JSP Servlet JDBC MySQL CRUD Example Tutorial


In this tutorial, we are building a simple User Management web application that manages a collection of users with the basic feature: list, insert, update, delete (or CURD operations - Create, Update, Read and Delete).
You can download the source code of this tutorial from my GitHub repository and the link is given at the end of this tutorial.

Top JSP, Servlet and JDBC Tutorials:
Check out Build Todo App using JSP, Servlet, JDBC, and MySQL

Video Tutorial

This tutorial explained very well in below youtube video. Subscribe to our youtube channel for more future video updates.
We will develop below simple basic features in our User Management web application:
  1. Create a User
  2. Update a User
  3. Delete a User
  4. Retrieve a User
  5. List of all Users
The application looks something like this:

Tools and technologies used

  • JSP - 2.2 +
  • IDE - STS/Eclipse Neon.3
  • JDK - 1.8 or later
  • Apache Tomcat - 8.5
  • JSTL - 1.2.1
  • Servlet API - 2.5
  • MySQL - mysql-connector-java-8.0.13.jar

Development Steps

  1. Create an Eclipse Dynamic Web Project
  2. Add Dependencies
  3. Project Structure
  4. MySQL Database Setup
  5. Create a JavaBean - User.java
  6. Create a UserDAO.java
  7. Create a UserServlet.java
  8. Creating User Listing JSP Page - user-list.jsp
  9. Create a User Form JSP Page - user-form.jsp
  10. Creating Error JSP page
  11. Deploying and Testing the Application Demo

Class Diagram

Here is the class diagram of the User Management web application that we are going to develop in this tutorial:

1. Create an Eclipse Dynamic Web Project

To create a new dynamic Web project in Eclipse:
1. On the main menu select File > New > Project....
2. In the upcoming wizard choose Web > Dynamic Web Project.


3. Click Next.
4. Enter project name as "jsp-servlet-jdbc-mysql-example";
5. Make sure that the target runtime is set to Apache Tomcat with the currently supported version. 

2. Add Dependencies

Add the latest release of below jar files to the lib folder.
  • jsp-api.2.3.1.jar
  • servlet-api.2.3.jar
  • mysql-connector-java-8.0.13.jar
  • jstl-1.2.jar

3. Project Structure

Standard project structure for your reference - 

4. MySQL Database Setup

Let's create a database named "demo" in MySQL. Now, create a users table using below DDL script:
CREATE DATABASE 'demo';
USE demo;

create table users (
 id  int(3) NOT NULL AUTO_INCREMENT,
 name varchar(120) NOT NULL,
 email varchar(220) NOT NULL,
 country varchar(120),
 PRIMARY KEY (id)
);
You can use either MySQL Command Line Client or MySQL Workbench tool to create the database. The above a users table looks like:

5. Create a JavaBean - User.java

Let's create a User java class to model a user entity in the database with the following code:
package net.javaguides.usermanagement.model;

/**
 * User.java
 * This is a model class represents a User entity
 * @author Ramesh Fadatare
 *
 */
public class User {
    protected int id;
    protected String name;
    protected String email;
    protected String country;

    public User() {}

    public User(String name, String email, String country) {
        super();
        this.name = name;
        this.email = email;
        this.country = country;
    }

    public User(int id, String name, String email, String country) {
        super();
        this.id = id;
        this.name = name;
        this.email = email;
        this.country = country;
    }

    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
    public String getCountry() {
        return country;
    }
    public void setCountry(String country) {
        this.country = country;
    }
}

6. Create a UserDAO.java

Let's create a UserDAO class which is a Data Access Layer (DAO) class that provides CRUD (Create, Read, Update, Delete) operations for the table users in a database. Here’s the full source code of the UserDAO:
package net.javaguides.usermanagement.dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import net.javaguides.usermanagement.model.User;

/**
 * AbstractDAO.java This DAO class provides CRUD database operations for the
 * table users in the database.
 * 
 * @author Ramesh Fadatare
 *
 */
