JSP and Servlet Integration Case

Posted by phpprog on Fri, 23 Aug 2019 16:01:37 +0200

02 System Page Creation-System Requirements Analysis

2.2 Brief Answers
2.2.1 According to the video, please write out the realization of login function?
User information is queried according to user name and password. If it is found, the login succeeds and if it is not found, the login fails.
What are the three functional requirements of 2.2.2 video? ,
Implementing user login: Find out if there is this person in the database according to user name and password, if there is, login succeeds, if not, login fails.
Implementing User Exit: Destroying session
Implementing user registration: inserting user information into database
2.3 Programming Questions
2.3.1 According to the video instructions, the template of the main page is implemented independently.

03 Login Servlet Creation and MVC Ideas

3.1 Programming Question
3.2.1 According to the requirement analysis in video, MySQL is used to complete the creation of user information table, and the table creation statement and test data SQL are used as the answers.

create table t_user(
uid int primary key auto_increment,
uname varchar(20) not null,
pwd varchar(10) not null,
sex char(4) not NULL,
age int not null,
birthday date not null
);

insert into t_user values(default,"Zhang San","123","male",18,"1997-10-2");
insert into t_user values(default,"Li Si","456","male",18,"1997-10-2");

select * from t_user;

3.2.2 Modify the action address submitted by the login page data
Screenshots as answers


3.2.3 Create login Servlet and complete the encoding settings in the Servlet. The code for obtaining login information is compiled, and the implementation of code pasting is the answer.

public class UserServlet extends HttpServlet {
	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		//Setting Request Encoding Format
		req.setCharacterEncoding("utf-8");
		//Setting the response encoding format
		resp.setContentType("text/html;charset=utf-8");
		//Getting Request Information
		String uname = req.getParameter("uname");
		String pwd = req.getParameter("pwd");
		//Processing request information
		System.out.println(uname+":"+pwd);
		//Response processing results
			//Direct response
			//Request forwarding
			//redirect
	}
}

3.2.4 Modify the key names submitted by the user name and password in the form on the login page, and paste the modified form code as the answer.

<input type="text" class="input input-big" name="uname" placeholder="Login account" data-validate="required:Please fill in the account number." />
<input type="password" class="input input-big" name="pwd" placeholder="Login password" data-validate="required:Please fill in the password." />

3.2.5 Brief Description of MVC Programming Thought and Its Benefits
M:model, service layer, dao layer and entity class layer
V:view. View layer jsp page, etc.
C:controller control layer servlet

04 MVC Realizes Logon and Query User Information (A)

4.3 Programming Questions
4.3.1 According to the video instructions, the creation of service layer and Dao in MVC is completed in the project. Only the creation of interface and its implementation class is needed, and the functional method is not declared at first.

4.3.2 Create User Entity Classes Based on Video

public class User implements Serializable{
	private int uid;
	private String uname;
	private String pwd;
	private String sex;
	private int age;
	private String birthday;
	public int getUid() {
		return uid;
	}
	public void setUid(int uid) {
		this.uid = uid;
	}
	public String getUname() {
		return uname;
	}
	public void setUname(String uname) {
		this.uname = uname;
	}
	public String getPwd() {
		return pwd;
	}
	public void setPwd(String pwd) {
		this.pwd = pwd;
	}
	public String getSex() {
		return sex;
	}
	public void setSex(String sex) {
		this.sex = sex;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public String getBirthday() {
		return birthday;
	}
	public void setBirthday(String birthday) {
		this.birthday = birthday;
	}
	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + age;
		result = prime * result
				+ ((birthday == null) ? 0 : birthday.hashCode());
		result = prime * result + ((pwd == null) ? 0 : pwd.hashCode());
		result = prime * result + ((sex == null) ? 0 : sex.hashCode());
		result = prime * result + uid;
		result = prime * result + ((uname == null) ? 0 : uname.hashCode());
		return result;
	}
	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		User other = (User) obj;
		if (age != other.age)
			return false;
		if (birthday == null) {
			if (other.birthday != null)
				return false;
		} else if (!birthday.equals(other.birthday))
			return false;
		if (pwd == null) {
			if (other.pwd != null)
				return false;
		} else if (!pwd.equals(other.pwd))
			return false;
		if (sex == null) {
			if (other.sex != null)
				return false;
		} else if (!sex.equals(other.sex))
			return false;
		if (uid != other.uid)
			return false;
		if (uname == null) {
			if (other.uname != null)
				return false;
		} else if (!uname.equals(other.uname))
			return false;
		return true;
	}
	@Override
	public String toString() {
		return "User [uid=" + uid + ", uname=" + uname + ", pwd=" + pwd
				+ ", sex=" + sex + ", age=" + age + ", birthday=" + birthday
				+ "]";
	}
	public User() {
		super();
	}

