Java Web JSP development model (14)

Posted by ejwf on Sat, 08 Jan 2022 12:43:13 +0100

1, Overview
The development model of JSP is JSP Model. In order to use JSP technology more conveniently in web development, SUN company provides two development models for JSP technology: JSP Model1 and JSP Model2.
2, Characteristics
JSP model 1: simple and portable, suitable for the rapid development of small Web projects.
JSP model 2: provides a clearer layering, which is suitable for large-scale Web projects developed by multiple people.
3, JSP Model1
Early model of JSP development: JSP file is an independent module that can complete all tasks independently. It is responsible for business logic, controlling web page process and page display.
HTML code and Java code in JSP pages are strongly coupled, which makes the code very poor readability.
Data, business logic and control process are mixed together, which makes the program difficult to modify and maintain.
In order to solve the above problems, SUN company provides an architecture model for JSP development: JSP Model1
JSP Model1 overview:
JSP+JavaBean technology is adopted to separate the page and business logic. JSP is responsible for process control and page display, and JavaBean is responsible for data encapsulation and business logic. JSP is only responsible for receiving user requests and calling JavaBeans to respond to user requests. This design realizes the separation of data, business logic and page display, realizes the modularization of program development to a certain extent, and reduces the difficulty of program modification and maintenance.
4, JSP Model2
Problem: Although JSP model 1 separates the data and part of the business logic from JSP, JSP pages still need to be responsible for process control and generating user pages. A lot of Java code is embedded in JSP pages, which will bring great trouble to project management.
In order to solve the above problems, SUN company provides JSP Model2.

summary:
JSP Model2 architecture model adopts the technology of JSP+Servlet+JavaBean, which extracts the process control code from the original JSP page and encapsulates it into the Servlet, so as to realize the separation of page display, process control and business logic. In fact, the JSP Model2 model is the MVC design pattern (model: Model View: View Controller: controller). Among them, Servlet is the controller, JSP is the view, and JavaBean is the model.

**Process: * * first, the Servlet receives the request sent by the browser, then instantiates the JavaBean object according to the request information to encapsulate the data returned after operating the database, and finally selects the corresponding JSP page to display the corresponding structure in the browser.

1. Create a project and write JavaBean Java class
(1) Write UserBean to encapsulate user information

package cn.itcast.chapter11.model2.domain;
public class UserBean {
	private String name;            //Define user name
	private String password;       //Define password
	private String email;           //Define mailbox
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	public String getEmail() {
		return email;
	}
	public void setEmail(String email) {
		this.email = email;
	}
}

(2) Write the registerformbean class to encapsulate the registration form information

 package cn.itcast.chapter11.model2.domain;
 import java.util.HashMap;
 import java.util.Map;
 public class RegisterFormBean {
 	private String name;            //Define user name
 	private String password;       //Define password
 	private String password2;      //Define confirmation password
 	private String email;           //Define mailbox
      // Define the member variable errors to encapsulate the error information during form validation
 	private Map<String, String> errors = new HashMap<String, String>();
 	public String getName() {
 		return name;
 	}
 	public void setName(String name) {
 		this.name = name;
 	}
 	public String getPassword() {
 		return password;
 	}
 	public void setPassword(String password) {
 		this.password = password;
 	}
 	public String getPassword2() {
 		return password2;
 	}
 	public void setPassword2(String password2) {
 		this.password2 = password2;
 	}
 	public String getEmail() {
 		return email;
 	}
 	public void setEmail(String email) {
 		this.email = email;
 	}
 	public boolean validate() {
 		boolean flag = true;
 		if (name == null || name.trim().equals("")) {
 			errors.put("name", "Please enter your name.");
 			flag = false;
 		}
 		if (password == null || password.trim().equals("")) {
 			errors.put("password", "Please input a password.");
 			flag = false;
 		} else if (password.length() > 12 || password.length() < 6) {
 			errors.put("password", "Please enter 6-12 Characters.");
 			flag = false;
 		}
 		if (password != null && !password.equals(password2)) {
 			errors.put("password2", "The passwords entered twice do not match.");
 			flag = false;
 		}
 		// Regular expressions are used to check the email format
 		if (email == null || email.trim().equals("")) {
 			errors.put("email", "Please enter email address.");
 			flag = false;
 		} else if (!email.matches("[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\\.[a-zA-Z0-9_-]+)+")) {
 			errors.put("email", "Mailbox format error.");
 			flag = false;
 		}
 		return flag;
 	}
     // Add error information to the Map collection errors
 	public void setErrorMsg(String err, String errMsg) {
 		if ((err != null) && (errMsg != null)) {
 			errors.put(err, errMsg);
 		}
 	}
     // Gets the errors collection
      public Map<String, String> getErrors() {
 		return errors;
 	}
 }

2. Create a tool class

Define DBUtill class

p

ackage cn.itcast.chapter11.model2.util;
import java.util.HashMap;
import cn.itcast.chapter11.model2.domain.UserBean;
public class DBUtil {
private static DBUtil instance = new DBUtil();   //
// Define the users collection to simulate the database
private HashMap<String,UserBean> users = new HashMap<String,UserBean>();
	private DBUtil() {
		// Store two pieces of data into the database (users)
		UserBean user1 = new UserBean();
		user1.setName("Jack");
		user1.setPassword("12345678");
		user1.setEmail("jack@it315.org");
		users.put("Jack ",user1);
		
		UserBean user2 = new UserBean();
		user2.setName("Rose");
		user2.setPassword("abcdefg");
		user2.setEmail("rose@it315.org");
		users.put("Rose ",user2);			
	}
	public static DBUtil getInstance()	{
		return instance;
	}
	// Get data in the database (users)
	public UserBean getUser(String userName) {
		UserBean user = (UserBean) users.get(userName);
		return user;
	}
	// Insert data into the database (users)
	public boolean insertUser(UserBean user) {
		if(user == null) {
			return false;
		}
		String userName = user.getName();
		if(users.get(userName) != null) {
			return false;
		}
		users.put(userName,user);
		return true;
	}
}