public class UserDAO {
    private String jdbcURL = "jdbc:mysql://localhost:3306/demo?useSSL=false";
    private String jdbcUsername = "root";
    private String jdbcPassword = "root";

    private static final String INSERT_USERS_SQL = "INSERT INTO users" + "  (name, email, country) VALUES " +
        " (?, ?, ?);";

    private static final String SELECT_USER_BY_ID = "select id,name,email,country from users where id =?";
    private static final String SELECT_ALL_USERS = "select * from users";
    private static final String DELETE_USERS_SQL = "delete from users where id = ?;";
    private static final String UPDATE_USERS_SQL = "update users set name = ?,email= ?, country =? where id = ?;";

    public UserDAO() {}

    protected Connection getConnection() {
        Connection connection = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            connection = DriverManager.getConnection(jdbcURL, jdbcUsername, jdbcPassword);
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return connection;
    }

    public void insertUser(User user) throws SQLException {
        System.out.println(INSERT_USERS_SQL);
        // try-with-resource statement will auto close the connection.
        try (Connection connection = getConnection(); PreparedStatement preparedStatement = connection.prepareStatement(INSERT_USERS_SQL)) {
            preparedStatement.setString(1, user.getName());
            preparedStatement.setString(2, user.getEmail());
            preparedStatement.setString(3, user.getCountry());
            System.out.println(preparedStatement);
            preparedStatement.executeUpdate();
        } catch (SQLException e) {
            printSQLException(e);
        }
    }

    public User selectUser(int id) {
        User user = null;
        // Step 1: Establishing a Connection
        try (Connection connection = getConnection();
            // Step 2:Create a statement using connection object
            PreparedStatement preparedStatement = connection.prepareStatement(SELECT_USER_BY_ID);) {
            preparedStatement.setInt(1, id);
            System.out.println(preparedStatement);
            // Step 3: Execute the query or update query
            ResultSet rs = preparedStatement.executeQuery();

            // Step 4: Process the ResultSet object.
            while (rs.next()) {
                String name = rs.getString("name");
                String email = rs.getString("email");
                String country = rs.getString("country");
                user = new User(id, name, email, country);
            }
        } catch (SQLException e) {
            printSQLException(e);
        }
        return user;
    }

    public List < User > selectAllUsers() {

        // using try-with-resources to avoid closing resources (boiler plate code)
        List < User > users = new ArrayList < > ();
        // Step 1: Establishing a Connection
        try (Connection connection = getConnection();

            // Step 2:Create a statement using connection object
            PreparedStatement preparedStatement = connection.prepareStatement(SELECT_ALL_USERS);) {
            System.out.println(preparedStatement);
            // Step 3: Execute the query or update query
            ResultSet rs = preparedStatement.executeQuery();

            // Step 4: Process the ResultSet object.
            while (rs.next()) {
                int id = rs.getInt("id");
                String name = rs.getString("name");
                String email = rs.getString("email");
                String country = rs.getString("country");
                users.add(new User(id, name, email, country));
            }
        } catch (SQLException e) {
            printSQLException(e);
        }
        return users;
    }

    public boolean deleteUser(int id) throws SQLException {
        boolean rowDeleted;
        try (Connection connection = getConnection(); PreparedStatement statement = connection.prepareStatement(DELETE_USERS_SQL);) {
            statement.setInt(1, id);
            rowDeleted = statement.executeUpdate() > 0;
        }
        return rowDeleted;
    }

    public boolean updateUser(User user) throws SQLException {
        boolean rowUpdated;
        try (Connection connection = getConnection(); PreparedStatement statement = connection.prepareStatement(UPDATE_USERS_SQL);) {
            statement.setString(1, user.getName());
            statement.setString(2, user.getEmail());
            statement.setString(3, user.getCountry());
            statement.setInt(4, user.getId());

            rowUpdated = statement.executeUpdate() > 0;
        }
        return rowUpdated;
    }