4.3.3 Import MySQL jar packages based on video instructions, and import database operation tool classes and configuration of db.properties

4.3.4 Complete the function code of business layer and database layer according to video

public interface UserService {
	User getUserInfoService(String uname, String pwd);
}
public class UserServiceImpl implements UserService{
	UserDao ud = new UserDaoImpl();
	//Query user information based on username and password
	@Override
	public User getUserInfoService(String uname, String pwd) {
		return ud.getUserInfoDao(uname,pwd);
	}
}
public interface UserDao {
	User getUserInfoDao(String uname, String pwd);
}

public class UserDaoImpl implements UserDao{
	//Query user information based on username and password
	@Override
	public User getUserInfoDao(String uname, String pwd) {
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		User u = null;
		try{
			conn = (Connection) DBUtil.getConnection();
			String sql = "select * from t_user where uname=? and pwd=?";
			ps = conn.prepareStatement(sql);
			ps.setString(1,uname);
			ps.setString(2, pwd);
			rs = ps.executeQuery();
			while(rs.next()){
				u = new User();
				u.setUid(rs.getInt("uid"));
				u.setUname(rs.getString("uname"));
				u.setSex(rs.getString("sex"));
				u.setAge(rs.getInt("age"));
				u.setBirthday(rs.getString("birthday"));
			}
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			DBUtil.closeAll(rs, ps, conn);
		}
		return u;
	}
}

4.3.5 Print the inquired user information in the background according to the video explanation.

05 User Logon Failure and Successful Handling

5.1 Programming Questions
5.1.1 According to the video instructions, complete the login failure redirection to the login page, and display the prompt username or password error on the login page.

UserServlet Addition of code:
//Create or get session objects
		HttpSession session = req.getSession();
			//redirect
		if(user!=null){//Successful login
			//Successful display of current user information
			session.setAttribute("user", user);
			resp.sendRedirect("/project/main.jsp");
		}else{//Logon failure
			//Failure to display prompt information
			session.setAttribute("flag", "ERROR Incorrect username or password");
			resp.sendRedirect("/project/login.jsp");
		}
Login.jsp Add code:
<!-- statement java code block -->
                	<%
                		Object obj = session.getAttribute("flag");
                		if(obj!=null){
                	%>
              		 <div  style="font-size:18px;color:red;" class="text-center margin-big padding-big-top">ERROR Incorrect username or password</div>        	
                	<%	
                		}
                		session.invalidate();
                	%>

5.1.2 Completes the addition of the logout button.

<div style="position: relative;left:820px" class="head-l"><span style="font-size: 15px;color: white">The current user is:<%= ((User)session.getAttribute("user")).getUname() %></span>&nbsp;&nbsp;<a class="button button-little bg-red" href="login.html"><span class="icon-power-off"></span> Log out</a> </div>

5.1.3 Complete login successfully, redirect home page code implementation. The user currently logged in is displayed on the home page.

06 User Exit Function Implementation

6.2 Exercises by Supervisors
6.2.1 Brief introduction to the realization of user exit
When a user clicks to exit, he first gives a pop-up box to ask if he wants to quit and give the user a friendly interaction. If he clicks on it, he destroys the session object and redirects it to the login.jsp page. If he clicks on it, he will not deal with it.
6.2.2 Declares and creates a Servlet to handle user logout requests.

