0% found this document useful (0 votes)
16 views29 pages

Workshop03 P

The document provides code examples and instructions for a workshop on Java Server Pages (JSP). It includes code snippets for JSP elements like scriplets, declarations, and expressions. It also includes full code examples for a JSP project with pages for joining an email list, a thank you page, and an error page.

Uploaded by

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

Workshop03 P

The document provides code examples and instructions for a workshop on Java Server Pages (JSP). It includes code snippets for JSP elements like scriplets, declarations, and expressions. It also includes full code examples for a JSP project with pages for joining an email list, a thank you page, and an error page.

Uploaded by

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

Subject: PRJ321

Workshop 03: JSP


RULES: Ws 03 should be submited on the LMS system
Contact me @ https://www.facebook.com/quynhtran.ly.94
--------------------------------------------------------------------------------------------------------

Students kindly practice these questions in class and at home based on the
Lecturer’s guidance. Thank you :-D
❖ Question 0: EL

JSP Scriplet!
CODE

FINISH
scriptingElements!
CODE
FINISH

ArrayList!
CODE

FINISH
❖ Question 01:

C:\Users\Ly Quynh
Tran\Documents\NetBeansProjects\WebErrorExceptionJSPDemo2021\web
\index.jsp
1 <%--
2 Document : index
3 Created on : 19/09/2021, 9:21:03 AM
4 Author : Ly Quynh Tran
5 --%>
6
7 <%@ page language="java" contentType="text/html; charset=UTF-8"
8 pageEncoding="UTF-8"%>
9 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
10 "http://www.w3.org/TR/html4/loose.dtd">
11 <html>
12 <head>
13 <meta http-equiv="Content-Type" content="text/html; charset=UTF-
8">
14 <title>JSP</title>
15 </head>
16 <body>
17 <form action="process.jsp">
18 Number 1:<input type="text" name="n1" /><br><br>
19 Number 2:<input type="text" name="n2" /><br> <br>
20 <input type="submit" value="Division" />
21 </form>
22 </body>
23 </html>
24
C:\Users\Ly Quynh
Tran\Documents\NetBeansProjects\WebErrorExceptionJSPDemo2021\web
\process.jsp
1 <%--
2 Document : process
3 Created on : 19/09/2021, 9:23:30 AM
4 Author : Ly Quynh Tran
5 --%>
6
7 <%@ page errorPage="error.jsp"%>
8 <%@ page language="java" contentType="text/html; charset=UTF-8"
9 pageEncoding="UTF-8"%>
10 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
11 "http://www.w3.org/TR/html4/loose.dtd">
12 <html>
13 <head>
14 <meta http-equiv="Content-Type" content="text/html; charset=UTF-
8">
15 <title>Process page</title>
16 </head>
17 <body>
18 <%
19 String num1 = request.getParameter("n1");
20 String num2 = request.getParameter("n2");
21
22 int a = Integer.parseInt(num1);
23 int b = Integer.parseInt(num2);
24 int c = a / b;
25 out.print(a + " divided by " + b + " = " + c);
26 %>
27 </body>
28 </html>
C:\Users\Ly Quynh
Tran\Documents\NetBeansProjects\WebErrorExceptionJSPDemo2021\web
\error.jsp
1 <%--
2 Document : error
3 Created on : 19/09/2021, 9:24:23 AM
4 Author : Ly Quynh Tran
5 --%>
6
7 <%@ page isErrorPage="true"%>
8 <%@ page language="java" contentType="text/html; charset=UTF-8"
9 pageEncoding="UTF-8"%>
10 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
11 "http://www.w3.org/TR/html4/loose.dtd">
12 <html>
13 <head>
14 <meta http-equiv="Content-Type" content="text/html; charset=UTF-
8">
15 <title>Error page</title>
16 </head>
17 <body>
18 <h3>Sorry an exception occured!</h3>
19 <p>Exception is:</p>
20 <%=exception%>
21 </body>
22 </html>

❖ Question 02:

C:\Users\Ly Quynh
Tran\Documents\NetBeansProjects\WebJSPElementDemo2021\web\declar
ation-test.jsp
1 <html>
2
3 <body>
4 <%!
5 String makeItLower(String data) {
6 return data.toLowerCase();
7 }
8 %>
9
10 Lower case "Hello World": <%= makeItLower("Hello World") %>
11
12 </body>
13 </html>
C:\Users\Ly Quynh
Tran\Documents\NetBeansProjects\WebJSPElementDemo2021\web\expre
ssion-test.jsp
1 <html>
2
3 <body>
4
5 Converting a string to uppercase: <%= new String("Hello
World").toUpperCase() %>
6
7 <br/><br/>
8
9 25 multiplied by 4 equals <%= 25*4 %>
10
11 <br/><br/>
12
13 Is 75 less than 69? <%= 75 < 69 %>
14
15 </body>
16
17 </html>
18
19
20
21
22
C:\Users\Ly Quynh
Tran\Documents\NetBeansProjects\WebJSPElementDemo2021\web\scriptl
et-test.jsp
1 <html>
2
3 <body>
4
5 <h3>Hello World of Java</h3>
6
7 <%
8 for (int i=1; i <=5; i++) {
9 out.println("<br/>I really code: " + i);
10 }
11 %>
12 </body>
13
14 </html>

❖ Question 03:

C:\Users\Ly Quynh
Tran\Documents\NetBeansProjects\WebEmailListJspDemo2021\web\index
.jsp
1 <%@page contentType="text/html" pageEncoding="utf-8"%>
2
3 <!DOCTYPE html>
4 <html>
5 <head>
6 <meta charset="utf-8">
7 <title>Java Servlets and JSP</title>
8 <link rel="stylesheet" href="styles/main.css" type="text/css"/>
9 </head>
10 <body>
11 <h1>Join our email list</h1>
12 <p>To join our email list, enter your name and
13 email address below.</p>
14 <p><i>${message}</i></p>
15 <form action="EmailListServlet" method="post">
16 <input type="hidden" name="action" value="add">
17 <label class="pad_top">Email:</label>
18 <input type="email" name="email" value="${user.email}"><br>
19 <label class="pad_top">First Name:</label>
20 <input type="text" name="firstName" value="${user.firstName}"><br>
21 <label class="pad_top">Last Name:</label>
22 <input type="text" name="lastName" value="${user.lastName}"><br>
23 <label>&nbsp;</label>
24 <input type="submit" value="Join Now" class="margin_left">
25 </form>
26 </body>
27 </html>
C:\Users\Ly Quynh
Tran\Documents\NetBeansProjects\WebEmailListJspDemo2021\web\than
ks.jsp
1 <%@page contentType="text/html" pageEncoding="utf-8"%>
2 <!DOCTYPE html>
3 <html>
4 <head>
5 <meta charset="utf-8">
6 <title>Java Servlets and JSP</title>
7 <link rel="stylesheet" href="styles/main.css" type="text/css"/>
8 </head>
9
10 <body>
11 <h1>Thanks for joining our email list</h1>
12
13 <p>Here is the information that you entered:</p>
14
15 <label>Email:</label>
16 <span>${user.email}</span><br>
17 <label>First Name:</label>
18 <span>${user.firstName}</span><br>
19 <label>Last Name:</label>
20 <span>${user.lastName}</span><br>
21
22 <p>To enter another email address, click on the Back
23 button in your browser or the Return button shown
24 below.</p>
25
26 <form action="" method="post">
27 <input type="hidden" name="action" value="join">
28 <input type="submit" value="Return">
29 </form>
30
31 </body>
32 </html>
C:\Users\Ly Quynh
Tran\Documents\NetBeansProjects\WebEmailListJspDemo2021\web\error
_404.jsp
1 <%@page contentType="text/html" pageEncoding="utf-8"%>
2 <!DOCTYPE html>
3 <html>
4 <head>
5 <meta charset="utf-8">
6 <title>Java Servlets and JSP</title>
7 <link rel="stylesheet" href="styles/main.css" type="text/css"/>
8 </head>
9 <body>
10
11 <h1>404 Error</h1>
12 <p>The server was not able to find the file you requested.</p>
13 <p>To continue, click the Back button.</p>
14
15 </body>
16 </html>
C:\Users\Ly Quynh
Tran\Documents\NetBeansProjects\WebEmailListJspDemo2021\src\java\C
ontroller\EmailListServlet.java
1 /*
2 * To change this license header, choose License Headers in Project
Properties.
3 * To change this template file, choose Tools | Templates
4 * and open the template in the editor.
5 */
6 package Controller;
7
8 import java.io.IOException;
9 import java.io.PrintWriter;
10 import javax.servlet.ServletException;
11 import javax.servlet.http.HttpServlet;
12 import javax.servlet.http.HttpServletRequest;
13 import javax.servlet.http.HttpServletResponse;
14 import model.User;
15 import model.UserDB;
16
17 /**
18 *
19 * @author Ly Quynh Tran
20 */
21 public class EmailListServlet extends HttpServlet {
22
23 /**
24 * Processes requests for both HTTP <code>GET</code> and
<code>POST</code>
25 * methods.
26 *
27 * @param request servlet request
28 * @param response servlet response
29 * @throws ServletException if a servlet-specific error occurs
30 * @throws IOException if an I/O error occurs
31 */
32 protected void processRequest(HttpServletRequest request,
HttpServletResponse response)
33 throws ServletException, IOException {
34 response.setContentType("text/html;charset=UTF-8");
35 try (PrintWriter out = response.getWriter()) {
36 /* TODO output your page here. You may use following sample code.
*/
37 out.println("<!DOCTYPE html>");
38 out.println("<html>");
39 out.println("<head>");
40 out.println("<title>Servlet EmailListServlet</title>");
41 out.println("</head>");
42 out.println("<body>");
43 out.println("<h1>Servlet EmailListServlet at " +
request.getContextPath() + "</h1>");
44 out.println("</body>");
45 out.println("</html>");
46 }
47 }
48
49 // <editor-fold defaultstate="collapsed" desc="HttpServlet methods.
Click on the + sign on the left to edit the code.">
50 /**
51 * Handles the HTTP <code>GET</code> method.
52 *
53 * @param request servlet request
54 * @param response servlet response
55 * @throws ServletException if a servlet-specific error occurs
56 * @throws IOException if an I/O error occurs
57 */
58 @Override
59 protected void doGet(HttpServletRequest request, HttpServletResponse
response)
60 throws ServletException, IOException {
61 processRequest(request, response);
62 }
63
64 /**
65 * Handles the HTTP <code>POST</code> method.
66 *
67 * @param request servlet request
68 * @param response servlet response
69 * @throws ServletException if a servlet-specific error occurs
70 * @throws IOException if an I/O error occurs
71 */
72 @Override
73 protected void doPost(HttpServletRequest request,
HttpServletResponse response)
74 throws ServletException, IOException {
75 String url = "/index.html";
76
77 // get current action
78 String action = request.getParameter("action");
79 if (action == null) {
80 action = "join"; // default action
81 }
82
83 // perform action and set URL to appropriate page
84 if (action.equals("join")) {
85 url = "/index.jsp"; // the "join" page
86 } else if (action.equals("add")) {
87 // get parameters from the request
88 String firstName = request.getParameter("firstName");
89 String lastName = request.getParameter("lastName");
90 String email = request.getParameter("email");
91
92 // store data in User object
93 User user = new User(firstName, lastName, email);
94
95 // validate the parameters
96 String message;
97 if (firstName == null || lastName == null || email == null
98 || firstName.isEmpty() || lastName.isEmpty() || email.isEmpty())
{
99 message = "Please fill out all three text boxes.";
100 url = "/index.jsp";
101 } else {
102 message = "";
103 url = "/thanks.jsp";
104 UserDB.insert(user);
105 }
106 request.setAttribute("user", user);
107 request.setAttribute("message", message);
108 }
109 getServletContext()
110 .getRequestDispatcher(url)
111 .forward(request, response);
112 }
113
114 /**
115 * Returns a short description of the servlet.
116 *
117 * @return a String containing servlet description
118 */
119 @Override
120 public String getServletInfo() {
121 return "Short description";
122 }// </editor-fold>
123
124 }
125
C:\Users\Ly Quynh
Tran\Documents\NetBeansProjects\WebEmailListJspDemo2021\src\java\
model\User.java
1 /*
2 * To change this license header, choose License Headers in Project
Properties.
3 * To change this template file, choose Tools | Templates
4 * and open the template in the editor.
5 */
6 package model;
7
8 import java.io.Serializable;
9
10 /**
11 *
12 * @author Ly Quynh Tran
13 */
14 public class User implements Serializable {
15
16 private String firstName;
17 private String lastName;
18 private String email;
19
20 public User() {
21 firstName = "";
22 lastName = "";
23 email = "";
24 }
25
26 public User(String firstName, String lastName, String email) {
27 this.firstName = firstName;
28 this.lastName = lastName;
29 this.email = email;
30 }
31
32 public String getFirstName() {
33 return firstName;
34 }
35
36 public void setFirstName(String firstName) {
37 this.firstName = firstName;
38 }
39
40 public String getLastName() {
41 return lastName;
42 }
43
44 public void setLastName(String lastName) {
45 this.lastName = lastName;
46 }
47
48 public String getEmail() {
49 return email;
50 }
51
52 public void setEmail(String email) {
53 this.email = email;
54 }
55 }
56
C:\Users\Ly Quynh
Tran\Documents\NetBeansProjects\WebEmailListJspDemo2021\src\java\
model\UserDB.java
1 /*
2 * To change this license header, choose License Headers in Project
Properties.
3 * To change this template file, choose Tools | Templates
4 * and open the template in the editor.
5 */
6 package model;
7
8 /**
9 *
10 * @author Ly Quynh Tran
11 */
12 public class UserDB {
13
14 public static long insert(User user) {
15 // TODO: Add code that adds the user to the database
16
17 return 0;
18 }
19 }
20
C:\Users\Ly Quynh
Tran\Documents\NetBeansProjects\WebEmailListJspDemo2021\web\style
s\main.css
1 /* The styles for the elements */
2 body {
3 font-family: Arial, Helvetica, sans-serif;
4 font-size: 85%;
5 margin-left: 2em;
6 margin-right: 2em;
7 width: 400px;
8}
9 h1 {
10 font-size: 140%;
11 color: teal;
12 margin-bottom: .5em;
13 }
14 h2 {
15 font-size: 120%;
16 color: teal;
17 margin-bottom: .5em;
18 }
19 label {
20 float: left;
21 width: 7em;
22 margin-bottom: 0.5em;
23 font-weight: bold;
24 }
25 input[type="text"], input[type="email"] { /* An attribute selector */
26 width: 15em;
27 margin-left: 0.5em;
28 margin-bottom: 0.5em;
29 }
30 span {
31 margin-left: 0.5em;
32 margin-bottom: 0.5em;
33 }
34 br {
35 clear: both;
36 }
37
38 /* The styles for the classes */
39 .pad_top {
40 padding-top: 0.25em;
41 }
42 .margin_left {
43 margin-left: 0.5em;
44 }
C:\Users\Ly Quynh
Tran\Documents\NetBeansProjects\WebEmailListJspDemo2021\web\WEB
-INF\web.xml
1 <?xml version="1.0" encoding="UTF-8"?>
2 <web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
3 <servlet>
4 <servlet-name>EmailListServlet</servlet-name>
5 <servlet-class>Controller.EmailListServlet</servlet-class>
6 </servlet>
7 <servlet>
8 <servlet-name>TestServlet</servlet-name>
9 <servlet-class>Controller.TestServlet</servlet-class>
10 </servlet>
11 <servlet-mapping>
12 <servlet-name>EmailListServlet</servlet-name>
13 <url-pattern>/EmailListServlet</url-pattern>
14 </servlet-mapping>
15 <servlet-mapping>
16 <servlet-name>TestServlet</servlet-name>
17 <url-pattern>/TestServlet</url-pattern>
18 </servlet-mapping>
19 <session-config>
20 <session-timeout>
21 30
22 </session-timeout>
23 </session-config>
24 <error-page>
25 <error-code>404</error-code>
26 <location>/error_404.jsp</location>
27 </error-page>
28 <error-page>
29 <error-code>500</error-code>
30 <location>/error_java.jsp</location>
31 </error-page>
32 <error-page>
33 <exception-type>java.lang.Exception</exception-type>
34 <location>/error_java.jsp</location>
35 </error-page>
36 </web-app>
37
❖ Question 04:

C:\Users\Ly Quynh
Tran\Documents\NetBeansProjects\WebMVCServletStudentDemoo2022\w
eb\WEB-INF\web.xml
1 <?xml version="1.0" encoding="UTF-8"?>
2 <web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
3 <servlet>
4 <servlet-name>StudentServlet</servlet-name>
5 <servlet-class>controller.StudentServlet</servlet-class>
6 </servlet>
7 <servlet-mapping>
8 <servlet-name>StudentServlet</servlet-name>
9 <url-pattern>/StudentServlet</url-pattern>
10 </servlet-mapping>
11 <session-config>
12 <session-timeout>
13 30
14 </session-timeout>
15 </session-config>
16 <welcome-file-list>
17 <welcome-file>index.jsp</welcome-file>
18 </welcome-file-list>
19 <error-page>
20 <error-code>404</error-code>
21 <location>/error_404.jsp</location>
22 </error-page>
23 </web-app>
24

C:\Users\Ly Quynh
Tran\Documents\NetBeansProjects\WebMVCServletStudentDemoo2022\w
eb\includes\column_left_home.jsp
1 <aside id="sidebarA">
2 <nav>
3 <ul>
4 <li><a class="current" href="index.jsp">Home</a></li>
5 <li><a href="addStudent.jsp"> Student Enrollment</a></li>
6 <li><a href="StudentServlet">Student List</a></li>
7 <li><a href="search.jsp">Student Search</a></li>
8 </ul>
9 </nav>
10 </aside>
C:\Users\Ly Quynh
Tran\Documents\NetBeansProjects\WebMVCServletStudentDemoo2022\w
eb\includes\column_right_news.jsp
1 <%@page contentType="text/html" pageEncoding="utf-8" %>
2 <aside id="sidebarB">
3 <h1>New Release</h1>
4 <img src="images/logo_apple.jpg" width="100"
5 alt="Activities Board">
6 <h2><a href="catalog/product/8601" class="no_underline">
7 Apple University News
8 </a></h2>
9 <p class="news_item">Summer semester started on 13/05/2022.</p>
10 </aside>
C:\Users\Ly Quynh
Tran\Documents\NetBeansProjects\WebMVCServletStudentDemoo2022\w
eb\includes\footer.jsp
1 <footer>
2 <p>Hit Counter ${Counter.count} &copy; Copyright ${currentYear}
Apple University.
3 All rights reserved.</p>
4 </footer>
5 </body>
6 </html>
C:\Users\Ly Quynh
Tran\Documents\NetBeansProjects\WebMVCServletStudentDemoo2022\w
eb\includes\header.jsp
1 <%@page contentType="text/html" pageEncoding="utf-8" %>
2 <%@ taglib uri = "http://java.sun.com/jsp/jstl/core" prefix = "c" %>
3 <!doctype html>
4
5 <html>
6 <head>
7 <meta charset="utf-8">
8 <title>Trường ĐẠI HỌC Apple </title>
9 <link rel="shortcut icon" href="images/favicon.ico">
10 <link rel="stylesheet" href="styles/main.css">
11 <script type="text/javascript"
src="https://cdnjs.cloudflare.com/ajax/libs/html5shiv/3.7.3/html5shiv.js"><
/script>
12 </head>
13 <% request.setCharacterEncoding("UTF-8"); %>
14 <body>
15
16 <header>
17 <meta charset="UTF-8">
18 <img src="images/logo_apple.jpg"
19 alt="Trường Đại học Apple" width="243" height="85" >
20 <h1>Apple University</h1>
21 <h2>Trường Đại học Apple - Cơ sở Đà Nẵng</h2>
22 </header>
23 <nav id="nav_bar">
24 <ul>
25 <li><a href="search.jsp">
26 Searching</a></li>
27 <li><a href="staff.jsp">
28 Staff</a></li>
29 <li><a href="">
30 News</a></li>
31 </ul>
32 </nav>
C:\Users\Ly Quynh
Tran\Documents\NetBeansProjects\WebMVCServletStudentDemoo2022\w
eb\error_404.jsp
1 <%--
2 Document : error_404
3 Created on : Apr 22, 2022, 3:44:59 AM
4 Author : Ly Quynh Tran
5 --%>
6
7 <%@page contentType="text/html" pageEncoding="UTF-8"%>
8 <!DOCTYPE html>
9 <%@include file="/includes/header.jsp" %>
10 <%@include file="/includes/column_left_home.jsp" %>
11 <section>
12 <h1>
13 Sorry, We can't find this page.
14 @@
15 </h1>
16 </section>
17 <%@include file="/includes/column_right_news.jsp" %>
18 <%@include file="/includes/footer.jsp" %>
19
C:\Users\Ly Quynh
Tran\Documents\NetBeansProjects\WebMVCServletStudentDemoo2022\w
eb\index.jsp
1 <%--
2 Document : index
3 Created on : Apr 22, 2022, 3:00:46 AM
4 Author : Ly Quynh Tran
5 --%>
6
7 <%@page contentType="text/html" pageEncoding="UTF-8"%>
8 <!DOCTYPE html>
9 <%@include file="/includes/header.jsp" %>
10 <%@include file="/includes/column_left_home.jsp" %>
11 <section>
12 <h1>
13 This is the session content
14 </h1>
15 </section>
16 <%@include file="/includes/column_right_news.jsp" %>
17 <%@include file="/includes/footer.jsp" %>
18
C:\Users\Ly Quynh
Tran\Documents\NetBeansProjects\WebMVCServletStudentDemoo2022\w
eb\list.jsp
1 <%--
2 Document : list
3 Created on : Apr 22, 2022, 3:28:04 AM
4 Author : Ly Quynh Tran
5 --%>
6
7 <%@page import="java.util.ArrayList"%>
8 <%@page import="model.Student"%>
9 <%@page contentType="text/html" pageEncoding="UTF-8"%>
10 <!DOCTYPE html>
11 <%@include file="/includes/header.jsp" %>
12 <%@include file="/includes/column_left_home.jsp" %>
13 <section id="main-contain" class="column">
14 <h1>
15 Student List
16 </h1>
17 <table border="1">
18 <thead>
19 <tr>
20 <th>ID</th>
21 <th>Name</th>
22 <th>Gender</th>
23 <th>DOB</th>
24 </tr>
25 </thead>
26 <tbody>
27 <%
28 ArrayList<Student> myList = (ArrayList<Student>)
request.getAttribute("MYSTUDENTS");
29 for (Student elem : myList) {%>
30 <tr>
31 <td><%=elem.getId()%></td>
32 <td><%=elem.getName()%></td>
33 <td><%=elem.getGender()%></td>
34 <td><%=elem.getDob()%></td>
35 </tr>
36 <%}
37 %>
38 </tbody>
39 </table>
40 </section>
41 <%@include file="/includes/column_right_news.jsp" %>
42 <%@include file="/includes/footer.jsp" %>
43
C:\Users\Ly Quynh
Tran\Documents\NetBeansProjects\WebMVCServletStudentDemoo2022\sr
c\java\controller\StudentServlet.java
1 /*
2 * To change this license header, choose License Headers in Project
Properties.
3 * To change this template file, choose Tools | Templates
4 * and open the template in the editor.
5 */
6 package controller;
7
8 import java.io.IOException;
9 import java.io.PrintWriter;
10 import java.util.ArrayList;
11 import javax.servlet.RequestDispatcher;
12 import javax.servlet.ServletException;
13 import javax.servlet.http.HttpServlet;
14 import javax.servlet.http.HttpServletRequest;
15 import javax.servlet.http.HttpServletResponse;
16 import model.Student;
17 import model.StudentList;
18
19 /**
20 *
21 * @author Ly Quynh Tran
22 */
23 public class StudentServlet extends HttpServlet {
24
25 /**
26 * Processes requests for both HTTP <code>GET</code> and
<code>POST</code>
27 * methods.
28 *
29 * @param request servlet request
30 * @param response servlet response
31 * @throws ServletException if a servlet-specific error occurs
32 * @throws IOException if an I/O error occurs
33 */
34 protected void processRequest(HttpServletRequest request,
HttpServletResponse response)
35 throws ServletException, IOException {
36 response.setContentType("text/html;charset=UTF-8");
37 try (PrintWriter out = response.getWriter()) {
38 /* TODO output your page here. You may use following sample code.
*/
39 out.println("<!DOCTYPE html>");
40 out.println("<html>");
41 out.println("<head>");
42 out.println("<title>Servlet StudentServlet</title>");
43 out.println("</head>");
44 out.println("<body>");
45 out.println("<h1>Servlet StudentServlet at " +
request.getContextPath() + "</h1>");
46 out.println("</body>");
47 out.println("</html>");
48 }
49 }
50
51 // <editor-fold defaultstate="collapsed" desc="HttpServlet methods.
Click on the + sign on the left to edit the code.">
52 /**
53 * Handles the HTTP <code>GET</code> method.
54 *
55 * @param request servlet request
56 * @param response servlet response
57 * @throws ServletException if a servlet-specific error occurs
58 * @throws IOException if an I/O error occurs
59 */
60 @Override
61 protected void doGet(HttpServletRequest request, HttpServletResponse
response)
62 throws ServletException, IOException {
63 StudentList list = new StudentList();
64 ArrayList<Student> myStudents = list.getList();
65 // Gan myStudents vao object request, duoi dang ten MYSTUDENTS
66 request.setAttribute("MYSTUDENTS", myStudents);
67 // sau do goi jsp de show ket qua
68 RequestDispatcher dispatcher =
request.getRequestDispatcher("list.jsp");
69 dispatcher.forward(request, response);
70
71 }
72
73 /**
74 * Handles the HTTP <code>POST</code> method.
75 *
76 * @param request servlet request
77 * @param response servlet response
78 * @throws ServletException if a servlet-specific error occurs
79 * @throws IOException if an I/O error occurs
80 */
81 @Override
82 protected void doPost(HttpServletRequest request,
HttpServletResponse response)
83 throws ServletException, IOException {
84 processRequest(request, response);
85 }
86
87 /**
88 * Returns a short description of the servlet.
89 *
90 * @return a String containing servlet description
91 */
92 @Override
93 public String getServletInfo() {
94 return "Short description";
95 }// </editor-fold>
96
97 }
98
C:\Users\Ly Quynh
Tran\Documents\NetBeansProjects\WebMVCServletStudentDemoo2022\sr
c\java\model\Student.java
1 /*
2 * To change this license header, choose License Headers in Project
Properties.
3 * To change this template file, choose Tools | Templates
4 * and open the template in the editor.
5 */
6 package model;
7
8 import java.text.ParseException;
9 import java.text.SimpleDateFormat;
10 import java.util.Date;
11 import java.util.logging.Level;
12 import java.util.logging.Logger;
13
14 /**
15 *
16 * @author Ly Quynh Tran
17 */
18 public class Student {
19
20 private int id;
21 private String name;
22 private boolean gender;
23 private Date dob;
24
25 public Student() {
26 }
27
28 public Student(int id, String name, boolean gender, Date dob) {
29 this.id = id;
30 this.name = name;
31 this.gender = gender;
32 this.dob = dob;
33 }
34
35 public Student(Student s) {
36 this(s.id, s.name, s.gender, s.dob);
37
38 }
39
40 // Chu y khuc ni hay ne, truyen date duoi dang String va chuyen qua
Date
41 // gender truyen duoi dang String, nhung this.gender can gia tri boolean
42 public Student(int id, String name, String gender, String dob) {
43 this.id = id;
44 this.name = name;
45 this.gender = gender.equals("M");// tra ve true neu gender la M
46 setDob(dob);
47 }
48
49 public int getId() {
50 return id;
51 }
52
53 public void setId(int id) {
54 this.id = id;
55 }
56
57 public String getName() {
58 return name;
59 }
60
61 public void setName(String name) {
62 this.name = name;
63 }
64
65 public boolean isGender() {
66 return gender;
67 }
68
69 public String getGender() {
70 return gender ? "Male" : "Female";
71
72 }
73
74 public void setGender(String gender) {
75 this.gender = gender.equals("M");
76 }
77
78 public String getDob() {
79 SimpleDateFormat myFormat = new
SimpleDateFormat("dd/MM/yyyy");
80 return myFormat.format(dob);
81 }
82
83 // Nhan date duoi dang String, sau do ep qua Date
84 public void setDob(String dob) {
85 SimpleDateFormat myFormat = new
SimpleDateFormat("dd/MM/yyyy");
86 try {
87 this.dob = new Date(myFormat.parse(dob).getTime());
88 } catch (ParseException ex) {
89 Logger.getLogger(Student.class.getName()).log(Level.SEVERE, null,
ex);
90 }
91 }
92
93 @Override
94 public String toString() {
95 return "Student{" + "id=" + id + ", name=" + name + ", gender=" +
gender + ", dob=" + dob + '}';
96 }
97
98 }
99
C:\Users\Ly Quynh
Tran\Documents\NetBeansProjects\WebMVCServletStudentDemoo2022\sr
c\java\model\StudentList.java
1 /*
2 * To change this license header, choose License Headers in Project
Properties.
3 * To change this template file, choose Tools | Templates
4 * and open the template in the editor.
5 */
6 package model;
7
8 import java.util.ArrayList;
9
10 /**
11 *
12 * @author Ly Quynh Tran
13 */
14 public class StudentList {
15
16 private ArrayList<Student> list = new ArrayList<>();
17
18 public StudentList() {
19 // Add sam 5 sinh vien vao list
20 list.add(new Student(1001, "Nguyen A", "M", "20/05/1999"));
21 list.add(new Student(1002, "Nguyen B", "M", "20/06/1999"));
22 list.add(new Student(1003, "Nguyen C", "F", "20/07/1999"));
23 list.add(new Student(1004, "Nguyen D", "F", "20/08/1999"));
24 list.add(new Student(1005, "Nguyen E", "M", "20/09/1999"));
25 }
26
27 public ArrayList<Student> getList() {
28 return list;
29 }
30
31 public void setList(ArrayList<Student> list) {
32 this.list = list;
33 }
34
35 }
36
C:\Users\Ly Quynh
Tran\Documents\NetBeansProjects\WebMVCServletStudentDemoo2022\sr
c\java\model\Main.java
1 /*
2 * To change this license header, choose License Headers in Project
Properties.
3 * To change this template file, choose Tools | Templates
4 * and open the template in the editor.
5 */
6 package model;
7
8 /**
9 *
10 * @author Ly Quynh Tran
11 */
12 public class Main {
13
14 /**
15 * @param args the command line arguments
16 */
17 public static void main(String[] args) {
18 // TODO code application logic here
19 StudentList studentList = new StudentList();
20 System.out.println(""+studentList.getList());
21 }
22
23 }
24

You might also like