Simple CRUD Using Jsp, Servlet and MySQL

You can view and download the complete source code of this tutorial from my github account.

In this tutorial, we will create a simple CRUD (Create Read Update Delete) User Management Web Application using Jsp, Servlet and MySQL.

For this tutorial, we will need the following tools: (The older or newer version should also works). Moreover, basic Java knowledge is assumed.

1. Eclipse IDE for Java EE Developers (Indigo – ver. 3.7)

2. Apache Tomcat ver 7.0

3. MySQL Community Server and MySQL Workbench (GUI Tool)

4. MySQL Connector for Java

5. jstl.jar and standard.jar. You can get these jars from your Tomcat. Check in this directory : (your tomcat directory)—>apache-tomcat-7.0.26-windows-x86—>apache-tomcat-7.0.26—>webapps—>examples—>WEB-INF—>lib

I will tell you where you should put these jars later.

6. jQuery for javascript capability. In this case, we only use it for the datepicker component


First, lets create the database and table for User using the following SQL scripts:

create database UserDB;
use UserDB;
grant all on UserDB.* to 'admin'@'localhost' identified by 'test'; 

CREATE TABLE UserDB.`users` (
  `userid` int(11) NOT NULL AUTO_INCREMENT,
  `firstname` varchar(45) DEFAULT NULL,
  `lastname` varchar(45) DEFAULT NULL,
  `dob` date DEFAULT NULL,
  `email` varchar(100) DEFAULT NULL,
  PRIMARY KEY (`userid`)
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8

Go to eclipse. Before we create a new project for our application, we need to setup the server. Select File—>New—>Other. From the tree, Select Server.

Choose Apache—>Tomcat v7.0 Server and set the runtime environment.

Next, create a new project. Select File—>New—>Dynamic Web Project.

Enter “SimpleJspServletDB” as the project name. Select target runtime to Apache Tomcat v7.0 which we already setup before. Click Finish.

Please refer to this project directory in case you miss something along the way

directory

Copy the standard.jar, mysql-connector jar and jstl jar to WEB-INF—>lib folder.

Create four packages in the src folder.

  • com.daniel.controller: contains the servlets
  • com.daniel.dao: contains the logic for database operation
  • com.daniel.model: contains the POJO (Plain Old Java Object). Each class in this package represents the database table. For this tutorial, however, we only have one table.
  • com.daniel.util : contains the class for initiating database connection

Next, create a new Java class. in com.daniel.model folder. Name it “User.java” and insert these following codes. Each of the variables in this class represents the field in USERS table in our database.

package com.daniel.model;

import java.util.Date;

public class User {

    private int userid;
    private String firstName;
    private String lastName;
    private Date dob;
    private String email;
    public int getUserid() {
        return userid;
    }
    public void setUserid(int userid) {
        this.userid = userid;
    }
    public String getFirstName() {
        return firstName;
    }
    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }
    public String getLastName() {
        return lastName;
    }
    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
    public Date getDob() {
        return dob;
    }
    public void setDob(Date dob) {
        this.dob = dob;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
    @Override
    public String toString() {
        return "User [userid=" + userid + ", firstName=" + firstName
                + ", lastName=" + lastName + ", dob=" + dob + ", email="
                + email + "]";
    }    
}

Create a new class in com.daniel.util package and name it DbUtil.java. This class handles the database connection to our MySQL server. In this class, we read a .properties file which contains the information necessary for the connection.

package com.daniel.util;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

public class DbUtil {

    private static Connection connection = null;

    public static Connection getConnection() {
        if (connection != null)
            return connection;
        else {
            try {
                Properties prop = new Properties();
                InputStream inputStream = DbUtil.class.getClassLoader().getResourceAsStream("/db.properties");
                prop.load(inputStream);
                String driver = prop.getProperty("driver");
                String url = prop.getProperty("url");
                String user = prop.getProperty("user");
                String password = prop.getProperty("password");
                Class.forName(driver);
                connection = DriverManager.getConnection(url, user, password);
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            } catch (SQLException e) {
                e.printStackTrace();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return connection;
        }

    }
}

Create the properties file directly under the src folder. Create a new file, name it db.properties. Put the following information inside.

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/UserDB
user=admin
password=test

Next, create a new class in com.daniel.dao package, name it UserDao.java. Dao stands for Data Access Object. It contains the logic for  database operation.

package com.daniel.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import com.daniel.model.User;
import com.daniel.util.DbUtil;

public class UserDao {

    private Connection connection;

    public UserDao() {
        connection = DbUtil.getConnection();
    }

    public void addUser(User user) {
        try {
            PreparedStatement preparedStatement = connection
                    .prepareStatement("insert into users(firstname,lastname,dob,email) values (?, ?, ?, ? )");
            // Parameters start with 1
            preparedStatement.setString(1, user.getFirstName());
            preparedStatement.setString(2, user.getLastName());
            preparedStatement.setDate(3, new java.sql.Date(user.getDob().getTime()));
            preparedStatement.setString(4, user.getEmail());
            preparedStatement.executeUpdate();

        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public void deleteUser(int userId) {
        try {
            PreparedStatement preparedStatement = connection
                    .prepareStatement("delete from users where userid=?");
            // Parameters start with 1
            preparedStatement.setInt(1, userId);
            preparedStatement.executeUpdate();

        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public void updateUser(User user) {
        try {
            PreparedStatement preparedStatement = connection
                    .prepareStatement("update users set firstname=?, lastname=?, dob=?, email=?" +
                            "where userid=?");
            // Parameters start with 1
            preparedStatement.setString(1, user.getFirstName());
            preparedStatement.setString(2, user.getLastName());
            preparedStatement.setDate(3, new java.sql.Date(user.getDob().getTime()));
            preparedStatement.setString(4, user.getEmail());
            preparedStatement.setInt(5, user.getUserid());
            preparedStatement.executeUpdate();

        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public List<User> getAllUsers() {
        List<User> users = new ArrayList<User>();
        try {
            Statement statement = connection.createStatement();
            ResultSet rs = statement.executeQuery("select * from users");
            while (rs.next()) {
                User user = new User();
                user.setUserid(rs.getInt("userid"));
                user.setFirstName(rs.getString("firstname"));
                user.setLastName(rs.getString("lastname"));
                user.setDob(rs.getDate("dob"));
                user.setEmail(rs.getString("email"));
                users.add(user);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return users;
    }

    public User getUserById(int userId) {
        User user = new User();
        try {
            PreparedStatement preparedStatement = connection.
                    prepareStatement("select * from users where userid=?");
            preparedStatement.setInt(1, userId);
            ResultSet rs = preparedStatement.executeQuery();

            if (rs.next()) {
                user.setUserid(rs.getInt("userid"));
                user.setFirstName(rs.getString("firstname"));
                user.setLastName(rs.getString("lastname"));
                user.setDob(rs.getDate("dob"));
                user.setEmail(rs.getString("email"));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return user;
    }
}

Finally, create a new Servlet inside the com.daniel.controller package and name it UserController.java

package com.daniel.controller;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.daniel.dao.UserDao;
import com.daniel.model.User;

public class UserController extends HttpServlet {
    private static final long serialVersionUID = 1L;
    private static String INSERT_OR_EDIT = "/user.jsp";
    private static String LIST_USER = "/listUser.jsp";
    private UserDao dao;

    public UserController() {
        super();
        dao = new UserDao();
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String forward="";
        String action = request.getParameter("action");

        if (action.equalsIgnoreCase("delete")){
            int userId = Integer.parseInt(request.getParameter("userId"));
            dao.deleteUser(userId);
            forward = LIST_USER;
            request.setAttribute("users", dao.getAllUsers());    
        } else if (action.equalsIgnoreCase("edit")){
            forward = INSERT_OR_EDIT;
            int userId = Integer.parseInt(request.getParameter("userId"));
            User user = dao.getUserById(userId);
            request.setAttribute("user", user);
        } else if (action.equalsIgnoreCase("listUser")){
            forward = LIST_USER;
            request.setAttribute("users", dao.getAllUsers());
        } else {
            forward = INSERT_OR_EDIT;
        }

        RequestDispatcher view = request.getRequestDispatcher(forward);
        view.forward(request, response);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        User user = new User();
        user.setFirstName(request.getParameter("firstName"));
        user.setLastName(request.getParameter("lastName"));
        try {
            Date dob = new SimpleDateFormat("MM/dd/yyyy").parse(request.getParameter("dob"));
            user.setDob(dob);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        user.setEmail(request.getParameter("email"));
        String userid = request.getParameter("userid");
        if(userid == null || userid.isEmpty())
        {
            dao.addUser(user);
        }
        else
        {
            user.setUserid(Integer.parseInt(userid));
            dao.updateUser(user);
        }
        RequestDispatcher view = request.getRequestDispatcher(LIST_USER);
        request.setAttribute("users", dao.getAllUsers());
        view.forward(request, response);
    }
}

Now, it’s time for us to create the jsp, the view for our application. Under the WebContent folder, create a jsp file, name it index.jsp

<%@ page language="java" contentType="text/html; charset=EUC-KR" pageEncoding="EUC-KR"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<title>Insert title here</title>
</head>
<body>
<jsp:forward page="/UserController?action=listUser" />
</body>
</html>

This jsp serves as the entry point for our application. In this case, it will redirect the request to our servlet to list all the users in the database.

Next, create the jsp to list all the users in the WebContent folder. Name it listUser.jsp

<%@ page language="java" contentType="text/html; charset=EUC-KR" pageEncoding="EUC-KR"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<title>Show All Users</title>
</head>
<body>
    <table border=1>
        <thead>
            <tr>
                <th>User Id</th>
                <th>First Name</th>
                <th>Last Name</th>
                <th>DOB</th>
                <th>Email</th>
                <th colspan=2>Action</th>
            </tr>
        </thead>
        <tbody>
            <c:forEach items="${users}" var="user">
                <tr>
                    <td><c:out value="${user.userid}" /></td>
                    <td><c:out value="${user.firstName}" /></td>
                    <td><c:out value="${user.lastName}" /></td>
                    <td><fmt:formatDate pattern="yyyy-MMM-dd" value="${user.dob}" /></td>
                    <td><c:out value="${user.email}" /></td>
                    <td><a href="UserController?action=edit&userId=<c:out value="${user.userid}"/>">Update</a></td>
                    <td><a href="UserController?action=delete&userId=<c:out value="${user.userid}"/>">Delete</a></td>
                </tr>
            </c:forEach>
        </tbody>
    </table>
    <p><a href="UserController?action=insert">Add User</a></p>
</body>
</html>

In this jsp, we use JSTL to connect between the jsp and the servlet. We should refrain from using scriplet inside the jsp because it will make the jsp more difficult to maintain. Not to mention it will make the jsp looks ugly.

Next, create a new jsp in WebContent folder and name it user.jsp

<%@ page language="java" contentType="text/html; charset=EUC-KR" pageEncoding="EUC-KR"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<link type="text/css"
    href="css/ui-lightness/jquery-ui-1.8.18.custom.css" rel="stylesheet" />
<script type="text/javascript" src="js/jquery-1.7.1.min.js"></script>
<script type="text/javascript" src="js/jquery-ui-1.8.18.custom.min.js"></script>
<title>Add new user</title>
</head>
<body>
    <script>
        $(function() {
            $('input[name=dob]').datepicker();
        });
    </script>

    <form method="POST" action='UserController' name="frmAddUser">
        User ID : <input type="text" readonly="readonly" name="userid"
            value="<c:out value="${user.userid}" />" /> <br /> 
        First Name : <input
            type="text" name="firstName"
            value="<c:out value="${user.firstName}" />" /> <br /> 
        Last Name : <input
            type="text" name="lastName"
            value="<c:out value="${user.lastName}" />" /> <br /> 
        DOB : <input
            type="text" name="dob"
            value="<fmt:formatDate pattern="MM/dd/yyyy" value="${user.dob}" />" /> <br /> 
        Email : <input type="text" name="email"
            value="<c:out value="${user.email}" />" /> <br /> <input
            type="submit" value="Submit" />
    </form>
</body>
</html>

Lastly, check the web.xml file located in WebContent—>WEB-INF folder in your project structure. Make sure it looks like this

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>SimpleJspServletDB</display-name>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
  <servlet>
    <description></description>
    <display-name>UserController</display-name>
    <servlet-name>UserController</servlet-name>
    <servlet-class>com.daniel.controller.UserController</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>UserController</servlet-name>
    <url-pattern>/UserController</url-pattern>
  </servlet-mapping>
</web-app>

That is it. Right click the project name and run it using Run As–>Run on server option.

usermgt
About these ads

124 thoughts on “Simple CRUD Using Jsp, Servlet and MySQL

  1. stvflyer says:

    Hi I am trying to run your example and I am getting The requested resource (/SimpleJspServletDB/listUser.jsp) is not available. I have the listUser.jsp in the WebContent folder so I am not sure why its not seeing it.

    • stvflyer says:

      Its all good got it working! Thanks for the very clear example! Finally I found one on the web. Thank you!

      • reyan says:

        What did you do men I also encounter an error ?

        HTTP Status 404 – /SimpleJspServletDB/

        ——————————————————————————–

        type Status report

        message /SimpleJspServletDB/

        description The requested resource is not available.

        ——————————————————————————–

        Apache Tomcat/7.0.35

      • Ghous Khan says:

        Check your user.jsp,listUser.jsp and index.jsp files they must be under the WebContent folder

      • gui_gofu says:

        thanks, that project was very useful.
        about the error message, in my case was the configuration of the libraries. In the project check:
        java resources>libraries>JRE System Library>right click>properties and choose the jre that you have installed in your system, it is jre7 in my case.

    • Kiran says:

      I am also having the same problem.Only thing i done is I kept all jsp files in folder named ‘jsp’.My tomcat is not starting now. It is unable to start up.I attempted by putting all code as it is. pls suggest me what should i do??

    • What did you do with this error ?

      type Exception report

      message An exception occurred processing JSP page /index.jsp at line 9

      description The server encountered an internal error that prevented it from fulfilling this request.

      exception

      org.apache.jasper.JasperException: An exception occurred processing JSP page /index.jsp at line 9

      6: Insert title here
      7:
      8:
      9:
      10:
      11:

  2. Travis says:

    How do you do this part?

    First, lets create the database and table for User using the following SQL scripts:

    create database UserDB;
    use UserDB;
    grant all on UserDB.* to ‘admin’@’localhost’ identified by ‘test’;

    CREATE TABLE UserDB.`users` (
    `userid` int(11) NOT NULL AUTO_INCREMENT,
    `firstname` varchar(45) DEFAULT NULL,
    `lastname` varchar(45) DEFAULT NULL,
    `dob` date DEFAULT NULL,
    `email` varchar(100) DEFAULT NULL,
    PRIMARY KEY (`userid`)
    ) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8

    never used a script before, the rest the tutorial is super simple but I got lost right here

  3. omya says:

    hey, I try to implement your code..
    I try to save some datas,
    after I debug it, I realize that the code through catch(SqlException e){}
    my datas unable to save to database..
    What does the SqlException means ?
    How can I fix this?

    • Deval Dholariya says:

      i have same Error :

      HTTP Status 404 – /SimpleJspServletDB/UserController>action=listuser

      ——————————————————————————–

      type Status report

      message /SimpleJspServletDB/UserController>action=listuser

      description The requested resource (/SimpleJspServletDB/UserController>action=listuser) is not available.

      ——————————————————————————–

      so please give me a solution of that Error :

  4. sangram panda says:

    Thanks dude………………………………
    nice tutorial and u explain it very clearly.

    all files are loosely coupled also.
    thanks again

  5. Hello, thanks for your tutorials.
    But i want to ask, how do you manage an application in folders? I confused manage url in Servlet, because my application’s view i put in folders spearately.

    Thank you

  6. Thank you! This really helped me get my head around Java servlets and Tomcat implementation. Was able to get a sample up and running that provides a good basis going forward.

  7. rahul says:

    package com.daniel.controller;

    import java.io.IOException;

    import java.text.ParseException;
    import java.text.SimpleDateFormat;
    import java.util.Date;

    import javax.servlet.RequestDispatcher ;//errors m getting
    import javax.servlet.ServletException; ;//errors m getting
    import javax.servlet.http.HttpServlet; ;//errors m getting
    import javax.servlet.http.HttpServletRequest; ;//errors m getting
    import javax.servlet.http.HttpServletResponse; ;//errors m getting

    import com.daniel.dao.UserDao;
    import com.daniel.model.User;

    public class UserController extends HttpServlet {
    private static final long serialVersionUID = 1L;
    private static String INSERT_OR_EDIT = “/user.jsp”;
    private static String LIST_USER = “/listUser.jsp”;
    private UserDao dao;

    public UserController() {
    super();
    dao = new UserDao();
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException,

  8. rahul says:

    If i have to add search functionality by user id then how togo for it

    I have used the same code that has been used for delete.
    and i have forward that to search.jsp and in this the code is same ajust as list users.jsp

    and also how to make the build file
    plz suggest

  9. rank says:

    Hi when i execute this code i am got an error as

    HTTP Status 500 –

    ——————————————————————————–

    type Exception report

    message

    description The server encountered an internal error () that prevented it from fulfilling this request.

    exception

    org.apache.jasper.JasperException: An exception occurred processing JSP page /index.jsp at line 10

    7: Insert title here
    8:
    9:
    10:
    11:
    12:

    Stacktrace:
    org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:553)
    org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:457)
    org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:391)
    org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:722)

    root cause

    java.lang.NullPointerException
    com.daniel.dao.UserDao.getAllUsers(UserDao.java:69)
    com.daniel.controller.UserController.doGet(UserController.java:63)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
    org.apache.jasper.runtime.PageContextImpl.doForward(PageContextImpl.java:745)
    org.apache.jasper.runtime.PageContextImpl.forward(PageContextImpl.java:716)
    org.apache.jsp.index_jsp._jspService(index_jsp.java:63)
    org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
    org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:419)
    org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:391)
    org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:722)

    note The full stack trace of the root cause is available in the Apache Tomcat/7.0.12 logs.

    ——————————————————————————–
    Please tell me the solutions
    Thanks in Advance

  10. Pochomaz says:

    Hi! if i have two or more “model” classes.. how many servlets are neccessary? one for each class? Like UserController, Class2Controller… ClassNController OR One BIIIG controller to handle all the classes.. Thank you for the tutorial, it is excellent!! sorry for my english!

    • if the operations are complex, best to use one servlet for each model, but if it is simple and the model always interact together, you can use one big controller. whichever suits your taste. after all you are the one who will develop it.

  11. russel says:

    Hi,
    I’ve been able to run your great example, but I’ve troubles setting the correct date format in the JSP user.jsp:

    the pattern defined is ignored and the listUser show the DOB as yyyy-MM-dd. I really cannot understand what’s wrong.

    Thanks

  12. KJohn says:

    This is an excellent tutorial, however you must have made some changes to the User class, and did not update the other classes. The data members of User are all ‘private’, and in listUser and user.jsp, you try to reference these directly:

    This fails and throws a null pointer exception. (HTTP Error 500 returned).

    These need to say:

    • KJohn says:

      Dang, the code got stripped. If you look in listUser.jsp, when you have value = user.userid, that will fail. It needs to use the get method of the User class: value = user.getUserid().

    • KJohn says:

      Nevermind! (I’m sure most can tell that I’m still learning this stuff!)
      The errors were due to my dynamic web project using Servlet 3.0, whereas your project (since it includes web.xml) is using 2.5.
      There are probably other minor configs that differ (how you use the JSTL) that can cause the HTTP 500 error.

      Fun stuff!

  13. ricky says:

    Good tutorial..but i find one bug in listuser when i refresh the page list row is go on adding with the previous result.Please tell me how to fix it.

    Thanks,

  14. KJohn says:

    This package will work on your local machine as you start/stop your server, but it will not work when deployed to a server which stays up, and database queries are not performed within 8 hours (or whatever your MySQL timeout is set to). The Connection object you instantiated will be closed, but will not be null, and the queries will fail.
    Need to check:
    connection.isClosed() and connection.isValid() before you attempt to perform queries; if those fail, you need to create a new connection.

    Or, use a DataSource Object (with PooledConnections) instead of DriverManager to create your Connection.

  15. Hi, very nice tuto.Ii have a trouble someone can show how or where to download the jstl.jar and the standar.jar. Since i looked on web but i can’t find them. Thx

    • ossevangelist says:

      All files are availabe at github, as also mentioned by the writer in this very first line of this tutorial. Writer has also provided the link.

      “You can view and download the complete source code of this tutorial from my github account.”

    • ossevangelist says:

      All the source files are available at github as mentioned by writer at the very first line of this tutorial. Writer has also provided the link in the second line.

      Pls let me know if you have any issue.

  16. Neha says:

    Hi,
    After adding all the files to respected directories i ma getting error in jsp pages listUser.jsp and user.jsp where the following to lines are not ecognsed.

    i have added the jstljar and standard.jas files to WebContent->WEB-INF->lib directory

    please help me.
    Thanks
    NehaLBK

      • Neha says:

        Hi,
        The example is working fine. Grate tutorial. But i need a example to upload any file(.doc,.pdf,.jpg etc) to oracle database Clob data type, and display it back in the same format when needed. I tried many examples but they upload only images or .txt files and display is in binay format. Please can you help me?
        Thanks in advance.

  17. Neha says:

    The uri’s are as follows which are not recognzed

    taglib uri=”http://java.sun.com/jsp/jstl/core” prefix=”c”
    taglib uri=”http://java.sun.com/jsp/jstl/fmt” prefix=”fmt”

  18. Deval Dholariya says:

    i have process as per given code furthere if give problem to me.
    I cant show user List on jsp page.

    Not give any Error and bugs. it also pass listarray and show in consol but i can show in table and i can not insert a new data. please give me a solution.

  19. Deval Dholariya says:

    i got this error :

    org.apache.jasper.JasperException: An exception occurred processing JSP page /listUser.jsp at line 33

    30:
    31:
    32:
    33:
    34:
    35:
    36:

    Stacktrace:
    org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:553)
    org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:457)
    org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:391)
    org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
    com.d.controller.UserController.doPost(UserController.java:121)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:641)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:722)

  20. suresh says:

    Hi,
    I am using the same code. I got this exception in server startup time…

    javax.servlet.ServletException: Wrapper cannot find servlet class com.daniel.controller.UserController or a class it depends on
    org.apache.jasper.runtime.PageContextImpl.doForward(PageContextImpl.java:706)
    org.apache.jasper.runtime.PageContextImpl.forward(PageContextImpl.java:677)
    org.apache.jsp.index_jsp._jspService(index_jsp.java:68)
    org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
    org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:374)
    org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:342)
    org.apache.jasper.servlet.JspServlet.service(JspServlet.java:267)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:717)

    Can any one help me..

    Cheers,
    Suresh

  21. Mas bro, kodingan ente ga bisa di input, terus ada yang salah parameter tuh…
    seharusnya “string”.equalsIgnoreCase(action)
    yang di controller…

    entah kenapa

  22. payal says:

    Hello KJohn,
    Awesome tutotrial, Thanks for your efforts. I am getting this error… “javax.el.PropertyNotFoundException: The class ‘com.daniel.model.User’ does not have the property ‘getUserid’. I have tried everything . My program loads in my weblogic server but when I insert a new user and try to submit..thats where I am getting this error. I would appreciate if you can please help me .
    I already added the get Userid in ListUser as you have mentioned earlier…that is not helping either.

    I would appreciate hearing back from you.

    thanks.

  23. Flemes says:

    Hi, there

    I have been trying your tutorial, but server is always returning the error below:

    java.lang.NullPointerException
    at com.entera.user.dao.UserDao.getAllUsers(UserDao.java:74)

    As if connection was not being created. But I was unable figure it out. Can you help me?

    Best regards,

    Flemes

  24. steve says:

    is there a way to do the project without using an IDE? [for 30+ years i've done it the text editor and love it.]

  25. Roman says:

    thanks for greate tutorial. it works perfectly. but I faced some problems when tried to add jquery libs via maven so I decided to remove ‘date of birth’ (dob) field and all references to it from data base table, jsp pages, UserDao.java and User.java.

  26. Dev says:

    HTTP Status 503 – Servlet UserController is currently unavailable

    type Status report

    messageServlet UserController is currently unavailable

    descriptionThe requested service (Servlet UserController is currently unavailable) is not currently available.
    GlassFish Server Open Source Edition 3.1.1

  27. Dev says:

    Same Time 1st Error..(I m suing netbens)
    HTTP Status 500 -

    type Exception report

    message

    descriptionThe server encountered an internal error () that prevented it from fulfilling this request.

    exception

    javax.servlet.ServletException: PWC1392: Error instantiating servlet class com.daniel.controller.UserController

    root cause

    com.sun.enterprise.container.common.spi.util.InjectionException: Error creating managed object for class: class com.daniel.controller.UserController

    root cause

    java.lang.reflect.InvocationTargetException

    root cause

    java.lang.NullPointerException

    note The full stack traces of the exception and its root causes are available in the GlassFish Server Open Source Edition 3.1.1 logs.
    GlassFish Server Open Source Edition 3.1.1

    2nd When I build —
    Deleting directory D:\Java project\Example\SimpleJspServletDB\build
    D:\Java project\Example\SimpleJspServletDB\nbproject\build-impl.xml:1054: Unable to delete file D:\Java project\Example\SimpleJspServletDB\build\web\WEB-INF\lib\jstl.jar
    BUILD FAILED (total time: 3 seconds)

  28. Kiran says:

    I am also having the same problem.Only thing i done is I kept all jsp files in folder named ‘jsp’.My tomcat is not starting now. It is unable to start up.I attempted by putting all code as it is. pls suggest me what should i do??

  29. Hi ,I have problem in UserContorl and this is the exception:

    18:44:41,446 INFO [org.jboss.as.server.deployment] (MSC service thread 1-7) JBAS015876: Starting deployment of “SimpleJspServletDB.war”
    18:44:41,486 WARN [org.jboss.as.ee] (MSC service thread 1-2) JBAS011006: Not installing optional component com.controller.UserController due to exception: java.lang.ClassNotFoundException: com.controller.UserController from [Module "deployment.SimpleJspServletDB.war:main" from Service Module Loader]
    at org.jboss.modules.ModuleClassLoader.findClass(ModuleClassLoader.java:190) [jboss-modules.jar:1.1.1.GA]
    at org.jboss.modules.ConcurrentClassLoader.performLoadClassUnchecked(ConcurrentClassLoader.java:468) [jboss-modules.jar:1.1.1.GA]
    at org.jboss.modules.ConcurrentClassLoader.performLoadClassChecked(ConcurrentClassLoader.java:456) [jboss-modules.jar:1.1.1.GA]
    at org.jboss.modules.ConcurrentClassLoader.performLoadClassChecked(ConcurrentClassLoader.java:423) [jboss-modules.jar:1.1.1.GA]
    at org.jboss.modules.ConcurrentClassLoader.performLoadClass(ConcurrentClassLoader.java:398) [jboss-modules.jar:1.1.1.GA]
    at org.jboss.modules.ConcurrentClassLoader.loadClass(ConcurrentClassLoader.java:120) [jboss-modules.jar:1.1.1.GA]
    at java.lang.Class.forName0(Native Method) [rt.jar:1.6.0_33]
    at java.lang.Class.forName(Class.java:247) [rt.jar:1.6.0_33]
    at org.jboss.as.server.deployment.reflect.DeploymentClassIndex.classIndex(DeploymentClassIndex.java:54) [jboss-as-server-7.1.1.Final.jar:7.1.1.Final]
    at org.jboss.as.ee.component.deployers.EEModuleConfigurationProcessor.deploy(EEModuleConfigurationProcessor.java:79)
    at org.jboss.as.server.deployment.DeploymentUnitPhaseService.start(DeploymentUnitPhaseService.java:113) [jboss-as-server-7.1.1.Final.jar:7.1.1.Final]
    at org.jboss.msc.service.ServiceControllerImpl$StartTask.startService(ServiceControllerImpl.java:1811) [jboss-msc-1.0.2.GA.jar:1.0.2.GA]
    at org.jboss.msc.service.ServiceControllerImpl$StartTask.run(ServiceControllerImpl.java:1746) [jboss-msc-1.0.2.GA.jar:1.0.2.GA]
    at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886) [rt.jar:1.6.0_33]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908) [rt.jar:1.6.0_33]
    at java.lang.Thread.run(Thread.java:662) [rt.jar:1.6.0_33]

  30. andy says:

    but for now you will get “side effect” after submiting new user. thats why it is better use redirect instead of request dispatcher.

  31. Hi All,
    we got this exception please help me what i made mistake here.
    //http://localhost:9989/SimpleJspServletDB/ when i tryed this url.

    SEVERE: Servlet.service() for servlet UserController threw exception
    java.lang.NullPointerException
    at com.daniel.dao.UserDao.getAllUsers(UserDao.java:71)
    at com.daniel.controller.UserController.doGet(UserController.java:44)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:617)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:646)

  32. Alonso says:

    Gracias, me ha ayudado mucho en mis estudios. Y lo verdaderamente increíble es que ha funcionado a la primera.

    Thanks, it helped me a lot in my studies. And the truly amazing thing is that it worked the first time.

  33. Lech says:

    You might also mention that one should put jQuery libraries into WebContent/js folder. At first I didn’t even recognize that something is wrong. I was putting the date manually and wondering what this jQuery snippet is used for? ;-)
    And the better way might be using absolute directories e.g.

    Nevertheless it is truly awesome tutorial for beginners! Very big THANKS! :-)

  34. Stephen Mogg says:

    Hi, and thanks so much for this great tutorial. I am using these principles in a small project which has several related tables. When listing data for some object, I would like to include descriptor information from a related table, and example would be if your user tables had a company_id, I would want to display company_name from a related table (company, primary key on company_id).

    I can see a few ways of doing this, but see problems with all of them.

    1. change the sql of the getuser functions include company information via a join, and populate necessare elements in the object (duplicate and cross dependancies in code)

    2. change the user object to include a company object, and then do a getCompanyById for each user in the resultset (processing intensive).

    3. a bastardisation of the two, using a join query to return user and company information and using the same results set to create user and related company objects (company object would not neccessarily be complete).

    Perhaps I am completed on the wrong track. Can someone tell me the best way to proceed,

    Regards
    Stephen

  35. Hi, i got this error, can you fix it please.

    HTTP Status 503 – Servlet UserController is currently unavailable

    type Status report

    message Servlet UserController is currently unavailable

    description The requested service is not currently available.

  36. and sometimes i also find this error.

    HTTP Status 500 – javax.servlet.ServletException: Error instantiating servlet class com.daniel.controller.UserController

    type Exception report

    message javax.servlet.ServletException: Error instantiating servlet class com.daniel.controller.UserController

    description The server encountered an internal error that prevented it from fulfilling this request.

    exception

    org.apache.jasper.JasperException: javax.servlet.ServletException: Error instantiating servlet class com.daniel.controller.UserController
    org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:549)
    org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:455)
    org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
    org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)

  37. Hi, when I try to run my project it seems ok, but when i clik button submit the page directly go to here :

    HTTP Status 500 -

    type Exception report

    message

    description The server encountered an internal error that prevented it from fulfilling this request.

    exception

    java.lang.NullPointerException
    net.roseindia.dao.UserDao.getAllUsers(UserDao.java:75)
    net.roseindia.handler.UserHandler.doGet(UserHandler.java:76)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:617)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:723)
    org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:393)

    please help me..
    thanks

  38. Please help, I got this error:

    type Exception report

    message An exception occurred processing JSP page /index.jsp at line 9

    description The server encountered an internal error that prevented it from fulfilling this request.

    exception

    org.apache.jasper.JasperException: An exception occurred processing JSP page /index.jsp at line 9

    6: Insert title here
    7:
    8:
    9:
    10:
    11:

  39. Hi, update and delete is working but for add it’s not. I got this error. Please Help. Thank you!

    java.lang.NullPointerException
    com.daniel.dao.UserDao.addUser(UserDao.java:28)
    com.daniel.controller.UserController.doPost(UserController.java:67)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:51)

  40. Krishna says:

    I got this problem. I am sure I get help with it because many people have successfully run it.

    HTTP Status 500 – An exception occurred processing JSP page /index.jsp at line 9

    ——————————————————————————–

    type Exception report

    message An exception occurred processing JSP page /index.jsp at line 9

    description The server encountered an internal error that prevented it from fulfilling this request.

    exception

    org.apache.jasper.JasperException: An exception occurred processing JSP page /index.jsp at line 9

    6: Insert title here
    7:
    8:
    9:
    10:
    11:

    Stacktrace:
    org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:568)
    org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:470)
    org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
    org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)

    root cause

    java.lang.NullPointerException
    com.daniel.dao.UserDao.getAllUsers(UserDao.java:71)
    com.daniel.controller.UserController.doGet(UserController.java:44)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:620)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    org.apache.jasper.runtime.PageContextImpl.doForward(PageContextImpl.java:750)
    org.apache.jasper.runtime.PageContextImpl.forward(PageContextImpl.java:720)
    org.apache.jsp.index_jsp._jspService(index_jsp.java:71)
    org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
    org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:432)
    org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
    org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)

  41. Krishna says:

    I have found a root cause of the above problem myself. I will give the answer as well. It’s pretty simple but unless we knot it’s hard.

    Problem: Driver could not be loaded (that I found by putting System.out.println logging statement in many places in DbUtil.java file)

    Solution: Placed JDBC driver inside lib folder of the web app directory (download from internet and copy and paste)

    When I put the JDBC driver in the java build path (right click the web app root directory > build path > configure build path), it did not work. It has to be put under the specific web directory.

  42. Michele.T says:

    Hi, thank you very much for your tutorial. I have a question: how can I handle mora tables? If I have 3 tables, how I handle Controllers and pages with forward???
    Thak you

  43. Dinesh Reddy says:

    HTTP Status 404 – /facultymange/UserController

    ——————————————————————————–

    type Status report

    message /facultymange/UserController

    description The requested resource is not available.

    ——————————————————————————–

    Apache Tomcat/6.0.39

    can u fix it

  44. Mario says:

    http://localhost:8080/SimpleJspServletDB/

    Estado HTTP 503 – Servlet UserController is currently unavailable

    How to fix this error? cause i import this project in Eclipse EE (Kepler) and inside the UserController.java i have error in the imports:

    import java.io.IOException;
    import java.text.ParseException;
    import java.text.SimpleDateFormat;
    import java.util.Date;

    And in this line:
    public class UserController extends HttpServlet {
    Show me this error:
    The hierarchy of the type UserController is inconsistent

    What can I Do?

  45. how can i catch exception in public void addUser(User user) (for example if query returns an error) ?

    if there is an error, it simply return to Users List without printin the exception
    i want see every error that comes…

    for the rest, very usefull post for newbie like me

    thanks

  46. Alex says:

    Hello,

    The tutorial seems great and it’s exactly what I was looking for :-D

    Howerver, I am trying to get it to work on JBoss 5 instead of Tomcat. I have followed the intructions, without any modifications.

    When I run the servlet, I get the following error:

    2014-06-17 14:33:15,106 INFO [org.apache.catalina.core.ContainerBase.[jboss.web].[localhost].[/SimpleJspServletDB]] (http-127.0.0.1-8080-2) Marking servlet UserController as unavailable

    2014-06-17 14:33:15,106 ERROR [org.apache.catalina.core.ContainerBase.[jboss.web].[localhost].[/SimpleJspServletDB].[UserController]] (http-127.0.0.1-8080-2) Excepción de reserva de espacio para servlet UserController [NOTE: i THINK THIS IS THE SAME AS
    "UnavailableException"]
    java.lang.NullPointerException
    at java.util.Properties$LineReader.readLine(Unknown Source)
    at java.util.Properties.load0(Unknown Source)
    at java.util.Properties.load(Unknown Source)
    at com.daniel.util.DbUtil.getConnection(DbUtil.java:21)
    at com.daniel.dao.UserDao.(UserDao.java:18)
    at com.daniel.controller.UserController.(UserController.java:25)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
    at java.lang.reflect.Constructor.newInstance(Unknown Source)
    at java.lang.Class.newInstance(Unknown Source)
    at org.jboss.web.tomcat.service.TomcatInjectionContainer.newInstance(TomcatInjectionContainer.java:264)
    at org.jboss.web.tomcat.service.TomcatInjectionContainer.newInstance(TomcatInjectionContainer.java:256)
    at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1006)
    at org.apache.catalina.core.StandardWrapper.allocate(StandardWrapper.java:777)
    at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:607)
    at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:444)
    at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:382)
    at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:310)
    at org.apache.jasper.runtime.PageContextImpl.doForward(PageContextImpl.java:696)
    at org.apache.jasper.runtime.PageContextImpl.forward(PageContextImpl.java:667)
    at org.apache.jsp.index_jsp._jspService(index_jsp.java:62)
    at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
    at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:369)
    at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:322)
    at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:249)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.jboss.web.tomcat.filters.ReplyHeaderFilter.doFilter(ReplyHeaderFilter.java:96)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:235)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
    at org.jboss.web.tomcat.security.SecurityAssociationValve.invoke(SecurityAssociationValve.java:190)
    at org.jboss.web.tomcat.security.JaccContextValve.invoke(JaccContextValve.java:92)
    at org.jboss.web.tomcat.security.SecurityContextEstablishmentValve.process(SecurityContextEstablishmentValve.java:126)
    at org.jboss.web.tomcat.security.SecurityContextEstablishmentValve.invoke(SecurityContextEstablishmentValve.java:70)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
    at org.jboss.web.tomcat.service.jca.CachedConnectionValve.invoke(CachedConnectionValve.java:158)
    at org.bonitasoft.console.security.SessionFixationValve.invoke(SessionFixationValve.java:77)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:330)
    at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:829)
    at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:598)
    at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:447)
    at java.lang.Thread.run(Unknown Source)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s