public class ExitServlet extends HttpServlet {
	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		//Setting Request Encoding Format
		req.setCharacterEncoding("utf-8");
		//Setting the response encoding format
		resp.setContentType("text/html;charset=utf-8");
		//Getting Request Information
		//Processing request information
		//Get the session object
		HttpSession session = req.getSession();
		//Compulsory destruction
		session.invalidate();
		//Response processing results
			//redirect
			resp.sendRedirect("/project/login.jsp");
	}
}

6.2.3 Modify the herf address of the exit login button to the Servlet path of exit login, then run the project, click exit login to see the effect of the operation.

  <div style="position: relative;left:820px" class="head-l"><span style="font-size: 15px;color: white">The current user is:<%= ((User)session.getAttribute("user")).getUname() %></span>&nbsp;&nbsp;<a class="button button-little bg-red" href="exit" id="div_a"><span class="icon-power-off"></span> Log out</a> </div>

6.2.3 Modify the code to add an exit prompt to the exit login button.

<script type="text/javascript">
	$(function(){
		$("#div_a").click(function(){
			return window.confirm("Do you really want to quit?");
		})
	})
</script>   

07 Create User Registration Page (1)

7.1 Programming Question
7.1.1 Add the registration button to the login page according to the video instructions.

<div style="font-size: 15px;position: relative;left: 300px;top: -15px"><a href="reg.jsp">register</a></div>

7.1.2 According to the video instructions, create the registration page and apply the template content.

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE html>
<html lang="zh-cn">
<head>
    <base href="<%=basePath%>">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<meta name="renderer" content="webkit">
<title></title>
<link rel="stylesheet" href="css/pintuer.css">
<link rel="stylesheet" href="css/admin.css">
<script src="js/jquery.js"></script>
<script src="js/pintuer.js"></script>
</head>
<body>
<div class="panel admin-panel">
  <div class="panel-head"><strong><span class="icon-key"></span> User Registration Page</strong></div>
  <div class="body-content">
    <form method="post" class="form-x" action="">
      <div class="form-group">
        <div class="label">
          <label for="sitename">User name:</label>
        </div>
        <div class="field">
          <input type="text" class="input w50" id="mpass" name="uname" size="50" placeholder="enter one user name" />       
        </div>
      </div>      
      <div class="form-group">
        <div class="label">
          <label for="sitename">User password:</label>
        </div>
        <div class="field">
          <input type="password" class="input w50" name="pwd" size="50" placeholder="Please enter a new password" data-validate="required:Please enter a new password,length#>= 5: The new password should not be less than 5 bits "/>"         
        </div>
      </div>
      <div class="form-group">
        <div class="label">
          <label for="sitename">Confirm the new password:</label>
        </div>
        <div class="field">
          <input type="password" class="input w50" name="npwd" size="50" placeholder="Please enter the new password again." data-validate="required:Please enter the new password again.,repeat#newpass: Password inconsistencies entered twice'/> ___________          
        </div>
      </div>
      <div class="form-group">
        <div class="label">
          <label></label>
        </div>
        <div class="field">
          <button class="button bg-main icon-check-square-o" type="submit"> Submission</button>   
        </div>
      </div>      
    </form>
  </div>
</div>
</body></html>

7.1.3 According to the video instructions, modify the original template content of the registration page, modify it to our own registration page, and add user gender options.

<div class="form-group">
			        <div class="label">
			          <label>Gender:</label>
			        </div>
			        <div class="field">
			          <div class="button-group radio">
			          
			          <label class="button active">
			         	  <span class="icon-check" id="manSpan"></span>             
			              <input name="sex" value="1" id="man" type="radio" checked="checked">male         
			          </label>             
			        
			          <label class="button active" ><span class="" id="womanSpan"></span>          	
			              <input name="sex" value="0" id="woman" type="radio">female
			          </label>         
			           </div>       
			        </div>
			     </div> 

