Home Jsp JSP CRUD Application
Questions:Ask|Latest


 
 

Share on Google+Share on Google+

JSP CRUD Application

Advertisement
This tutorial explains you how you can write CRUD application in JSP. CRUD means create, read, update and delete. This example explains you about all the steps in creating JSP CRUD application.

Create JSP CRUD Application and run on Tomcat 7

In this section we will discuss about how to create a simple crud application in JSP using Eclipse IDE. We will use Eclipse to compile and deploy the application on Tomcat 7 server.

CRUD is basically used in the context of database driven application where it Creates, Reads, Updates and Deletes the data of database. CRUD is also know as create, read, update and delete. The example given here will teach you how easily you can create application that insert, query, update and delete the data. Create means to insert a record into the database table, Update means edit/make changes into the existing record, and the Delete means deleting of record from the table. We can also create a CRUD application using JSP, Servlet, And the JDBC.

Example

Here we will create a CRUD application using Java Servlet, JSP, and the JDBC. We will understand here the basic purpose of creating a CRUD application by a registration form where the user will registered by providing the id, first name, and last name. Update/Edit their records, and can delete their record also. For this application we will required some front end interfaces for the registering a user and updating the record. For creating the interfaces I have created the JSP pages such as user.jsp page for adding new user this page contains a form and the respective input text fields for providing their information and the submit button as well as created edit.jsp page where the selected record's ID will be showed in the readonly textfield and the other textfields for updating the respective fields. Then I have created a Java Beans named UserBean.java which contains some data members (id, fName, lName) and their setter getter methods. These setter getter methods are used for setting and getting the corresponding value respectively. Then I have created a ConnectionProvider class to connect with the existing database (in my case I am using MySQL). Then I have created a DAO class where I have written the code for adding the user, editing the user record, deleting the user record, getting the all user record, and for getting user record by ID. Then I have created a Servlet where written the code to handle insert, edit, and delete records. Finally I have created a listUser.jsp page for displaying all records and the link for updating and deleting the records. In this application you can insert, edit, or delete application one by one.

Directory Structure for this application

Source Code

Create Database table

CREATE TABLE `users` (                   
          `userid` int(5) NOT NULL,              
          `firstname` varchar(20) DEFAULT NULL,  
          `lastname` varchar(20) DEFAULT NULL,   
          PRIMARY KEY (`userid`)                 
        )

UserBean.java

package net.roseindia.bean;

public class UserBean {

    private int id;
    private String fName;
    private String lName;
        
    
    public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getfName() {
		return fName;
	}
	public void setfName(String fName) {
		this.fName = fName;
	}
	public String getlName() {
		return lName;
	}
	public void setlName(String lName) {
		this.lName = lName;
	}	
}

ConnectionProvider.java

package net.roseindia.dbconnection;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class ConnectionProvider {

    private static Connection con = null;

    public static Connection getConnection() {
        if (con != null)
            return con;
        else {
            try {
                
                String driver = "com.mysql.jdbc.Driver";
                String url = "jdbc:mysql://localhost:3306/record";
                String user = "root";
                String password = "root";
                Class.forName(driver);
                con = DriverManager.getConnection(url, user, password);
            } catch (ClassNotFoundException cnfe) {
                System.out.println(cnfe);
            } catch (SQLException sqe) {
                System.out.println(sqe);
            } 
            return con;
        }

    }
}

UserDao.java

package net.roseindia.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 net.roseindia.bean.UserBean;
import net.roseindia.dbconnection.ConnectionProvider;

public class UserDao {

    private Connection conn;

    public UserDao() {
    	conn = ConnectionProvider.getConnection();
    }