    private void printSQLException(SQLException ex) {
        for (Throwable e: ex) {
            if (e instanceof SQLException) {
                e.printStackTrace(System.err);
                System.err.println("SQLState: " + ((SQLException) e).getSQLState());
                System.err.println("Error Code: " + ((SQLException) e).getErrorCode());
                System.err.println("Message: " + e.getMessage());
                Throwable t = ex.getCause();
                while (t != null) {
                    System.out.println("Cause: " + t);
                    t = t.getCause();
                }
            }
        }
    }
}

7. Create a UserServlet.java

Now, let's create UserServlet that acts as a page controller to handle all requests from the client. Let’s look at the code first:
package net.javaguides.usermanagement.web;

import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

import javax.servlet.RequestDispatcher;
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 net.javaguides.usermanagement.dao.UserDAO;
import net.javaguides.usermanagement.model.User;

/**
 * ControllerServlet.java
 * This servlet acts as a page controller for the application, handling all
 * requests from the user.
 * @email Ramesh Fadatare
 */

@WebServlet("/")
public class UserServlet extends HttpServlet {
    private static final long serialVersionUID = 1 L;
    private UserDAO userDAO;

    public void init() {
        userDAO = new UserDAO();
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        doGet(request, response);
    }

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

        try {
            switch (action) {
                case "/new":
                    showNewForm(request, response);
                    break;
                case "/insert":
                    insertUser(request, response);
                    break;
                case "/delete":
                    deleteUser(request, response);
                    break;
                case "/edit":
                    showEditForm(request, response);
                    break;
                case "/update":
                    updateUser(request, response);
                    break;
                default:
                    listUser(request, response);
                    break;
            }
        } catch (SQLException ex) {
            throw new ServletException(ex);
        }
    }

    private void listUser(HttpServletRequest request, HttpServletResponse response)
    throws SQLException, IOException, ServletException {
        List < User > listUser = userDAO.selectAllUsers();
        request.setAttribute("listUser", listUser);
        RequestDispatcher dispatcher = request.getRequestDispatcher("user-list.jsp");
        dispatcher.forward(request, response);
    }

    private void showNewForm(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        RequestDispatcher dispatcher = request.getRequestDispatcher("user-form.jsp");
        dispatcher.forward(request, response);
    }

    private void showEditForm(HttpServletRequest request, HttpServletResponse response)
    throws SQLException, ServletException, IOException {
        int id = Integer.parseInt(request.getParameter("id"));
        User existingUser = userDAO.selectUser(id);
        RequestDispatcher dispatcher = request.getRequestDispatcher("user-form.jsp");
        request.setAttribute("user", existingUser);
        dispatcher.forward(request, response);

    }

    private void insertUser(HttpServletRequest request, HttpServletResponse response)
    throws SQLException, IOException {
        String name = request.getParameter("name");
        String email = request.getParameter("email");
        String country = request.getParameter("country");
        User newUser = new User(name, email, country);
        userDAO.insertUser(newUser);
        response.sendRedirect("list");
    }

    private void updateUser(HttpServletRequest request, HttpServletResponse response)
    throws SQLException, IOException {
        int id = Integer.parseInt(request.getParameter("id"));
        String name = request.getParameter("name");
        String email = request.getParameter("email");
        String country = request.getParameter("country");

        User book = new User(id, name, email, country);
        userDAO.updateUser(book);
        response.sendRedirect("list");
    }

    private void deleteUser(HttpServletRequest request, HttpServletResponse response)
    throws SQLException, IOException {
        int id = Integer.parseInt(request.getParameter("id"));
        userDAO.deleteUser(id);
        response.sendRedirect("list");

    }
}

8. Creating User Listing JSP Page - user-list.jsp