08 Create User Registration Page (2)

8.1 Programming Question
8.1.1 Complete the user's gender selection function according to the video explanation.

<script type="text/javascript">
	$(function(){
		
		$("#man").click(function(){
			
			$("#manSpan").addClass("icon-check");
			$("#womanSpan").removeClass("icon-check");
		})
		
		$("#woman").click(function(){
			
			$("#manSpan").removeClass("icon-check");
			$("#womanSpan").addClass("icon-check");
		})
	})
</script>

8.1.2 Improve the registration page, add user age and birth date options

 <div class="form-group">
        <div class="label">
          <label for="sitename">User Age:</label>
        </div>
        <div class="field">
          <input type="number" class="input w50" id="mpass" name="age" size="50" placeholder="Please enter user age" />       
        </div>
      </div>      
      
      <div class="form-group">
        <div class="label">
          <label for="sitename">Date of birth:</label>
        </div>
        <div class="field">
          <input type="date" class="input w50" id="mpass" name="birthday" size="50" />       
        </div>
      </div>   

8.1.3 Modify the basic form validation that comes with the registration page.
Replace the basic form validation that comes with the registration page with our own form item validation

09 User Registration Function Implementation

9.1 Programming Question
9.1.1 According to the video instructions, continue to complete the registration page, modify the registration page form data submission key name.
User name: name = "uname" password: name = "pwd"
Gender: name = sex; age: name = age
Date of birth: name = "birthday"
9.1.2 Create and declare Servlet s that handle registration functions

public class RegServlet extends HttpServlet {
	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		//Setting Request Encoding Format
		req.setCharacterEncoding("utf-8");
		//Setting the response encoding format
		resp.setContentType("text/html;charset=utf-8");
		//Getting Request Information
		String uname = req.getParameter("uname");
		String pwd = req.getParameter("pwd");
		String num = req.getParameter("sex");
		String sex = null;
		if("1".equals(num)){
			sex = "male";
		}else if("0".equals(num)){
			sex = "female";
		}
		int age = Integer.parseInt(req.getParameter("age"));
		String birthday = req.getParameter("birthday");
		//Processing request information		
		//Getting Business Layer Objects
		UserService us = new UserServiceImpl();
	}
}


9.1.3 Code for Business Layer and Database Layer to Complete Registration Function

int addUserInfoService(String uname, String pwd, String sex, int age,
			String birthday);
@Override
	public int addUserInfoService(String uname, String pwd, String sex,
			int age, String birthday) {
		return ud.addUserInfoDao(uname,pwd,sex,age,birthday);
	}
int addUserInfoDao(String uname, String pwd, String sex, int age,
			String birthday);
@Override
	public int addUserInfoDao(String uname, String pwd, String sex, int age,
			String birthday) {
		String sql = "insert into t_user values(default,?,?,?,?,?)";
		int i = DBUtil.executeDML(sql, uname,pwd,sex,age,birthday);
		return i;
	}

9.1.4 Complete the code logic of registration success and registration failure in regServlet, then run the project, click on registration to observe the operation effect.

int i = us.addUserInfoService(uname,pwd,sex,age,birthday);
		//System.out.println(i);
		//Create or get session objects
		HttpSession session = req.getSession();
		//Response processing results
		if(i>0){
			//Store login results in session
			session.setAttribute("flag", "regSuccess");
			//redirect
			resp.sendRedirect("/project/login.jsp");
		}else{
			resp.sendRedirect("/project/reg.jsp");
		}

10 Successful Tips for Registration-Project Problem Introduction and Solution

10.1 Programming Question
10.1.1 Complete the function of successful registration prompt according to video explanation.
See above
What are the problems of the current project in the 10.1.2 video? ,
Now we have a request or a separate business logic to create a single servlet for request processing. But the function of a website is very many, if each create a separate Servlet for processing, this causes too many Servlets. It wastes resources.
What is the solution given in the 10.1.3 video?
When the server receives the request sent by the browser, it calls the corresponding Servlet to process the request. The Service method in the Servlet is then called for processing. We encapsulate the processing of different functions into corresponding methods. In the service method, the corresponding function processing method is invoked for request processing. So we only need one Servlet.

