before inserting check already existing data in database - mysql

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");
}

Related

Delete row from database through Servlet

I had a problem in my servlet regarding deleting record from my database.
Please look over my servlet code and please do correct me. Thank you in advance
DeleteRow servlet is working perfectly right when a single ID is given manually.
Scenario is:
ManageSinger.java servlet displays the records in database along with a "Delete" hyperLink in every row. But problem is whenever i try to press delete button.. it receives a null value for ID in deleterow.java servlet ..
Please guide me from here how can only that corresponding ID can be pass to another servlet.
ManageSinger.java
package com.ea.servlet;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
public class ManageSinger extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 1L;
public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException {
PrintWriter out = res.getWriter();
res.setContentType("text/html");
out.println("<html><body>");
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/EATWO","root","");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("select * from singerdetails");
out.println("<form method = \"post\">");
out.println("<table border=1 width=50% height=50%>");
out.println("<tr><th align=\"center\">Singer Name</th><th align=\"center\">StageName</th><th align=\"center\">Language</th><th></th><tr>");
while (rs.next()) {
String singername = rs.getString("singername");
String stagename = rs.getString("stagename");
String language = rs.getString("language");
String id = rs.getString("userID");
HttpSession session = req.getSession(true);
session.setAttribute("userID",id);
out.println("<tr><td align=\"center\">" + singername + "</td><td align=\"center\">" + stagename + "</td><td align=\"center\">" + language + "</td><td align=\"center\">Delete</td></tr>");
}
out.println("</table>");
out.println("</form");
out.println("</body></html>");
con.close();
}
catch (Exception e) {
e.printStackTrace();
}finally{
}
}
}
DeleteRow.java
package com.ea.servlet;
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 java.sql.SQLException;
import javax.jws.Oneway;
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 javax.servlet.http.HttpSession;
public class DeleteRow extends HttpServlet
{
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws IOException, ServletException
{
res.setContentType("text/html");
PrintWriter pw = res.getWriter();
Connection con;
PreparedStatement st;
ResultSet rs;
try
{
HttpSession session = req.getSession(true);
Class.forName("com.mysql.jdbc.Driver");
String id = (String) session.getAttribute("id");
System.out.println(id);
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/EATWO","root","");
st= con.prepareStatement("delete from singerdetails where userID = ?");
st.setString(1, id);
st.executeUpdate();
int i = st.executeUpdate();
if(i!=0)
pw.println("Deleting row...");
else if (i==0)
{
pw.println("<br>Row has been deleted successfully.");
}
}
catch(SQLException sx)
{
pw.println(sx);
}
catch(ClassNotFoundException cx)
{
pw.println(cx);
}
}
}
In DeleteRow.java say you should do String id = (String) session.getAttribute("userID"); instead of (String) session.getAttribute("id") .In ManageSinger.java you are setting the attribute as follows session.setAttribute("userID",id);
As per your current ManageSinger.java only the last userID gets set in session, which is why the last userID gets deleted. In ManageSinger.java instead of setting the userID as session attribute you can set it as url parameter for each record.
Following lists the changes:
//HttpSession session = req.getSession(true);
//session.setAttribute("userID",id);
out.println("<tr><td align=\"center\">" + singername + "</td><td align=\"center\">" + stagename + "</td><td align=\"center\">" + language + "</td><td align=\"center\">Delete</td></tr>");
In DeleteRow.java instead of getting the userID from session, you can get it from the url as following:
//HttpSession session = req.getSession(true);
//String id = (String) session.getAttribute("id");
String id = req.getParameter("userID").toString();

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

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

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....

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.

Access to MySQL using Java Servlet?

