my sql query error in servlet/jdbc ? inserting blob into database ..? - mysql

I am unable to insert the image of a user into a blob field through the following code:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.sql.*;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
/**
*
* #author SUKIRTI
*/
#WebServlet(urlPatterns = {"/imageupload"})
#MultipartConfig(maxFileSize = 16177215)
public class imageupload extends HttpServlet {
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
/* TODO output your page here. You may use following sample code. */
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet imageupload</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Servlet imageupload at " + request.getContextPath() + "</h1>");
out.println("</body>");
out.println("</html>");
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// processRequest(request, response);
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
InputStream inputStream = null;
Part filePart = request.getPart("photo");
if (filePart != null) {
// obtains input stream of the upload file
inputStream = filePart.getInputStream();
}
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/final_project?zeroDateTimeBehavior=convertToNull", "root", "madhumakhis");
String sql = "insert into signup(dp) values(?) where signup.name =" + request.getSession(false).getAttribute("uname")+";";
PreparedStatement statement = con.prepareStatement(sql);
if (inputStream != null) {
// fetches input stream of the upload file for the blob column
statement.setBlob(1, inputStream);
}
int row = statement.executeUpdate();
if (row > 0) {
out.println("image uploaded");
}
}catch(Exception e){out.println(e);}
}
/**
* Returns a short description of the servlet.
*
* #return a String containing servlet description
*/
#Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
It's showing the following error:
"com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'where signup.name =mummy' at line 1"
where mummy is the retrieved attribute("uname") ?
I am new in jsp/servlets so kindly explain what should I do to make it work.

There is no syntax insert into ...values .. where defined
looks like you want to update a column, so you have to use:
Update signup set dp =? where signup.name = ?
For more information about update syntax look in the official mysql documantation

Related

Hyperlink `<a>` not invoking a mapped Servlet. Returning 404: Resource not found [duplicate]

This question already has answers here:
Servlet returns "HTTP Status 404 The requested resource (/servlet) is not available"
(19 answers)
Closed 2 years ago.
What it says on the title. I'm trying to invoke a servlet to create a page when I click on a link. Attached below is the code.
HTML:
<html>
<head>
<title>NavBar</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="sheet.css">
</head>
<body>
<section class="ft_root">
<div class="ft">
<ul>
<li> 1 </li>
<li> 2 </li>
<li> 3 </li>
<li> 4 </li>
<li> 5 </li>
</ul>
</div>
</html>
Web.XML
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
<servlet>
<servlet-name>entry_page_gen</servlet-name>
<servlet-class>Servlets.entry_page_gen</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>entry_page_gen</servlet-name>
<url-pattern>/entry/*</url-pattern>
</servlet-mapping>
</web-app>
entry_page_gen.java
package Servlets;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
*
* #author oras
*/
#WebServlet(name = "entry_page_gen", urlPatterns = {"/entry/*"})
public class entry_page_gen extends HttpServlet {
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
/* TODO output your page here. You may use following sample code. */
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet entry_page_gen</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Servlet entry_page_gen at " + request.getContextPath() + "</h1>");
out.println("</body>");
out.println("</html>");
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* #return a String containing servlet description
*/
#Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
entry_page_gen.java is stored in a package called Servlets.
What's going wrong? If more information is needed, please ask. I didn't want to bog down the question with info that might not be needed.
A point to note is that if I change the Web.xml -> <servlet-mapping> -> <url-pattern> to /entry_page_gen and call the servlet from a <form> with the action parameter, everything works fine.
P.S: I referred to this question while creating the above pieces of code.
Well here is a solution for you.
entry_page_gen.java (By the way you should change this name to follow the java convention)
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//processRequest(request, response);
response.sendRedirect("hello.html");
return;
}
Configuration:
Output:
Notes:
In the image you are seeing the URL http://localhost:8080/web-project/hello.html because of the redirect in the method, but you can reach this element with: http://localhost:8080/web-project/entry
The explanation of the configuration could see here:
https://stackoverflow.com/a/26329628/1670134
As answered in here, the initial slash character refers to the path from the base URL (by default the domain name, unless changed with a <base> HTML element). So if your app URL is http://www.example.com/myapp, then an anchor 1 will refer to http://www.example.com/entry/test.html, therefore the servlet is not called.
You could change the anchor's href to this 1