Implementing Dynamic Call Processing Method in 11 Service (1)

11.1 Programming Question
11.1.1 Create DataServlet based on video, and declare three methods: login, exit and registration.

public class DataServlet extends HttpServlet {
	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		//Setting Request Encoding Format
		req.setCharacterEncoding("utf-8");
		//Setting the response encoding format
		resp.setContentType("text/html;charset=utf-8");
	}
	//User login method
	public void userLogin(HttpServletRequest req, HttpServletResponse resp){
		
	}
	//Method of User Exit
	public void userExit(HttpServletRequest req, HttpServletResponse resp){
			
	}
	//Method of User Registration
	public void userReg(HttpServletRequest req, HttpServletResponse resp){
			
	}
}

11.1.2 Complete the compilation of reflective code for dynamic invocation method processing requests in service method of DataServlet according to video instructions

//Getting Request Information
		String methodName = req.getParameter("method");
		try {
			//Get the class object of the current class
			Class c = this.getClass();
			//Get the class method object of the current class
			Method m = c.getMethod(methodName, HttpServletRequest.class,HttpServletResponse.class);
			//Call the corresponding method
			m.invoke(this, req,resp);
		} catch (Exception e) {
			e.printStackTrace();
		}

Implementing Dynamic Call Processing Method in 12 Service (2)

12.1 Programming Question
12.1.1 Perfect the code implementation of login, registration and exit methods in DataServlet according to video instructions.

//User login method
	public void userLogin(HttpServletRequest req, HttpServletResponse resp) throws IOException{
		//Getting Request Information
				String uname = req.getParameter("uname");
				String pwd = req.getParameter("pwd");
				//Processing request information
//				System.out.println(uname+":"+pwd);
				//Query for this person based on username and password
				//Call service layer for business logic processing
				UserService us = new UserServiceImpl();
				User user = us.getUserInfoService(uname,pwd);
				System.out.println("The user information found is"+user);
				//Response processing results
					//Direct response
					//Request forwarding
				//Create or get session objects
				HttpSession session = req.getSession();
					//redirect
				if(user!=null){//Successful login
					//Successful display of current user information
					session.setAttribute("user", user);
					resp.sendRedirect("/project/main.jsp");
				}else{//Logon failure
					//Failure to display prompt information
					session.setAttribute("flag", "loginFalse");
					resp.sendRedirect("/project/login.jsp");
				}
	}
	//Method of User Exit
	public void userExit(HttpServletRequest req, HttpServletResponse resp) throws IOException{
		//Getting Request Information
				//Processing request information
				//Get the session object
				HttpSession session = req.getSession();
				//Compulsory destruction
				session.invalidate();
				//Response processing results
					//redirect
					resp.sendRedirect("/project/login.jsp");
	}
	//Method of User Registration
	public void userReg(HttpServletRequest req, HttpServletResponse resp) throws IOException{
		//Getting Request Information
				String uname = req.getParameter("uname");
				String pwd = req.getParameter("pwd");
				String num = req.getParameter("sex");
				String sex = null;
				if("1".equals(num)){
					sex = "male";
				}else if("0".equals(num)){
					sex = "female";
				}
				int age = Integer.parseInt(req.getParameter("age"));
				String birthday = req.getParameter("birthday");
				//Processing request information		
				//Getting Business Layer Objects
				UserService us = new UserServiceImpl();
				int i = us.addUserInfoService(uname,pwd,sex,age,birthday);
				System.out.println(i);
				//Create or get session objects
				HttpSession session = req.getSession();
				//Response processing results
				if(i>0){
					//Store login results in session
					session.setAttribute("flag", "regSuccess");
					//redirect
					resp.sendRedirect("/project/login.jsp");
				}else{
					resp.sendRedirect("/project/reg.jsp");
				}
	}