    public void addUser(UserBean userBean) {
        try {
        	String sql = "INSERT INTO users(userid, firstname,lastname)" +
    		" VALUES (?, ?, ? )";
            PreparedStatement ps = conn.prepareStatement(sql);
            
            ps.setInt(1, userBean.getId());
            ps.setString(2, userBean.getfName());
            ps.setString(3, userBean.getlName());            
            ps.executeUpdate();

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

    public void removeUser(int userId) {
        try {
        	String sql = "DELETE FROM users WHERE userid=?";
            PreparedStatement ps = conn
                    .prepareStatement(sql);
            ps.setInt(1, userId);
            ps.executeUpdate();

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

    public void editUser(UserBean userBean) {    	
    	try {
    		String sql = "UPDATE users SET firstname=?, lastname=?" +
            " WHERE userid=?";
            PreparedStatement ps = conn
                    .prepareStatement(sql);
            ps.setString(1, userBean.getfName());
            ps.setString(2, userBean.getlName());            
            ps.setInt(3, userBean.getId());
            ps.executeUpdate();            

        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    
    public List getAllUsers() {
        List users = new ArrayList();
        try {
        	String sql = "SELECT * FROM users";
            PreparedStatement ps = conn.prepareStatement(sql);
            ResultSet rs = ps.executeQuery();
            while (rs.next()) {
                UserBean userBean = new UserBean();
                userBean.setId(rs.getInt("userid"));
                userBean.setfName(rs.getString("firstname"));
                userBean.setlName(rs.getString("lastname"));                             
                users.add(userBean);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return users;
    }

    public UserBean getUserById(int userId) {
    	UserBean userBean = new UserBean();
        try {
        	String sql = "SELECT * FROM users WHERE userid=?";
            PreparedStatement ps = conn.
                    prepareStatement(sql);
            ps.setInt(1, userId);
            ResultSet rs = ps.executeQuery();

            if (rs.next()) {
            	userBean.setId(rs.getInt("userid"));
            	userBean.setfName(rs.getString("firstname"));
            	userBean.setlName(rs.getString("lastname"));                           
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return userBean;
    }
}

UserHandler.java

package net.roseindia.handler;

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 net.roseindia.dao.UserDao;
import net.roseindia.bean.UserBean;

public class UserHandler extends HttpServlet {    
    private static String INSERT = "/user.jsp";
    private static String Edit = "/edit.jsp";
    private static String UserRecord = "/listUser.jsp";
    private UserDao dao;

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

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String redirect="";
        String uId = request.getParameter("userid");        
        String action = request.getParameter("action");
        if(!((uId)== null) && action.equalsIgnoreCase("insert"))
        {
        	int id = Integer.parseInt(uId);
        	UserBean user = new UserBean();
        	user.setId(id);
            user.setfName(request.getParameter("firstName"));
            user.setlName(request.getParameter("lastName"));
        	dao.addUser(user);
        	redirect = UserRecord;
            request.setAttribute("users", dao.getAllUsers());    
           	System.out.println("Record Added Successfully");
        }
        else if (action.equalsIgnoreCase("delete")){
            String userId = request.getParameter("userId");
            int uid = Integer.parseInt(userId);
            dao.removeUser(uid);
            redirect = UserRecord;
            request.setAttribute("users", dao.getAllUsers());
            System.out.println("Record Deleted Successfully");
        }else if (action.equalsIgnoreCase("editform")){        	
        	redirect = Edit;            
        } else if (action.equalsIgnoreCase("edit")){
        	String userId = request.getParameter("userId");
            int uid = Integer.parseInt(userId);            
            UserBean user = new UserBean();
        	user.setId(uid);
            user.setfName(request.getParameter("firstName"));
            user.setlName(request.getParameter("lastName"));
            dao.editUser(user);
            request.setAttribute("user", user);
            redirect = UserRecord;
            System.out.println("Record updated Successfully");
         } else if (action.equalsIgnoreCase("listUser")){
            redirect = UserRecord;
            request.setAttribute("users", dao.getAllUsers());
         } else {
            redirect = INSERT;
        }

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

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

user.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!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=ISO-8859-1">
<title>Add New User</title>
</head>
<body>
<form method="POST" action='UserHandler' name="frmAddUser"><input
type="hidden" name="action" value="insert" />
<p><b>Add New Record</b></p>
<table>
<tr>
<td>User ID</td>
<td><input type="text" name="userid" /></td>
</tr>
<tr>
<td>First Name</td>
<td><input type="text" name="firstName" /></td>
</tr>
<tr>
<td>Last Name</td>
<td><input type="text" name="lastName" /></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="Submit" /></td>
</tr>
</table>
</form>
<p><a href="UserHandler?action=listUser">View-All-Records</a></p>
</body>
</html>

edit.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%@ page import="net.roseindia.bean.UserBean"%>
<%@ page import="net.roseindia.dao.UserDao"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Edit User</title>
</head>
<body>
<%
UserBean user = new UserBean();
%>
<%
UserDao dao = new UserDao();
%>
<form method="POST" action='UserHandler' name="frmEditUser"><input
type="hidden" name="action" value="edit" /> <%
String uid = request.getParameter("userId");
if (!((uid) == null)) {
int id = Integer.parseInt(uid);
user = dao.getUserById(id);
%>
<table>
<tr>
<td>User ID</td>
<td><input type="text" name="userId" readonly="readonly"
value="<%=user.getId()%>"></td>
</tr>
<tr>
<td>First Name</td>
<td><input type="text" name="firstName" /></td>
</tr>
<tr>
<td>Last Name</td>
<td><input type="text" name="lastName" /></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="Update" /></td>
</tr>
</table>
<%
} else
out.println("ID Not Found");
%>
</form>
</body>
</html>

listUser.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%@ page import="net.roseindia.bean.UserBean"%>
<%@ page import="net.roseindia.dao.UserDao"%>
<%@ page import="java.util.*"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>All User</title>
</head>
<body>
<%
//UserBean user = new UserBean();
UserDao dao = new UserDao();
List<UserBean> userList = dao.getAllUsers();
//Iterator<UserBean> itr = userList.iterator();
%>
<table border="1">
<tr>
<th>Id</th>
<th>First Name</th>
<th>Last Name</th>
</tr>
<tr>
<%
/*while(itr.hasNext())
{
System.out.println(user.getId());*/
for (UserBean user : userList) {
%>
<td><%=user.getId()%></td>
<td><%=user.getfName()%></td>
<td><%=user.getlName()%></td>
<td><a
href="UserHandler?action=editform&userId=<%=user.getId()%>">Update</a></td>
<td><a
href="UserHandler?action=delete&userId=<%=user.getId()%>">Delete</a></td>

</tr>
<%
}
//}
%>
</table>
<p><a href="UserHandler?action=insert">Add User</a></p>
</body>
</html>

web.xml

<?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>jspServletJdbcExample</display-name>
<welcome-file-list>
<welcome-file>user.jsp</welcome-file>
</welcome-file-list>
<servlet>
<description></description>
<servlet-name>UserHandler</servlet-name>
<servlet-class>net.roseindia.handler.UserHandler</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>UserHandler</servlet-name>
<url-pattern>/UserHandler</url-pattern>
</servlet-mapping>
</web-app>

Output

When you will execute the above example you will get the output as follows :

1. Database table before inserting the record

2. After executing this example the user.jsp page will be opened from here you can insert the new record and view the record's available in the table.

3. After providing the fields value ( I have inserted two records) when you will click on the submit button, in the above image, the page will be forwarded to the listUser.jsp as follows :

In the above image you can see a hyperlink "Add User", this is for adding more new user as well as there are two more hyperlinks "Update" and "Delete" update is used for editing the existing record (discussed later) and the delete is used for deleting the existing record (discussed later).

And when you will see the database table you will see these two records are also added into the table as follows :

4. Updating record : When you will click on the hyperlink Update shown at the listUser.jsp page an interface for updating the corresponding record, such as I want to edit the record with user ID 1, will be opened as follows :

5. Here You can alter the record of user ID 1, such as I have changed the Last Name from Singh to Roy and keep the Deepak as it is then the output will be as follows :

And the database table after update will be look like as follows :

6. Now I want to delete the record with of User ID = 2 So, I have click on the hyperlink delete in the second row whose id is 2 the record is deleted and then after the remaining list is as follows :

And the database table will be look like as follows :

Download Source Code (WAR File)

After downloading this war file simply rename it to the jspServletJdbcExample and import it into your eclipse and run this example.

Advertisement

Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: January 22, 2013

Ask Questions?    Discuss: JSP CRUD Application  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments
Prag Tyagi
May 22, 2013
The code is throwing null pointer exception .

The code is throwing null pointer exception when clicking on the View-All records button . Exception :- java.lang.NullPointerException net.roseindia.dao.UserDao.getAllUsers(UserDao.java:71) net.roseindia.handler.UserHandler.doGet(UserHandler.java:66) javax.servlet.http.HttpServlet.service(HttpServlet.java:621) javax.servlet.http.HttpServlet.service(HttpServlet.java:722) Also the addition button is not working . There an error is coming :- java.lang.NullPointerException net.roseindia.dao.UserDao.addUser(UserDao.java:26) net.roseindia.handler.UserHandler.doGet(UserHandler.java:39) net.roseindia.handler.UserHandler.doPost(UserHandler.java:76) javax.servlet.http.HttpServlet.service(HttpServlet.java:641) javax.servlet.http.HttpServlet.service(HttpServlet.java:722) Please suggest me as soon as possible on these errors
miral
March 11, 2013
a question

Thanks, it was very helpful for beginners such as me but can you tell me how to control what the user writes in the textfields? I can do it with a javascript code but i prefer that it will be in a class model (because we are working with the mvc).
Fraise
March 10, 2013
re

Thanks, it is very helpful even if you have used the get method instead of the post method in the servlet class which is not very secure. But it is clear and simple.
pallavi
September 13, 2013
list not displaying

when i am adding the user i am not able to see the displayed result by using the same code. i am using oracle and all credentials have been set. there are no errors but once i add the msg of added successfully is displaying but not the list.
kavi
October 24, 2013
pls provide the solution for my error

after running my user.jsp file i got this error pls provide the solution 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 ConnectionProcess.UserDao.addUser(UserDao.java:29) HandlerProcess.UserHandler.doGet(UserHandler.java:41) HandlerProcess.UserHandler.doPost(UserHandler.java:87) javax.servlet.http.HttpServlet.service(HttpServlet.java:637) javax.servlet.http.HttpServlet.service(HttpServlet.java:717) note The full stack trace of the root cause is available in the Apache Tomcat/6.0.33 logs.
KAVI
October 24, 2013
pls provide the solutoion

after running the user.jsp i got this error ....pls provide the solution 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 ConnectionProcess.UserDao.addUser(UserDao.java:29) HandlerProcess.UserHandler.doGet(UserHandler.java:41) HandlerProcess.UserHandler.doPost(UserHandler.java:87) javax.servlet.http.HttpServlet.service(HttpServlet.java:637) javax.servlet.http.HttpServlet.service(HttpServlet.java:717) note The full stack trace of the root cause is available in the Apache Tomcat/6.0.33 logs.
rakesh
January 29, 2014
Exception in Code

Hi, i am Rakesh ,I was downloaded code(Curd jsp servlet jdbc) from ur tutorial , While running this code inside server I got Exception like.. java.lang.ClassNotFoundException: oracle.jdbc.driver.OracleDriver Jan 29, 2014 10:58:42 PM org.apache.catalina.core.StandardWrapperValve invoke SEVERE: Servlet.service() for servlet jsp threw exception java.lang.NullPointerException at info.dao.UserDao.getAllUsers(UserDao.java:71) at org.apache.jsp.listUser_jsp._jspService(listUser_jsp.java:70) at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70) at javax.servlet.http.HttpServlet.service(HttpServlet.java:723) at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:388) at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:313) at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:260) at javax.servlet.http.HttpServlet.service(HttpServlet.java:723) 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.StandardWrapperValve.invoke(StandardWrapperValve.java:233) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:293) at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:861) at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:606) at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489) at java.lang.Thread.run(Unknown Source) pls replay how i can resolve this exception Thanks & regards Rakesh
the employe
March 5, 2014
ask

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
trank
March 10, 2014
ask

good tutorial, may i know, how to set combo box to save in database? because in your tutorial at user.jsp, just using input type = "text". can you give me some example for combo box? Thnks
Sanketh
March 11, 2014
error when submit is pressed

Error 404: javax.servlet.UnavailableException: SRVE0200E: Servlet [net.roseindia.handler.UserHandler]: Could not find required class - net/roseindia/handler/UserHandler i am getting this error after step 2 step that is when i press submit after filling the form.
DMCA.com