before inserting check already existing data in database

Register.java
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
*
* #author srini
*/
#WebServlet(urlPatterns = {"/RegisterServlet"})
public class RegisterServlet extends HttpServlet {
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
public void doGet(HttpServletRequest request,HttpServletResponse response)
throws IOException,ServletException{
processRequset (request,response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequset (request,response);
}
#SuppressWarnings("unused")
public void processRequset(HttpServletRequest request,HttpServletResponse response)
throws IOException,ServletException{
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String phone =request.getParameter("phone");
String username =request.getParameter("uname");
String password =request.getParameter("pass");
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection(
"jdbc:mysql://localhost:3306/register","root","toor");
PreparedStatement pstmt=con.prepareStatement("select * from headwy where unmae=? " );
ResultSet rs = pstmt.executeQuery();
if(rs.next()==true)
{
out.print("username already exist");
}
else {
String insertquery = "insert into headwwy (phone,uname,pass) values(?,?,?)";
pstmt.executeQuery("insertquery");
pstmt.setString(1,phone);
pstmt.setString(2,username);
pstmt.setString(3,password);
out.print("You are successfully registered...");
pstmt.close();
con.close();
}
}
catch (Exception e2) {System.out.println(e2);
}
out.close();
}
}
I am trying to check the existing data in database and insert the record.In the above try to execute it shows the blank page.
before insert command is worked but we adding the select command its not working.
using the select command for the check the database and in case any data existing the database it shows the record is already exist ,please choose the another name.
In case of no duplicate data not found,insert command perform the action and insert the new record into the database and it shows the new record in to database successfully.
But my code is not working for the properly.
thank you.
You have mistake in your code :
PreparedStatement pstmt=con.prepareStatement("select * from headwy where unmae=? " );
check your column name its "uname" not "unmae".
There are multiple issues in your code. First there is a typo. If that is the reason for failure.
select * from headwy where unmae=?
insert into headwwy (phone,uname,pass) values(?,?,?)
Also
pstmt.executeQuery("insertquery");
should be executed after you have set the parameters
pstmt.setString(1,phone);
pstmt.setString(2,username);
pstmt.setString(3,password);
I'll recommend to go through JDBC tutorial and run again.
You should set the parameters in your preparedstatement before executing your preparedstatement.
PreparedStatement pstmt=con.prepareStatement("select * from headwy where unmae=? " );
pstmt.setString(1,username);
ResultSet rs = pstmt.executeQuery();
if(rs.next())
{
System.out.print("username already exist");
}

Encountering an error when uploading an image