12.1.2 Modify the login page to add hidden notes in the form, add method names in the request data, and complete the login function.

<input type="hidden" name="method" value="userLogin"/>

12.1.3 Modify the exit button to complete the exit function

 <div style="position: relative;left:820px" class="head-l"><span style="font-size: 15px;color: white">The current user is:<%= ((User)session.getAttribute("user")).getUname() %></span>&nbsp;&nbsp;<a class="button button-little bg-red" href="data?method=userExit" id="div_a"><span class="icon-power-off"></span> Log out</a> </div>

12.1.4 Modify the registration page to complete the registration function

<input type="hidden" name="method" value="userReg" />

What was the last question raised in the 12.1.5 video?
Now we use reflection to implement dynamic request processing in the service method by calling the corresponding method according to the request. But in the real development process, although not every function will create a servlet, but will not only use a servlet, our servlet is not only a single function module, generally a servlet. We need to declare the reflection code in the service methods in these servlets.

13 - Extract BaseServlet classes up

13.1 Programming Question
13.1.1 Complete the creation of BaseServlet based on video

public abstract  class BaseServlet extends HttpServlet {
	protected void service(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		//Setting Request Encoding Format
		req.setCharacterEncoding("utf-8");
		//Setting the response encoding format
		resp.setContentType("text/html;charset=utf-8");
		//Getting Request Information
		String methodName = req.getParameter("method");
		try {
			//Get the class object of the current class
			Class c = this.getClass();
			//Get the class method object of the current class
			Method m = c.getMethod(methodName, HttpServletRequest.class,HttpServletResponse.class);
			//Call the corresponding method
			m.invoke(this, req,resp);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

13.1.2 Modify Data Servlet to inherit BaseServlet based on video
Then start the project to re-access the relevant functions.

public class DataServlet  extends BaseServlet{}

13.1.3 What is the process of using BaseServlet?
1. Create a Servlet to inherit BaseServlet.
2. Don't declare service method in your servlet, just write the request processing function method.
3. Request our own servlet normally
Be careful:
The request must be accompanied by the method name to be executed

14 - Project Summary and Defects

14.1 Brief Answer
What are the six items summarized in 14.1.1 video?
1. Fast page construction using template
Create jsp files in your own projects
Then assign the front-end related code in the template to your own jsp file
Copy static resources to webRoot
2. Development process of MVC
M:model service dao pojo
v:view jsp js css html
c:controller Servlet
3. Function Development Process of Servlet+jsp+jdbc
1. Browsers initiate page requests directly to jsp
2. Browser initiates function request to servlet, servlet calls service, service carries on business logic processing.
Service calls dao, the Dao layer performs database operations (jdbc), and the Dao layer returns the processing results to service
The service returns the result to the Servlet (or continues to request forwarding or redirect other servlets to continue processing).
The request is forwarded or redirected to jsp, which responds to the page.
4. Use of request and session scopes
Request: the carrier of data flow for request forwarding
Session: The redirected carrier of data flow (but session can solve the database sharing problem of different requests from the same user).
5. How browsers initiate requests to servers (key memory)
Non-ajax requests
form submission: action data submission address, method: data submission method
Hyperlink tag: href: submit address for data, can you use it directly? Splice request data, similar to form form form get request.
window.location.herf in js: Address submission for data, can you use it directly? Splice request data, similar to form form form get request.
Be careful:
When the browser receives the response content, it will overwrite the original content and display the response results.
6. Extraction and Use of BaseServlet
reflex
abstract class

14.1.2 According to the video, what are the shortcomings of the project?
1. Obtaining data flowing from Servlet in jsp is particularly troublesome
2. It is very inconvenient to write and read logically using java code blocks in jsp pages.
3. It's very convenient to use session for data flow, but session fails, and all session-dependent functions will have problems.
4. The results of the response are displayed to the user by covering the original content.

Topics: Session JSP Programming encoding