The Solution:
I added this code
Class.forName("com.mysql.jdbc.Driver");
brfore
Connection con = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/test", "root", "root");
Thank you all for reply my question
====================
I have problem, I try to insert data into mysql db using servlet, but I couldn'y access to MySQL
Database name: test
Table name: test
I already added jdbc connector to the project library
I'm using JDK 1.7, NetBeans 7.3, MySQL 5.6, Tomcat 7.0, Connector/J 5.1.24
1- this is "form action" in sign_up.jsp page:
<form action="RegisterUser" method="post">
<td><input type="submit" value="Submit"></td>
</form>
2- this is RegisterUser.java servlet:
import java.io.IOException;
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 com.mysql.jdbc.Driver;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;
#WebServlet(urlPatterns = {"/RegisterUser"})
public class RegisterUser extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException, SQLException {
try{
Connection con = DriverManager.getConnection("jdbc:mysql://localhost/test", "root", "root");
Statement s = (Statement) con.createStatement();
String name = "Hassan3";
int phone = 123456;
String insert = "INSERT INTO test VALUES ('\" + name + \"', \" + phone + \")";
s.executeUpdate(insert);
s.close();
con.close();
}catch(Exception e){
throw new SecurityException("Class not found " + e.toString());
}
}
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
processRequest(request, response);
} catch (SQLException ex) {
Logger.getLogger(RegisterUser.class.getName()).log(Level.SEVERE, null, ex);
}
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
processRequest(request, response);
} catch (SQLException ex) {
Logger.getLogger(RegisterUser.class.getName()).log(Level.SEVERE, null, ex);
}
}
#Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
3- the exception result:
HTTP Status 500 - Class not found java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost/test
type Exception report
message Class not found java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost/test
description The server encountered an internal error that prevented it from fulfilling this request.
exception
java.lang.SecurityException: Class not found java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost/test
RegisterUser.processRequest(RegisterUser.java:66)
RegisterUser.doPost(RegisterUser.java:173)
javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
note The full stack trace of the root cause is available in the Apache Tomcat/7.0.39 logs.
4- But when I use same code but in java file "without servlet or web app" it's working correctly:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
public class Test {
public static void main(String[] args){
try{
Connection con = DriverManager.getConnection("jdbc:mysql://localhost/test", "root", "root");
Statement s = (Statement) con.createStatement();
String name = "Hassan4";
int phone = 8985895;
String insert = "INSERT INTO test VALUES ('" + name + "', " + phone + ")";
s.executeUpdate(insert);
s.close();
con.close();
System.out.println("done");
}catch(Exception e){
throw new SecurityException("Class not found " + e.toString());
}
}
}
so what is problem with servlet? Why the code works with java app. but it doesn't work with web app.?
You are getting Class not found java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost/test
It means When you are running it from Web Application, JRE could not find Class in the Classpath.
If this code works in your Standalone it means you need to have a JAR file somewhere containing com.mysql.jdbc.Driver class (so called JDBC driver). This JAR needs to be visible in Tomcat. So, I would suggest placing mysql-jdbc.jar at a physical location to /WEB-INF/lib directory of your project.
Alternatively, you can add Third party libraries like JDBC driver here using
Right Click Project Name--> Properties
from your NetBeans IDE
Then restarting Tomcat should work.
Second, you don't need
import com.mysql.jdbc.Driver;
in your Servlet.
David is right and i want to add, you can also install the driver by pasting the jar file in the the installation folder of java.
\Program Files\Java\jre7\lib\ext
Well i dont like mysql very much and always use Mssql with a windows server 2008. This is the code i use for that, i might be your answer since mysql connection works pretty much the same as sql.
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
conn = DriverManager.getConnection("jdbc:sqlserver://localhost:1433;databaseName="+database+";user="+user+";password="+password);
First, you should put that into a persistance layer.
1) Ensure that your JDBC driver is in place. Copy it into your classpath, e.g. /WEB-INF/lib directory. Link: MySQL JDBC Driver Download Page
2) Check your connect string: jdbc:mysql://<server>:<port>/<database>, looks like the port is missing. Try jdbc:mysql://127.0.0.1:3306/test