Jweb M L101

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 13

Java Technologies for Web Applications

Lab G ui des

Document Code 25e-BM/HR/HDCV/FSOFT

Version 1.1

Effective Date 20/11/2012

Hanoi, 04/2019
Lab Guides Java Technologies for Web Applications Issue/Revision: x/y

RECORD OF CHANGES

No Effective Date Change Description Reason Reviewer Approver

1 25/Jun/2018 Create a new Lab Create new DieuNT1 VinhNV

2 01/May/2019 Update Fsoft Template Update DieuNT1 VinhNV

25e-BM/HR/HDCV/FSOFT v1.1 Internal use 2/13


Lab Guides Java Technologies for Web Applications Issue/Revision: x/y

Contents
Unit 1 - JSP/Servlet Introduction......................................................................................................4
Objectives:................................................................................................................................ 4
Problem Descriptions:............................................................................................................... 4

25e-BM/HR/HDCV/FSOFT v1.1 Internal use 3/13


Lab Guides Java Technologies for Web Applications Issue/Revision: x/y

CODE: NWEB.M.L101
TYPE: Medium
LOC:
DURATION: 60 MINUTES

Unit 1 - JSP/Servlet Introduction


Objectives:

 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

Step 1: Tạo Database

25e-BM/HR/HDCV/FSOFT v1.1 Internal use 4/13


Lab Guides Java Technologies for Web Applications Issue/Revision: x/y

Tạo DB có tên “JNWEBML101_SMS” có các bảng và quan hệ như sau:

Tạo stored procedure “usp_registerUser” như sau:

1. CREATE PROC [dbo].[usp_registerUser]


2. @firstName VARCHAR(50),
3. @lastName VARCHAR(50),
4. @email VARCHAR(100),
5. @userName VARCHAR(50),
6. @password VARCHAR(50)
7. AS
8. BEGIN
9. INSERT INTO Users VALUES (@firstName, @lastName, @email, @userName, @password)
10. END
Step 2: Tạo maven project

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

25e-BM/HR/HDCV/FSOFT v1.1 Internal use 5/13


Lab Guides Java Technologies for Web Applications Issue/Revision: x/y

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");

25e-BM/HR/HDCV/FSOFT v1.1 Internal use 6/13


Lab Guides Java Technologies for Web Applications Issue/Revision: x/y

11.     var confirmPasswordElement = document.getElementById("confirmPassword");


12.     
13.     // variable to check valid input
14.     var status = false;
15.     
16.     var message = "Please fill all mandatory fields";
17.     
18.     setBorderColor(firstNameElement);
19.     setBorderColor(lastNameElement);
20.     setBorderColor(emailElement);
21.     setBorderColor(userNameElement);
22.     setBorderColor(passwordElement);
23.     setBorderColor(confirmPasswordElement);
24.     
25.     var email = emailElement.value;
26.     
27.     if (email != "" && !validateEmail(email)) {
28.         message = "Email is incorrect format";
29.         emailElement.style.borderColor = "red";
30.     } else if (passwordElement.value != confirmPasswordElement.value) {
31.         message = "Confirm password is not match with password";
32.         confirmPasswordElement.style.borderColor = "red";
33.     }
34.     
35.     // count number of input tags
36.     var numberOfInput = document.getElementsByTagName("input").length;
37.     var countNumberValidInput = 0;
38.     for (var j = 0; j < numberOfInput; j++) {
39.         // check all input are valid
40.         if (document.getElementsByTagName("input")[j].
41. style.borderColor == "green") {
42.             countNumberValidInput++;
43.         }
44.     }
45.     // if all input are valid, set ok = true
46.     if (countNumberValidInput == numberOfInput) {
47.         message = "";
48.         status = true;
49.     }
50.
51.     document.getElementById("error").innerHTML = message;
52.     // if statuc -> call method showUserRegisted()
53.     if(status) {
54.         showUserRegisted();
55.     }
56. }
57.
58. /*
59. This function to create a header row for an existed table and
60. append data to it.

25e-BM/HR/HDCV/FSOFT v1.1 Internal use 7/13


Lab Guides Java Technologies for Web Applications Issue/Revision: x/y

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. }

Layout màn hình khi validate:

25e-BM/HR/HDCV/FSOFT v1.1 Internal use 8/13


Lab Guides Java Technologies for Web Applications Issue/Revision: x/y

Screen 01_Layout 02

Screen 01_Layout 03

25e-BM/HR/HDCV/FSOFT v1.1 Internal use 9/13


Lab Guides Java Technologies for Web Applications Issue/Revision: x/y

Screen 01_Layout 04

Step4: Tạo servlet class và cấu hình

Tạo lớp User trong package fa.training.entities như sau:

25e-BM/HR/HDCV/FSOFT v1.1 Internal use 10/13


Lab Guides Java Technologies for Web Applications Issue/Revision: x/y

 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ó 2 cách cấu hình servlet để mapping với request tương ứng:

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

25e-BM/HR/HDCV/FSOFT v1.1 Internal use 11/13


Lab Guides Java Technologies for Web Applications Issue/Revision: x/y

Cách 2: Sử dụng Annotation @WebServlet

Thêm Annotation @WebServlet trước class RegisterServlet

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.

86. package fa.training.dao;


87.
88. import java.io.IOException;
89. import java.sql.CallableStatement;
90. import java.sql.Connection;
91. import java.sql.ResultSet;
92. import java.sql.SQLException;
93.
94. import fa.training.entities.User;
95. import fa.training.utils.DBUtils;
96.
97. /**
98. * The class contains methods to update and retrieve data from database
99. *
100. * @author FA
101. *
102. */
103. public class UserDao {
104.
105. /**
106. * The method to insert a new user into database.
107. *
108. * @param user an user object.
109. * @return true if register successfully.
110. * @throws SQLException
111. * @throws IOException
112. * @throws ClassNotFoundException
113. */
114. public boolean registerUser(User user)
115. throws ClassNotFoundException, IOException, SQLException {
116. Connection connection = null;
117. try {

25e-BM/HR/HDCV/FSOFT v1.1 Internal use 12/13


Lab Guides Java Technologies for Web Applications Issue/Revision: x/y

118. connection = DBUtils.getConnection();


119. CallableStatement callableStatement =
120. connection.prepareCall("{call
usp_registerUser(?,?,?,?,?)}");
121. int param = 0;
122. callableStatement.setString(++param, user.getFirstName());
123. callableStatement.setString(++param, user.getLastName());
124. callableStatement.setString(++param, user.getEmail());
125. callableStatement.setString(++param, user.getUserName());
126. callableStatement.setString(++param, user.getPassword());
127. int result = callableStatement.executeUpdate();
128.
129. if (result > 0) {
130. return true;
131. }
132. return false;
133.
134. } finally {
135. DBUtils.closeConnection(connection);
136. }
137.
138. }
139. }

-- THE END --

25e-BM/HR/HDCV/FSOFT v1.1 Internal use 13/13

You might also like