0% found this document useful (0 votes)
1K views10 pages

JSP, Servlet, JSTL and Mysql Simple Crud Application

This document describes a simple CRUD (create, read, update, delete) web application using JSP, Servlet, JSTL and MySQL. It includes code snippets to create the database structure, model classes like User, DAO class to handle database operations, and a servlet class to handle HTTP requests and forward them to JSP pages. Index, user and listuser JSP pages are also created to display and manage user data in the application.

Uploaded by

zhadraoui
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1K views10 pages

JSP, Servlet, JSTL and Mysql Simple Crud Application

This document describes a simple CRUD (create, read, update, delete) web application using JSP, Servlet, JSTL and MySQL. It includes code snippets to create the database structure, model classes like User, DAO class to handle database operations, and a servlet class to handle HTTP requests and forward them to JSP pages. Index, user and listuser JSP pages are also created to display and manage user data in the application.

Uploaded by

zhadraoui
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 10

JSP, SERVLET, JSTL AND MYSQL SIMPLE

CRUD APPLICATION

This is a simple CRUD (Create Read Update Delete) User Management


Web Application using Jsp, Servlet, JSTL and MySQL created using
NetBeans IDE.

First, create a database and table for User using the following SQL
scripts:
1 CREATE TABLE `users` (
2 `uname` varchar(10) NOT NULL,
3 `password` varchar(10) NOT NULL,
4 `email` varchar(50) default NULL,
5 `registeredon` date default NULL,
6 PRIMARY KEY (`uname`),
UNIQUE KEY `email` (`email`)
7 ) ENGINE=InnoDB DEFAULT CHARSET=latin1;
8

Now create a project in netbeans with the following project structure.

Create four packages in the src folder.

com.bari.controller: contains the servlets(UserController.java)