I am trying to upload an image to my database using jsp. I want to store the image in a folder called Upload and want to insert the image name in the database. I used a servlet to do this.
I uses seperate pages for input, action and database connection and I explain the code below.
Photo.jsp
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body><form name="f" action="uploadimage" method="post" enctype="multipart/form-data">
<table>
<tr><td>
Name</td><td><input type="text" name="name"/></td></tr>
<tr><td> Address</td><td><textarea name="addr" rows="10" cols="10"></textarea></td></tr>
<tr> <td><input type="file" name="f1"></td></tr>
<tr><td colspan="2"><input type="submit" name="b1"></td></tr></table> </form>
</body>
</html>
My database connection is given below:
public int insert_file(String name, String addr, String img)
{
int i=0;
System.out.println("inside insert_file");
try
{
Connection con21=get_con();
System.out.print(con21);
Statement s21=con21.createStatement();
String s11="insert into image(name,addr,image) values ('"+name+"','"+addr+"','"+img+"')";
System.out.println("i"+s11);
i=s21.executeUpdate(s11);
System.out.println(i);
}
catch(Exception e)
{
System.out.println(e);
}
return i;
}
Here is my servlet page:
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.tomcat.util.http.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import DBConnection.MYConnection;
/**
*
* #author MONOOS
*/
#WebServlet(name = "uploadimage", urlPatterns = {"/uploadimage"})
public class uploadimage extends HttpServlet {
String name,addr,img;
//MYConnection obj=new MYConnection();
/**
* Processes requests for both HTTP
* <code>GET</code> and
* <code>POST</code> methods.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
MYConnection obj=new MYConnection();
out.println(obj);
out.println("haiiii");
try {
out.println("inside try");
System.out.print("inside try");
List fileItems;
// Parsing field values
DiskFileItemFactory factory = new DiskFileItemFactory();
out.println(factory);
factory.setSizeThreshold(10000000);
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
// maximum file size to be uploaded.
upload.setSizeMax(10000000);
try {
// Parse the request to get file items.
out.println("inside nested try");
fileItems = upload.parseRequest(request);
// Process the uploaded file items
Iterator i = fileItems.iterator();
out.println(i);
while (i.hasNext()) {
FileItem fi = (FileItem) i.next();
if (fi.isFormField()) {
if (fi.getFieldName().equals("name")) {
name = fi.getString();
out.println(name);;
System.out.println("name:"+name);
}
if (fi.getFieldName().equals("addr"))
{
addr = fi.getString();
System.out.println("address:"+addr);
out.println(addr);
}
}
else
{
out.println("inside else");
System.out.println("inside else");
img = fi.getName();
System.out.println("Image :"+img);
File outfile = new File("I:\\NetBeansProjects\\MGNREGA\\web\\Upload" + fi.getName());
fi.write(outfile);
}
}
int j=obj.insert_file("nayana","gfg",img);
System.out.println("j:" + j);
}
catch(Exception e)
{
System.out.print(e);
}
}
finally {
out.close();
}
}// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP
* <code>GET</code> method.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP
* <code>POST</code> method.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* #return a String containing servlet description
*/
#Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
My problem is that the code is running, but it does not do what I want. The first print statement in the try clause are printed successfully.
I resolve my problem... I change the package "import org.apache.tomcat.util.http.fileupload.FileItem;" into "import org.apache.commons.fileupload.FileItem;".
now it running well....

Issue in populating combobox using Json from postgresql in ExtJs and Servlets

In my Java EE web application there is a combobox in a form panel. I tried to populate this combobox from my postgresql database using JsonReader. I am using ExtJs 3.0 and JSP & Sevlets.
This is my ExtJs code segment for combobox and JsonReader.
var vehicleStore = new Ext.data.Store({
proxy : new Ext.data.HttpProxy({
url : "http://" + host + ":" + port + "/" + projectName + "/"
+ "DeliveryVehicle"
}),
reader : new Ext.data.JsonReader({
idProperty : 'vCode',
root : 'vehicles',
fields : [ {
name : 'vCode'
}, {
name : 'vRegNum'
} ]
}),
autoLoad : true
});
{
xtype : 'combo',
name : 'include_type',
fieldLabel : 'Delivery Vehicle',
emptyText : 'Delivery Vehicle',
editable : false,
hideLabel : true,
style : 'marginleft:10px',
displayField : 'vRegNum',
valueField : 'vCode',
store : vehicleStore,
flex : 1
}
And this is my DeliveryVehicle.java servlet.
package com.xontworld.ornox.Geotrack;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.xontworld.ornox.connection.ConnectionManager;
public class DeliveryVehicle extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public DeliveryVehicle() {
//super();
// TODO Auto-generated constructor stub
}
#Override
public void init() throws ServletException {
// TODO Auto-generated method stub
super.init();
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
processRequest(request, response);
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
processRequest(request, response);
}
protected void processRequest(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
ServletContext context = getServletContext();
String dbName = context.getInitParameter("ConnectionDB");
String connectionHost = context.getInitParameter("ConnectionHost");
String connectionUser = context.getInitParameter("ConnectionUser");
String connectionPassword = context.getInitParameter("ConnectionPassword");
String port = "5433";
Statement statement = null;
ResultSet vehicleResultSet = null;
Connection pgConnection = null;
String lineString = "";
try {
pgConnection = ConnectionManager.getPostgresConnection(
connectionHost, connectionUser, connectionPassword,
dbName, port);
out.println(connectionHost+","+ connectionUser+","+ connectionPassword+","+ dbName);
statement = pgConnection.createStatement();
out.print(pgConnection);
String sql = "";
sql = "select distinct vehiclecode, registrationnumber from hoobtvehicles v WHERE v.status='1'";
vehicleResultSet = statement.executeQuery(sql);
String jsonData = "{'vehicles':[";
while (vehicleResultSet.next()) {
jsonData += "{ 'vCode' : '";
jsonData += vehicleResultSet.getString(1).trim();
jsonData += "', ";
jsonData += "'vRegNum' : '";
jsonData += vehicleResultSet.getString(2).trim();
if (vehicleResultSet.isLast()) {
jsonData += "' } ";
} else {
jsonData += "' } , ";
}
}
jsonData += "]}";
out.print(jsonData);
} catch (Exception e) {
// TODO Auto-generated catch block
out.println(e.toString());
e.printStackTrace();
}
}
}
And this is my Json data.
{'vehicles':[{ 'vCode' : '1001', 'vRegNum' : 'XY-100-123' } , { 'vCode' : '1002', 'vRegNum' : 'GY-122-120' } , { 'vCode' : '1000000001', 'vRegNum' : 'XY-100-123' } ]}
The problem is it doesn't load the combobox and it doesn't even print anything in my eclipse console. And also it doesn't show any error message in firebug console. I use alert to check the size of the vehicleStore. It'a zero. Anyone has an idea what's going on here.
I would be much obliged if anyone please be so kind enough to explain what's wrong with my codes and how should I correct it?
Thanks a lot

