En primer lugar, crear una base de datos y la tabla de usuario utilizando las siguientes secuencias de comandos SQL:
CREATE
TABLE
`users` (
`uname`
varchar
(10)
NOT
NULL
,
`
password
`
varchar
(10)
NOT
NULL
,
`email`
varchar
(50)
default
NULL
,
`registeredon`
date
default
NULL
,
PRIMARY
KEY
(`uname`),
UNIQUE
KEY
`email` (`email`)
) ENGINE=InnoDB
DEFAULT
CHARSET=latin1;
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
2
3
4
5
6
7
8
9
| package com.bari.model; import java.util.Date; public class User { String uname, password, email; Date registeredon; //put getter and setter here } |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
| package com.bari.util; import java.sql.Connection; import java.sql.DriverManager; public class Database { public static Connection getConnection() { try { Class.forName( "com.mysql.jdbc.Driver" ); Connection con = DriverManager.getConnection "root" , "dbpass" ); return con; } catch (Exception ex) { System.out.println( "Database.getConnection() Error -->" + ex.getMessage()); return null ; } } public static void close(Connection con) { try { con.close(); } catch (Exception ex) { } } } |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
| package com.bari.dao; import java.sql.*; import java.util.*; import com.bari.model.User; import com.bari.util.Database; public class UserDao { private Connection connection; public UserDao() { connection = Database.getConnection(); } public void checkUser(User user) { try { PreparedStatement ps = connection.prepareStatement( "select uname from users where uname = ?" ); ps.setString( 1 , user.getUname()); ResultSet rs = ps.executeQuery(); if (rs.next()) // found { updateUser(user); } else { addUser(user); } } catch (Exception ex) { System.out.println( "Error in check() -->" + ex.getMessage()); } } public void addUser(User user) { try { PreparedStatement preparedStatement = connection.prepareStatement( "insert into users(uname, password, email, registeredon) values (?, ?, ?, ? )" ); // Parameters start with 1 preparedStatement.setString( 1 , user.getUname()); preparedStatement.setString( 2 , user.getPassword()); preparedStatement.setString( 3 , user.getEmail()); preparedStatement.setDate( 4 , new java.sql.Date(user.getRegisteredon().getTime())); preparedStatement.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } } public void deleteUser(String userId) { try { PreparedStatement preparedStatement = connection.prepareStatement( "delete from users where uname=?" ); // Parameters start with 1 preparedStatement.setString( 1 , userId); preparedStatement.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } } public void updateUser(User user) { try { PreparedStatement preparedStatement = connection.prepareStatement( "update users set password=?, email=?, registeredon=?" + "where uname=?" ); // Parameters start with 1 System.out.println( new java.sql.Date(user.getRegisteredon().getTime())); preparedStatement.setString( 1 , user.getPassword()); preparedStatement.setString( 2 , user.getEmail()); preparedStatement.setDate( 3 , new java.sql.Date(user.getRegisteredon().getTime())); preparedStatement.setString( 4 , user.getUname()); 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.setUname(rs.getString( "uname" )); user.setPassword(rs.getString( "password" )); user.setEmail(rs.getString( "email" )); user.setRegisteredon(rs.getDate( "registeredon" )); users.add(user); } } catch (SQLException e) { e.printStackTrace(); } return users; } public User getUserById(String userId) { User user = new User(); try { PreparedStatement preparedStatement = connection.prepareStatement( "select * from users where uname=?" ); preparedStatement.setString( 1 , userId); ResultSet rs = preparedStatement.executeQuery(); if (rs.next()) { user.setUname(rs.getString( "uname" )); user.setPassword(rs.getString( "password" )); user.setEmail(rs.getString( "email" )); user.setRegisteredon(rs.getDate( "registeredon" )); } } catch (SQLException e) { e.printStackTrace(); } return user; } } |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
| package com.bari.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.bari.dao.UserDao; import com.bari.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" )){ String userId = request.getParameter( "userId" ); dao.deleteUser(userId); forward = LIST_USER; request.setAttribute( "users" , dao.getAllUsers()); } else if (action.equalsIgnoreCase( "edit" )){ forward = INSERT_OR_EDIT; String userId = 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.setUname(request.getParameter( "uname" )); user.setPassword(request.getParameter( "pass" )); try { Date reg = new SimpleDateFormat( "yyyy/MM/dd" ).parse(request.getParameter( "dob" )); System.out.println( "rrrrrrrrrrr" + reg); user.setRegisteredon(reg); } catch (ParseException e) { e.printStackTrace(); } user.setEmail(request.getParameter( "email" )); String userid = request.getParameter( "uname" ); // if(userid == null || userid.isEmpty()) // { // dao.addUser(user); // } // else // { user.setUname(userid); dao.checkUser(user); // } RequestDispatcher view = request.getRequestDispatcher(LIST_USER); request.setAttribute( "users" , dao.getAllUsers()); view.forward(request, response); } } |
index.jsp
1
2
3
4
5
6
7
8
9
10
11
| <%@page contentType="text/html" pageEncoding="UTF-8"%> <!DOCTYPE html> < html > < head > < meta http-equiv = "Content-Type" content = "text/html; charset=UTF-8" > < title >CRUD Example</ title > </ head > < body > < jsp:forward page = "/UserController?action=listuser" /> </ body > </ html > |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
| <%@page contentType="text/html" pageEncoding="UTF-8"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%> <!DOCTYPE html> < html > < head > < meta http-equiv = "Content-Type" content = "text/html; charset=UTF-8" > < title >Add new user</ title > </ head > < body > < form method = "POST" action = 'UserController' name = "frmAddUser" > <% String action = request.getParameter("action"); System.out.println(action); %> <% if (action.equalsIgnoreCase("edit")) {%> User Name : < input type = "text" name = "uname" value = "<c:out value=" ${user.uname}" />" readonly="readonly"/> (You Can't Change this)< br /> <%} else {%> User Name : < input type = "text" name = "uname" value = "<c:out value=" ${user.uname}" />" /> < br /> <%}%> Password : < input type = "password" name = "pass" value = "<c:out value=" ${user.password}" />" /> < br /> Email : < input type = "text" name = "email" value = "<c:out value=" ${user.email}" />" /> < br /> <% if (action.equalsIgnoreCase("edit")) {%> Registration : < input type = "text" name = "dob" value = "<fmt:formatDate pattern=" yyyy/MM/dd" value = "${user.registeredon}" />" readonly="readonly"/>(You Can't Change this) < br /> <%} else {%> Registration : < input type = "text" name = "dob" value = "<fmt:formatDate pattern=" yyyy/MM/dd" value = "${user.registeredon}" />" />(yyyy/MM/dd) < br /> <%}%> < input type = "submit" value = "Submit" /> </ form > </ body > </ html > |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
| <%@page contentType="text/html" pageEncoding="UTF-8"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%> <!DOCTYPE html> < html > < head > < meta http-equiv = "Content-Type" content = "text/html; charset=UTF-8" > < title >Show All Users</ title > </ head > < body > < table border = 1 > < thead > < tr > < th >User Name</ th > < th >Email</ th > < th >Registration Date</ th > < th colspan = 2 >Action</ th > </ tr > </ thead > < tbody > < c:forEach items = "${users}" var = "user" > < tr > < td >< c:out value = "${user.uname}" /></ td > < td >< c:out value = "${user.email}" /></ td > < td >< fmt:formatDate pattern = "dd MMM,yyyy" value = "${user.registeredon}" /></ td > < td >< a href = "UserController?action=edit&userId=<c:out value=" ${user.uname}"/>">Update</ a ></ td > < td >< a href = "UserController?action=delete&userId=<c:out value=" ${user.uname}"/>">Delete</ a ></ td > </ tr > </ c:forEach > </ tbody > </ table > < p >< a href = "UserController?action=insert" >Add User</ a ></ p > </ body > </ html > |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
| <? xml version = "1.0" encoding = "UTF-8" ?> < web-app version = "2.5" xmlns = "http://java.sun.com/xml/ns/javaee" xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation = "http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" > < servlet > < servlet-name >UserController</ servlet-name > < servlet-class >com.bari.controller.UserController</ servlet-class > </ servlet > < servlet-mapping > < servlet-name >UserController</ servlet-name > < url-pattern >/UserController</ url-pattern > </ servlet-mapping > < session-config > < session-timeout > 30 </ session-timeout > </ session-config > < welcome-file-list > < welcome-file >index.jsp</ welcome-file > </ welcome-file-list > </ web-app > |
No hay comentarios:
Publicar un comentario