Next, create a JSP page for displaying all users from the database. Let's create a list-user.jsp page under the WebContent directory in the project with the following code:
<%@ page language="java" contentType="text/html; charset=UTF-8"
 pageEncoding="UTF-8"%>
    <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
        <html>

        <head>
            <title>User Management Application</title>
            <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
        </head>

        <body>

            <header>
                <nav class="navbar navbar-expand-md navbar-dark" style="background-color: tomato">
                    <div>
                        <a href="https://www.javaguides.net" class="navbar-brand"> User
     Management App </a>
                    </div>

                    <ul class="navbar-nav">
                        <li><a href="<%=request.getContextPath()%>/list" class="nav-link">Users</a></li>
                    </ul>
                </nav>
            </header>
            <br>

            <div class="row">
                <!-- <div class="alert alert-success" *ngIf='message'>{{message}}</div> -->

                <div class="container">
                    <h3 class="text-center">List of Users</h3>
                    <hr>
                    <div class="container text-left">

                        <a href="<%=request.getContextPath()%>/new" class="btn btn-success">Add
     New User</a>
                    </div>
                    <br>
                    <table class="table table-bordered">
                        <thead>
                            <tr>
                                <th>ID</th>
                                <th>Name</th>
                                <th>Email</th>
                                <th>Country</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <!--   for (Todo todo: todos) {  -->
                            <c:forEach var="user" items="${listUser}">

                                <tr>
                                    <td>
                                        <c:out value="${user.id}" />
                                    </td>
                                    <td>
                                        <c:out value="${user.name}" />
                                    </td>
                                    <td>
                                        <c:out value="${user.email}" />
                                    </td>
                                    <td>
                                        <c:out value="${user.country}" />
                                    </td>
                                    <td><a href="edit?id=<c:out value='${user.id}' />">Edit</a> &nbsp;&nbsp;&nbsp;&nbsp; <a href="delete?id=<c:out value='${user.id}' />">Delete</a></td>
                                </tr>
                            </c:forEach>
                            <!-- } -->
                        </tbody>

                    </table>
                </div>
            </div>
        </body>

        </html>
Once you will deploy above JSP page in tomcat and open in the browser looks something like this:

9. Create a User Form JSP Page - user-form.jsp

Next, we create a JSP page for creating a new User called user-form.jsp. Here’s its full source code:
<%@ page language="java" contentType="text/html; charset=UTF-8"
 pageEncoding="UTF-8"%>
    <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
        <html>

        <head>
            <title>User Management Application</title>
            <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
        </head>

        <body>

            <header>
                <nav class="navbar navbar-expand-md navbar-dark" style="background-color: tomato">
                    <div>
                        <a href="https://www.javaguides.net" class="navbar-brand"> User Management App </a>
                    </div>

                    <ul class="navbar-nav">
                        <li><a href="<%=request.getContextPath()%>/list" class="nav-link">Users</a></li>
                    </ul>
                </nav>
            </header>
            <br>
            <div class="container col-md-5">
                <div class="card">
                    <div class="card-body">
                        <c:if test="${user != null}">
                            <form action="update" method="post">
                        </c:if>
                        <c:if test="${user == null}">
                            <form action="insert" method="post">
                        </c:if>

                        <caption>
                            <h2>
                                <c:if test="${user != null}">
                                    Edit User
                                </c:if>
                                <c:if test="${user == null}">
                                    Add New User
                                </c:if>
                            </h2>
                        </caption>

                        <c:if test="${user != null}">
                            <input type="hidden" name="id" value="<c:out value='${user.id}' />" />
                        </c:if>

                        <fieldset class="form-group">
                            <label>User Name</label> <input type="text" value="<c:out value='${user.name}' />" class="form-control" name="name" required="required">
                        </fieldset>

                        <fieldset class="form-group">
                            <label>User Email</label> <input type="text" value="<c:out value='${user.email}' />" class="form-control" name="email">
                        </fieldset>

                        <fieldset class="form-group">
                            <label>User Country</label> <input type="text" value="<c:out value='${user.country}' />" class="form-control" name="country">
                        </fieldset>

                        <button type="submit" class="btn btn-success">Save</button>
                        </form>
                    </div>
                </div>
            </div>
        </body>

        </html>
Once you will deploy above JSP page in tomcat and open in the browser looks something like this:
The above page acts for both functionalities to create a new User and Edit the same user. The edit page looks like:

10. Creating Error JSP page

Here’s the code of the Error.jsp page which simply shows the exception message:
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8" isErrorPage="true" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
 "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Error</title>