com.bari.dao: contains the logic for database operation(UserDao.java)
com.bari.model: contains the POJO (Plain Old Java Object).(User.java)
com.bari.util : contains the class for initiating database
connection(Database.java)
User.java
1 package com.bari.model;
2 import java.util.Date;
3
4 public class User {
5 String uname, password, email;
6 Date registeredon;
7
//put getter and setter here
8 }
9
Database.java
1
2
3 package com.bari.util;
import java.sql.Connection;
4
import java.sql.DriverManager;
5 public class Database {
6 public static Connection getConnection() {
7 try {
8 Class.forName("com.mysql.jdbc.Driver");
9 Connection con = DriverManager.getConnection
("jdbc:mysql://localhost:3306/dbname",
10 "root","dbpass");
11 return con;
12 }
13 catch(Exception ex) {
14 System.out.println("Database.getConnection() Error -->" + ex.getMessa
return null;
15 }
16 }
17
18 public static void close(Connection con) {
19 try {
20 con.close();
21 }
catch(Exception ex) {
22 }
23 }
24 }
25
26
UserDao.java
1 package com.bari.dao;
2
3 import java.sql.*;
import java.util.*;
4 import com.bari.model.User;
5 import com.bari.util.Database;
6 public class UserDao {
7
8 private Connection connection;
9
10 public UserDao() {
11 connection = Database.getConnection();
12 }
13
public void checkUser(User user) {
14 try {
15 PreparedStatement ps = connection.prepareStatement("select uname from use
16 ps.setString(1, user.getUname());
17 ResultSet rs = ps.executeQuery();
18 if (rs.next()) // found
{
19 updateUser(user);
20 } else {
21 addUser(user);
22 }
} catch (Exception ex) {
23 System.out.println("Error in check() -->" + ex.getMessage());
24 }
25 }
26 public void addUser(User user) {
27 try {
PreparedStatement preparedStatement = connection.prepareStatement("insert
28 // Parameters start with 1
29 preparedStatement.setString(1, user.getUname());
30 preparedStatement.setString(2, user.getPassword());
31 preparedStatement.setString(3, user.getEmail());
32 preparedStatement.setDate(4, new java.sql.Date(user.getRegisteredon().getT
preparedStatement.executeUpdate();
33
34 } catch (SQLException e) {
35 e.printStackTrace();
36 }
37 }
38
public void deleteUser(String userId) {
39 try {
40 PreparedStatement preparedStatement = connection.prepareStatement("delete
41 // Parameters start with 1
42 preparedStatement.setString(1, userId);
43 preparedStatement.executeUpdate();
44
} catch (SQLException e) {
45 e.printStackTrace();
46 }
47 }
48
49 public void updateUser(User user) {
try {
50
51 PreparedStatement preparedStatement = connection.prepareStatement("update
+ "where uname=?");
52 // Parameters start with 1
53 System.out.println(new java.sql.Date(user.getRegisteredon().getTime()));
54 preparedStatement.setString(1, user.getPassword());
55 preparedStatement.setString(2, user.getEmail());
56 preparedStatement.setDate(3, new java.sql.Date(user.getRegisteredon().getT
preparedStatement.setString(4, user.getUname());
57 preparedStatement.executeUpdate();
58
59 } catch (SQLException e) {
60 e.printStackTrace();
61 }
62 }
63
public List<User> getAllUsers() {
64 List<User> users = new ArrayList<User>();
65 try {
66 Statement statement = connection.createStatement();
67 ResultSet rs = statement.executeQuery("select * from users");
while (rs.next()) {
68 User user = new User();
69 user.setUname(rs.getString("uname"));
70 user.setPassword(rs.getString("password"));
71 user.setEmail(rs.getString("email"));
72 user.setRegisteredon(rs.getDate("registeredon"));
users.add(user);
73 }
74 } catch (SQLException e) {
75 e.printStackTrace();
76 }
77
78 return users;
}
79
80 public User getUserById(String userId) {
81 User user = new User();
82 try {
83 PreparedStatement preparedStatement = connection.prepareStatement("select
preparedStatement.setString(1, userId);
84 ResultSet rs = preparedStatement.executeQuery();
85
86 if (rs.next()) {
87 user.setUname(rs.getString("uname"));
88 user.setPassword(rs.getString("password"));
89 user.setEmail(rs.getString("email"));
user.setRegisteredon(rs.getDate("registeredon"));
90 }
91 } catch (SQLException e) {
92 e.printStackTrace();
93 }
94
return user;
95
}
96 }
97
98
99
10
0
10
1
10
2
10
3
10
4
10
5
10
6
10
7
10
8
10
9
110
111
112
113
114
UserController.java
1 package com.bari.controller;
2
import java.io.IOException;
3 import java.text.ParseException;
4 import java.text.SimpleDateFormat;
5 import java.util.Date;
6
7 import javax.servlet.RequestDispatcher;
8 import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
9 import javax.servlet.http.HttpServletRequest;
10 import javax.servlet.http.HttpServletResponse;
11
12 import com.bari.dao.UserDao;
13 import com.bari.model.User;
14
15 public class UserController extends HttpServlet {
private static final long serialVersionUID = 1L;
16 private static String INSERT_OR_EDIT = "/user.jsp";
17 private static String LIST_USER = "/listuser.jsp";
18 private UserDao dao;
19
20 public UserController() {
super();
21 dao = new UserDao();
22 }
23
24 protected void doGet(HttpServletRequest request, HttpServletResponse response) t
25 String forward="";
26 String action = request.getParameter("action");
27
if (action.equalsIgnoreCase("delete")){
28 String userId = request.getParameter("userId");
29 dao.deleteUser(userId);
30 forward = LIST_USER;
31 request.setAttribute("users", dao.getAllUsers());
32 } else if (action.equalsIgnoreCase("edit")){
forward = INSERT_OR_EDIT;
33 String userId = request.getParameter("userId");
34 User user = dao.getUserById(userId);
35 request.setAttribute("user", user);
36 } else if (action.equalsIgnoreCase("listUser")){
forward = LIST_USER;
37 request.setAttribute("users", dao.getAllUsers());
38 } else {
39 forward = INSERT_OR_EDIT;
40 }
41
42 RequestDispatcher view = request.getRequestDispatcher(forward);
view.forward(request, response);
43 }
44
45 protected void doPost(HttpServletRequest request, HttpServletResponse response)
46 User user = new User();
47 user.setUname(request.getParameter("uname"));
48 user.setPassword(request.getParameter("pass"));
try {
49 Date reg = new SimpleDateFormat("yyyy/MM/dd").parse(request.getParamete
50 System.out.println("rrrrrrrrrrr"+ reg);
51 user.setRegisteredon(reg);
52 } catch (ParseException e) {
e.printStackTrace();
53 }
54 user.setEmail(request.getParameter("email"));
55 String userid = request.getParameter("uname");
56 // if(userid == null || userid.isEmpty())
57 // {
// dao.addUser(user);
58 // }
59 // else
60 // {
61 user.setUname(userid);
dao.checkUser(user);
62
// }
63 RequestDispatcher view = request.getRequestDispatcher(LIST_USER);
64 request.setAttribute("users", dao.getAllUsers());
65 view.forward(request, response);
66
67
68
69
70
71
72 }
73 }
74
75
76
77
78
79

Now, its time to create three jsp pages.

index.jsp
1
2 <%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
3 <html>
4 <head>
5 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
6 <title>CRUD Example</title>
7 </head>
<body>
8 <jsp:forward page="/UserController?action=listuser" />
9 </body>
10 </html>
11
user.jsp
1 <%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
2 <%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
3 <!DOCTYPE html>
4 <html>
5 <head>
6 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Add new user</title>
7 </head>
8 <body>
9 <form method="POST" action='UserController' name="frmAddUser">
10 <% String action = request.getParameter("action");
11 System.out.println(action);
%>
12 <% if (action.equalsIgnoreCase("edit")) {%>
13 User Name : <input type="text" name="uname"
14 value="<c:out value="${user.uname}" />" readonly="re
15 <%} else {%>
User Name : <input type="text" name="uname"
16 value="<c:out value="${user.uname}" />" /> <br />
17
18
19
20
<%}%>
21 Password : <input
22 type="password" name="pass"
23 value="<c:out value="${user.password}" />" /> <br />
24 Email : <input
type="text" name="email"
25 value="<c:out value="${user.email}" />" /> <br />
26
27 <% if (action.equalsIgnoreCase("edit")) {%>
28 Registration : <input
29 type="text" name="dob"
30 value="<fmt:formatDate pattern="yyyy/MM/dd" value="${user.registere
<%} else {%>
31 Registration : <input
32 type="text" name="dob"
33 value="<fmt:formatDate pattern="yyyy/MM/dd" value="${user.registere
34 <%}%>
35 <input type="submit" value="Submit" />
36 </form>
</body>
37 </html>
38
39
40
41
listuser.jsp
1 <%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
2 <%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
3 <!DOCTYPE html>
4 <html>
5 <head>
6 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Show All Users</title>
7 </head>
8 <body>
9 <table border=1>
10 <thead>
11 <tr>
<th>User Name</th>
12 <th>Email</th>
13 <th>Registration Date</th>
14 <th colspan=2>Action</th>
15 </tr>
</thead>
16 <tbody>
17 <c:forEach items="${users}" var="user">
18 <tr>
19 <td><c:out value="${user.uname}" /></td>
20 <td><c:out value="${user.email}" /></td>
<td><fmt:formatDate pattern="dd MMM,yyyy" value="${user.register
21
22
23
24 <td><a href="UserController?action=edit&userId=<c:out value="${
25 <td><a href="UserController?action=delete&userId=<c:out value="
26 </tr>
</c:forEach>
27 </tbody>
28 </table>
29 <p><a href="UserController?action=insert">Add User</a></p>
30 </body>
31 </html>
32
33
34

Finally configure your web.xml file.


1
2
3
4
5
6
7 <?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w
8 http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
9 <servlet>
1 <servlet-name>UserController</servlet-name>
0 <servlet-class>com.bari.controller.UserController</servlet-class>
</servlet>
11 <servlet-mapping>
1 <servlet-name>UserController</servlet-name>
2 <url-pattern>/UserController</url-pattern>
1 </servlet-mapping>
<session-config>
3 <session-timeout>
1 30
4 </session-timeout>
1 </session-config>
5 <welcome-file-list>
<welcome-file>index.jsp</welcome-file>
1 </welcome-file-list>
6 </web-app>
1
7
1
8
1
9

Thats it. Run the project. These are some screenshots.

You might also like