3. Create a Servlet

Define the ControllerServlet class to process user requests

package cn.itcast.chapter11.model2.web;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import cn.itcast.chapter11.model2.domain.RegisterFormBean;
import cn.itcast.chapter11.model2.domain.UserBean;
import cn.itcast.chapter11.model2.util.DBUtil;
public class ControllerServlet extends HttpServlet {
	public void doGet(HttpServletRequest request,
	HttpServletResponse response) throws ServletException, IOException {
		this.doPost(request, response);
	}
	public void doPost(HttpServletRequest request,
	HttpServletResponse response) throws ServletException, IOException {
        response.setHeader("Content-type", "text/html;charset=GBK");  
		response.setCharacterEncoding("GBK");
		// Get the parameter information submitted by the form during user registration
		String name = request.getParameter("name");
		String password=request.getParameter("password");
		String password2=request.getParameter("password2");
		String email=request.getParameter("email");
		// Encapsulate the obtained parameters into the RegisterFormBean class related to the registry form
		RegisterFormBean formBean = new RegisterFormBean();
		formBean.setName(name);
		formBean.setPassword(password); 
		formBean.setPassword2(password2);
		formBean.setEmail(email);
		// Verify whether the parameter filling meets the requirements. If not, forward it to register JSP refill
		if(!formBean.validate()){
			request.setAttribute("formBean", formBean);
			request.getRequestDispatcher("/register.jsp").forward(request, response);
			return;
		}
		// If the parameter filling meets the requirements, the data will be encapsulated in the UserBean class
		UserBean userBean = new UserBean();
		userBean.setName(name);
		userBean.setPassword(password);
		userBean.setEmail(email);
        // Call the insertUser() method in the DBUtil class to perform the add operation and return a boolean flag
		boolean b = DBUtil.getInstance().insertUser(userBean);
        // If false is returned, it indicates that the registered user already exists and redirects to register JSP refill
		if(!b){
			request.setAttribute("DBMes", "The user you registered already exists");
              request.setAttribute("formBean", formBean);
		     request.getRequestDispatcher("/register.jsp").forward(request, response);
			return;
		}
		response.getWriter().print("Congratulations on your successful registration. Jump automatically in 3 seconds");
		// Add the successfully registered user information to the Session
		request.getSession().setAttribute("userBean", userBean);
		// After successful registration, jump to login success page loginsuccess.com in 3 seconds jsp
		response.setHeader("refresh", "3;url=loginSuccess.jsp");
	}
}

4. Create JSP page

(1) User registration form

<%@ page language="java" pageEncoding="GBK"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 
Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
    <head>
    <title>User registration</title>
    <style type="text/css">
        h3 {
	        margin-left: 100px;
        }
        #outer {
	        width: 750px;
        }
        span {
	        color: #ff0000
        }
        div {
             height:20px;
	        margin-bottom: 10px;
        }
        .ch {
	        width: 80px;
	        text-align: right;
	        float: left;
        }
        .ip {
	        width: 500px;
	        float: left
        }
        .ip>input {
	        margin-right: 20px
        }
        #bt {
	        margin-left: 50px;
        }
        #bt>input {
	        margin-right: 30px;
        }
    </style>
</head>
<body>
	    <form action="ControllerServlet" method="post">
		    <h3>User registration</h3>
		    <div id="outer">
			    <div>
				    <div class="ch">full name:</div>
				    <div class="ip">
				<input type="text" name="name" value="${formBean.name }" />
					    <span>${formBean.errors.name}${DBMes}</span>
				    </div>
			    </div>
			    <div>
				    <div class="ch">password:</div>
				    <div class="ip">
					    <input type="password" name="password" />
					    <span>${formBean.errors.password}</span>
				    </div>
			    </div>
			    <div>
				    <div class="ch">Confirm password:</div>
				    <div class="ip">
					    <input type="password" name="password2" />
					    <span>${formBean.errors.password2}</span>
				    </div>
			    </div>
			    <div>
				    <div class="ch">mailbox:</div>
				    <div class="ip">
			<input type="text" name="email" value="${formBean.email }" />
					    <span>${formBean.errors.email}</span>
				    </div>
			    </div>
			    <div id="bt">
				    <input type="reset" value="Reset " />
				    <input type="submit" value="register" />
			    </div>
		    </div>
	    </form>
</body>
</html>

(2) Write loginsuccess JSP file

<%@ page language="java" pageEncoding="GBK" import="cn.itcast.chapter11.model2.domain.UserBean"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 
Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>login successfully</title>
    <style type="text/css">
        #main {
	        width: 500px;
	        height: auto;
        }
        #main div {
	        width: 200px;
	        height: auto;
        }
        ul {
	        padding-top: 1px;
	        padding-left: 1px;
	        list-style: none;
        }
    </style>
</head>
<body>
	    <%
		    if (session.getAttribute("userBean") == null) {
	    %>
	    <jsp:forward page="register.jsp" />
	    <%
		    return;
		    }
	    %>
	    <div id="main">
		    <div id="welcome">Congratulations, login succeeded</div>
             <hr />
		    <div>Your information</div>
		    <div>
			    <ul>
				    <li>Your name:${userBean.name }</li>
				    <li>Your email:${userBean.email }</li>
			    </ul>
		    </div>
	    </div>
</body>
</html>

Topics: Java Front-end mvc