</head>
<body>
 <center>
  <h1>Error</h1>
  <h2><%=exception.getMessage() %><br/> </h2>
 </center> 
</body>
</html>

11. Deploying and Testing the Application

It's time to see a demo of the above User Management web application. Deploy this web application in tomcat server. 
Type the following URL in your web browser to access the User Management application: http://localhost:8080/jsp-servlet-jdbc-mysql-crud-example/

Create a new User

Edit a User

List of all Users

GitHub Repository

Comments

  1. Excellent tutorial with step by step explanation. This blog website is recommended.

    ReplyDelete
  2. In the UserDao.java the method printSQLException the line "for (Throwable e: ex)" throws me an error that the variable e is already define in method printSQLException(SQLException)
    what could be the problem?

    ReplyDelete
    Replies
    1. In the userDao he is using an method to print the detailed exception. you can remove that method and use try-catch block in the every method where you are performing the database operation. I did that.

      try {
      // Step 2:Create a statement using connection object
      PreparedStatement ps = con.prepareStatement("select * from user where id=?");
      ps.setInt(1, id);
      System.out.println(ps);
      // Step 3: Execute the query or update query
      ResultSet rs = ps.executeQuery();

      // Step 4: Process the ResultSet object.
      while (rs.next())
      {
      String name = rs.getString("name");
      String email = rs.getString("email");
      String country = rs.getString("country");
      user = new User(id, name, email, country);
      }
      }catch (SQLException e) {e.printStackTrace();}
      return user;


      The code I have pasted doesn't require the printsqlexception() method.

      Delete
  3. In the user servlet why did you used the @WebServlet("/") annotation like ("/") and how it is able to perform it's tasks even without the servlet name in the annotation. I am little bit confuse about the working of this servlet plz explane me this part.

    ReplyDelete
    Replies
    1. Do watch video tutorial of this tutorial, everything explained over there. If you still have any doubt then let me know.

      Delete
    2. Hi Ramesh, this tutorial is excellent, the only thing where i am stuck is that I am trying to manage users as well as products in my application where I have followed the same way like you did, just the problem is I cannot redirect myself because of getServletPath() is always redirecting me to users not products.

      Delete
  4. Because @WebServlet is annotaion base servletConfiguration which means that any servlet request belongs to which servlet class. Its simple means we can ignore DeploymentDescipter file i.e web.xml.

    Before annotation base config we have to implicitly managed which request mapped to which servlet class with help of servelt name and url-pattern.

    In above code see
    String action = request.getServletPath();
    which type user will sent request then accoding to userRequset getServletPath() method set which action wants to perform by request , then perform some action.

    ReplyDelete
  5. Thanks for your reply ambesh, I do understand what you are trying to explain, but what if I have two servlet like UserServlet and ProductServlet, now how do I manage the request, because it never call Product servlet, directly it redirect me to UserServlet like http://localhost:8080/WoodenOnlineStore/new
    http://localhost:8080/WoodenOnlineStore/edit

    I want this request to call ProductServlet actions nor UserServlet actions, Please Help

    ReplyDelete
    Replies
    1. Excellent Tutorial !! I followed this to make a simple student management system with basic CRUD operations.

      I have a similar problem. I have three Servlets for Student, Faculty and Staff models respectively. I have to perform CRUD operations for all of these models. So, I have these URLS:
      http://localhost:8080/jsp_project/students/new
      http://localhost:8080/jsp_project/students/edit
      http://localhost:8080/jsp_project/students/delete
      http://localhost:8080/jsp_project/students/update
      http://localhost:8080/jsp_project/students/list

      and similarly all these URLs for the other two models.

      I have 3 separate servlets for these 3 models. I'm getting error "Resource not available" for these URLs.

      Can you please tell me what am I doing wrong here?

      Delete
    2. I am facing similar problem. First I am able to do CRUD in my category table as explained but when I am trying to do same in the another table currency_master/new it is showing "new" of category table

      Delete
  6. whenever i am running the project on tomcat server i am getting this error -

    HTTP Status 500 – Internal Server Error

    Type Exception Report

    Description The server encountered an unexpected condition that prevented it from fulfilling the request.

    Exception

    java.lang.NullPointerException
    studentmanagement.dao.StudentDAO.selectAllUsers(StudentDAO.java:98)
    studentmanagement.web.StudentServlet.listUser(StudentServlet.java:65)
    studentmanagement.web.StudentServlet.doGet(StudentServlet.java:55)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    Note The full stack trace of the root cause is available in the server logs.
    Kindly help to tell me what am I doing wrong.

    ReplyDelete
    Replies
    1. same Error is coming for me.. Did you correct the error.. if so can you share the code

      Delete
    2. Check your database connection. If database connection is not established then this exception occurs. Do watch the video tutorial for more information.

      Delete
    3. I used tomcat and it was showing connection established. Still this error occured.

      Delete
    4. You can create the NullPointerException throwable to replace the SQLException at selectAllUsers:

      catch (Throwable any) {
      System.out.println("We get the error: " +any);
      any.printStackTrace();

      Delete
    5. I did what you suggested. After that JSP pages are loading but when I am filling form for insert new user, new user is not showing on list of users.

      Delete
    6. Check for new user inserted in database table. If user record inserted in database table then same user should appear in the list on Web UI.

      Delete
    7. This happenned to me,,took me DAYS to track it down, found no answer,,FINALLY I got cute and played around with the @WebServlet("/"), ("list") in the Servlet annotations, be careful there you get conflicts. Hope that helps!

      Delete
  7. not working. Showing NullPointer Exception... i coppied every thing you said. but not working

    ReplyDelete
    Replies
    1. Check your database connection. If database connection is not established then this exception occurs. Do watch the video tutorial for more information.

      Delete
  8. am getting this message please help sir
    HTTP Status 404 – Not Found


    Type Status Report

    Message /jsp-servlet-jdbc-mysql-tutorial/user-list.jsp

    Description The origin server did not find a current representation for the target resource or is not willing to disclose that one exists.


    Apache Tomcat/9.0.34

    ReplyDelete
    Replies
    1. same error...please help

      Delete
    2. I am also facing same issue.
      While debugging I am getting value from database.
      But on browser am getting "HTTP Status 404 – Not Found" error as listed above I tried many things but it couldn't work.
      I have just update my DB connection based on my local system else all code are same.
      Please help me to resolve this issue.

      Delete
  9. Sir,

    I created two servlet one for user and for employee and deleted the name like this "@WebServlet("/")" and ran in the server it gives this error " Tomcat v8.5 Server at localhost failed to start. but if i give names two servlet like this,
    for employee - @WebServlet("/EmployeeServlet")
    for user - @WebServlet("/UserServlet")
    then the server ran well but the functioon are not working.

    pleases help me with this sir.

    ReplyDelete
    Replies
    1. How you access these servlets from browser. Paste links here

      Delete
    2. Thanks for your reply sir, I wrote the method like you showed in the video,

      String action = request.getServletPath();

      try {
      switch (action) {
      case "/new":
      showNewForm(request, response);
      break;
      case "/insert":
      insertUser(request, response);
      break;
      case "/delete":
      deleteUser(request, response);
      break;
      case "/edit":
      showEditForm(request, response);
      break;
      case "/update":
      updateUser(request, response);
      break;
      default:
      listUser(request, response);
      break;
      }
      } catch (SQLException ex) {
      throw new ServletException(ex);
      }
      }
      For employee and user both I gave like this i think thats why it's showing me error, can you suggest me a way to send all jsp servlet path to one servlet?

      Delete
    3. You can create all the actions like in this tutorial for employee and user in one servlet and implement these actions in JSP pages. Make sure that all the actions are unique.

      Delete
  10. Excellent tutorial, but am having this error each time I click on delete option
    Http 400 bad request
    The request could not be understood by the server due to malformed syntax.

    ReplyDelete
    Replies
    1. Check your delete request in JSP page and mapping with action in Servlet.

      Delete
  11. The data are not inserted. Every time I click on the SignUp button it says the resource file cannot be found.

    ReplyDelete
  12. Sir please help i do it in the same way as u did but i dont know what's wrong and where's the error ?

    public class Tourguide
    {
    private int id;
    private String guidername;
    private String age;
    private String email;
    private String contactnum;
    private String knownlanguage;
    private String year_experience;
    private String about;

    public Tourguide(int id, String guidername, String age, String email, String contactnum, String knownlanguage,
    String year_experience, String about) {
    super();
    this.id = id;
    this.guidername = guidername;
    this.age = age;
    this.email = email;
    this.contactnum = contactnum;
    this.knownlanguage = knownlanguage;
    this.year_experience = year_experience;
    this.about = about;
    }



    i input 7 those details but the output is only shown the first 3 details other 4 details didn't appear just empty box in the Database also only first 3 outputs other 4 didn't seem to be there. can u please help me sir

    ReplyDelete
  13. The answer by @BinhNguyen solves the null pointer. Then make sure your database connection username and password are correct. Nice tutorial.

    ReplyDelete
  14. hi sir for some reason the list user aint working

    ReplyDelete
  15. Hi Ramesh, This is an wonderful session, I was able to run both user-form page and user-list page, but when I give the entries and clicking on submit I am redirecting to a blank page though the details got populated in Database, please help me here.

    ReplyDelete
  16. Hi Ramesh, This is an wonderful session, I was able to run both user-form page and user-list page, but when I give the entries and clicking on submit I am redirecting to a blank page though the details got populated in Database, please help me here.

    ReplyDelete
  17. after using your code I am able to do crud operation on one table successfully. But when I copied the same code to do crud operation in another table and trying to run the second table's list.jsp it is showing first table s data. pls help

    ReplyDelete
  18. hello i am getting an HTTP Status 500 – Internal Server Error

    java.lang.NumberFormatException: For input string: " "
    java.lang.NumberFormatException.forInputString(Unknown Source)
    java.lang.Integer.parseInt(Unknown Source)
    java.lang.Integer.parseInt(Unknown Source)
    im not able to find why im getting this error

    ReplyDelete
    Replies
    1. Type Exception Report

      Description The server encountered an unexpected condition that prevented it from fulfilling the request.

      Exception
      java.lang.NullPointerException
      crud.dao.UserDAO.selectAllUsers(UserDAO.java:89)
      crud.web.UserServlet.listUser(UserServlet.java:70)
      crud.web.UserServlet.doGet(UserServlet.java:60)
      javax.servlet.http.HttpServlet.service(HttpServlet.java:626)
      javax.servlet.http.HttpServlet.service(HttpServlet.java:733)
      org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)


      Note The full stack trace of the root cause is available in the server logs.



      I am getting this error.. Advice me something to resolve this.

      Delete
  19. How to add a search and pagination to it?

    ReplyDelete
  20. i have a problem accessing the list javax.el.PropertyNotFoundException: Property not found on type, i even tried executing the class an the dao without the jsp and the servlet an tried displaying values of list but it gives me wrong information i neeed your help

    ReplyDelete
  21. java.lang.NoClassDefFoundError: org/apache/juli/logging/LogFactory
    at org.apache.catalina.core.StandardService.(StandardService.java:56)
    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.apache.catalina.startup.Bootstrap.init(Bootstrap.java:225)
    at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:410)
    Caused by: java.lang.ClassNotFoundException: org.apache.juli.logging.LogFactory
    at java.net.URLClassLoader.findClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    ... 8 more

    Hi,
    Getting this error while starting the Tomcat v5.5 Server, please help me to resolve the issue.

    ReplyDelete
  22. Hi i am having issue with css which i saved as style.css inside webcontent folder. I am using single servlet as above example

    ReplyDelete
  23. your project helped me a lot thanks.

    ReplyDelete
  24. hi please in the user-list.jsp i do get an internal server error

    ReplyDelete

Post a Comment

Leave Comment