Unable to get connection to mysql database in netbeans java web application

I am new to web development to java. I am writing this basic java web application that is going to store customer information into a database. I use the MVC-2 architecture. My Jsp sends a request to a servlet that in turn tries instatiates a bean an inserts that object into a database.
When i try to connect to the database (in debugging mode) the connection variable returns empty. So data cannot be inserted.
This is the class that makes connections to the db
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package customer;
import java.io.Serializable;
import java.sql.Connection;
import java.sql.DriverManager;
/**
*
* #author
*/
public class DatabaseOperations implements Serializable
{
private static Connection connection;
public DatabaseOperations()
{
try
{
String username = "root";
String password = "root";
String url = "jdbc:mysql://localhost/test";
Class.forName ("com.mysql.jdbc.Driver").newInstance();
connection = DriverManager.getConnection (url, username, password);
System.out.println("Database connection established");
}
catch(Exception e)
{
}
}
public static Connection getConnection()
{
return connection;
}
}
This is the method that adds a customer to the db
public void addCustomer(CustomerBean customer) throws SQLException {
DatabaseOperations db = new DatabaseOperations();
connection = DatabaseOperations.getConnection();
statement = connection.createStatement();
String query = "insert into customer (name, address, phone, email) "
+ "values (" + customer.name + ","
+ customer.address + ","
+ customer.phone + ","
+ customer.email + "," + ")";
statement.executeUpdate(query);
}
and finally this is the servlet where i call the method to add a customer
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package customer;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import customer.CustomerBean;
import javax.servlet.RequestDispatcher;
/**
*
* #author
*/
public class CustomerServlet extends HttpServlet {
/**
* Processes requests for both HTTP
* <code>GET</code> and
* <code>POST</code> methods.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
CustomerBean customer = new CustomerBean();
try {
out.println("tests");
customer.setName(request.getParameter("name"));
customer.setEmail(request.getParameter("email"));
customer.setAddress(request.getParameter("address"));
customer.setPhone(request.getParameter("phone"));
/************** ADD CUSTOMER TO DB HERE***********************/
customer.addCustomer(customer);
request.setAttribute("cust", customer);
request.getRequestDispatcher("/index.jsp").forward(request, response);
}
catch (Exception e)
{
e.printStackTrace();
}
}
First, I'd like to point out that your code is open to SQL injection. Personally, I'm a fan of procedures, so I'll recommend that: you should create a procedure in mysql to insert a new record, and then provide that sproc with the arguments (name, address, etc).
As for the problem at hand: After your statement.executeUpdate line, try closing the connection. Also, extract the Class.forName to your main method. It should only be executed once. Also, remove the .newInstance() off of that once you have done so.
If all that doesn't work, extract the entire connection out to a globally accessible static variable and do not assign to it more than once. See if your program works then. If not, you have a separate problem.