Jweb M L101
Jweb M L101
Jweb M L101
Lab G ui des
Version 1.1
Hanoi, 04/2019
Lab Guides Java Technologies for Web Applications Issue/Revision: x/y
RECORD OF CHANGES
Contents
Unit 1 - JSP/Servlet Introduction......................................................................................................4
Objectives:................................................................................................................................ 4
Problem Descriptions:............................................................................................................... 4
CODE: NWEB.M.L101
TYPE: Medium
LOC:
DURATION: 60 MINUTES
Understand the basic concepts of web development technologies with java (JSP / Servlet)
Able to write servlets using the Java programming language (Java servlets)
Create dynamic HTML content with Servlets and JavaServer Pages, using the Expression
Language, and the JSP Standard Tag Library (JSTL)
Create robust web applications using MVC architecture, session management, filters, and database
integration (JDBC)
Make Servlets and JSP work together cleanly
Create secure web applications using the features of the Java EE web container
Problem Descriptions:
Học viên được yêu cầu tạo 1 .jsp trang đơn giản với HTML, CSS và JavaScript. Nội dung của trang được
miêu tả như hình dưới đây:
register-user.jsp
Screen 01_Layout 01
Tạo 1 maven project với tên “JWEB_M_L101” có cấu trúc thư mục như sau:
File pom.xml
11. <dependencies>
12. <dependency>
13. <groupId>javax.servlet</groupId>
14. <artifactId>javax.servlet-api</artifactId>
15. <version>3.1.0</version>
16. </dependency>
17.
18. <dependency>
19. <groupId>com.microsoft.sqlserver</groupId>
20. <artifactId>mssql-jdbc</artifactId>
21. <version>7.0.0.jre8</version>
22. </dependency>
23.
24. <dependency>
25. <groupId>log4j</groupId>
26. <artifactId>log4j</artifactId>
27. <version>1.2.17</version>
28. </dependency>
29. </dependencies>
30. <build>
31. <finalName>NWEB_M_L101</finalName>
32. <plugins>
33. <plugin>
34. <groupId>org.apache.maven.plugins</groupId>
35. <artifactId>maven-compiler-plugin</artifactId>
36. <version>3.2</version>
37. <configuration>
38. <source>1.8</source>
39. <target>1.8</target>
40. </configuration>
41. </plugin>
42. </plugins>
43. </build>
Step3: Validate
Để validate dữ liệu và thêm dữ liệu vừa nhập vào bảng User List bên dưới, ta sẽ sử dụng JavaScript hoặc
jQuery.
Tạo file JS, register-user.js. Cấu trúc thư mục webapp như sau:
1. /*
2. This function called when "Register" button clicked.
3. */
4. function validateRegister() {
5. // Get the value that user enters at the form
6. var firstNameElement = document.getElementById("firstName");
7. var lastNameElement = document.getElementById("lastName");
8. var emailElement = document.getElementById("email");
9. var userNameElement = document.getElementById("userName");
10. var passwordElement = document.getElementById("password");
61. */
62.
63. function showUserRegisted() {
64. // get element tbody of table with id = tbl-result
65. var table = document.getElementById("tbl-result").
66. getElementsByTagName("tbody")[0];
67. var index = table.rows.length;
68. // if number rows of table == 0, insert th into thead of table
69. if (table.rows.length == 0) {
70. var thead = document.getElementById("tbl-result").
71. getElementsByTagName("thead")[0];
72. var row = thead.insertRow(0);
73. row.insertCell(0).outerHTML = "<th>No</th>";
74. row.insertCell(1).outerHTML = "<th>First Name</th>";
75. row.insertCell(2).outerHTML = "<th>Last Name</th>";
76. row.insertCell(3).outerHTML = "<th>Email</th>";
77. row.insertCell(4).outerHTML = "<th>Username</th>";
78. }
79. // insert user registed rows into table result
80. var row = table.insertRow(table.rows.length);
81. row.insertCell(0).innerHTML = ++index;
82. row.insertCell(1).innerHTML = document.getElementById("firstName").value;
83. row.insertCell(2).innerHTML =
84. document.getElementsByClassName("lastName")[0].value;
85. row.insertCell(3).innerHTML = document.getElementsByTagName("input")[2].value;
86. row.insertCell(4).innerHTML = document.getElementById("userName").value;
87. }
88. /*
89. Check valid email.
90. */
91. function validateEmail(email) {
92. var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\
[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]
{2,}))$/;
93. return re.test(email);
94. }
95. /*
96. Change border to an element.
97. */
98. function setBorderColor(element) {
99. if (element.value == "") {
100. element.style.borderColor = "red";
101. } else {
102. element.style.borderColor = "green";
103. }
104. }
Screen 01_Layout 02
Screen 01_Layout 03
Screen 01_Layout 04
Tạo một Servlet có tên RegisterServlet trong package fa.training.servlet và override phương thức
doPost() như sau:
44. @WebServlet(urlPatterns = "/register")
45. public class RegisterServlet extends HttpServlet {
46.
47. private static final long serialVersionUID = 1L;
48.
49. @Override
50. protected void doPost(HttpServletRequest request,
51. HttpServletResponse response) throws ServletException, IOException {
52. // Get data from the request using request.getParameter()
53. String firstName = request.getParameter("firstName");
54. String lastName = request.getParameter("lastName");
55. String email = request.getParameter("email");
56. String userName = request.getParameter("userName");
57. String password = request.getParameter("password");
58.
59. // Set data for the user
60. User user = new User(firstName, lastName, email, userName, password);
61. try {
62. UserDao userDao = new UserDao();
63. // Call registerUser() method to insert user into DB
64. if (userDao.registerUser(user)) {
65. // Send a attribute name as "userRegister"
66. to register-user-process.jsp page
67. request.setAttribute("userRegister", user);
68. // Forward to register-user-process.jsp page
69. request.getRequestDispatcher("/views/login.jsp").
70. forward(request, response);
71. } else {
72. // send a attribute name as "message" to register-user.jsp page
73. request.setAttribute("message", Constants.REGISTER_FAIL_MESSAGE);
74. // forward to register-user.jsp page
75. request.getRequestDispatcher("/views/register-user.jsp").
76. forward(request, response);
77. }
78.
79. } catch (ClassNotFoundException | SQLException e) {
80. // log error if exception occurs
81. LogFactory.getLogger().
82. error("An exception occurs while register user");
83. }
84. }
85. }
Cấu hình servlet để mapping với request, thay đổi action của form register thành:
<form action="<%=request.getContextPath()%>/register" method="post"
onsubmit="return validateRegister()" name="frm-register">
Cách 1: Cấu hình trong file web.xml bằng cách thêm đoạn code sau vào file web.xml
Step5: Xử lý DAO
Tạo method registerUser(User user) trong class UserDao để xử lý insert user vừa đăng ký vào bảng
Users trong database.
-- THE END --