Day 14 of learning Java Web

JSP development model

Two models of JSP development
Using JSP technology to develop Web applications, there are two architectural models to choose from. Commonly referred to as Model1 and Model2
1.Model1
Model 1 uses JSP+JavaBean technology to separate page display from business logic processing. JSP realizes page display, and JavaBean objects are used to save data and realize business logic.
In model 1, the JSP page responds to the request alone and returns the processing results to the customer. All the data is processed through the JavaBean, and the JSP realizes the page display.
jsp+javabean development pattern architecture diagram

In jsp+javabean architecture, JSP is responsible for the call of control logic, presentation logic and business object (javabean).

JSP+JavaBean mode is suitable for developing web applications with less complex business logic. In this mode, JavaBeans are used to encapsulate business data. JSP is responsible for processing user requests and displaying data.
2.Model2
In model 1, the JSP page embeds the process control code and part of the logic processing code. We can extract this part of the code and put it into a separate role, which is the controller role. Such a Web architecture is model 2 Model 2 conforms to the MVC architecture pattern. MVC is model view controller.
In model 2, the role of controller is realized by Servlet, the role of view is realized by JSP page, and the role of model is realized by JavaBean. The Model2 architecture is shown in the following figure:

The Servlet acts as a controller. It accepts requests and distributes them to the appropriate JSP page according to the request information to generate a response. The Servlet controller also generates instances of JavaBeans according to the requirements of JSP views and inputs them to the JSP environment. JSP view can get the data in JavaBean by directly calling the methods of JavaBean instance or using and action elements.
Servlet+JSP+JavaBean development mode
In normal Java Web project development, without using the third-party MVC development framework, the Servlet+JSP+JavaBean development mode is usually selected to develop java web projects. Servlet+JSP+JavaBean combined development is an MVC development mode. The controller adopts servlet, the model adopts JavaBean and the view adopts JSP. Before explaining the Servlet+JSP+JavaBean development mode, first briefly understand the MVC development mode.

        request response model in Web Development

In the Web world, the specific steps are as follows:

1. A Web browser (e.g. IE) initiates a request, such as access http://www.iteye.com/

2. The Web server (such as Tomcat) receives the request, processes the request (for example, if a user is added, the user will be saved), and finally generates a response (usually html).

3. After processing, the web server returns the content to the web client (generally our browser), and the client processes the received content (for example, the web browser will render the received html content to show it to the client).

Therefore, in the Web world: all requests are initiated by the Web client, and the Web server receives, processes and generates a response.

Generally, the Web server cannot actively notify the Web client to update the content. Although some technologies such as server push (such as Comet) and HTML5 websocket can realize the Web server to actively notify the Web client.

Now that we understand the request / response model in web development, let's take a look at what the standard MVC model is.
  
Standard MVC Model Overview
MVC model: it is an architectural model. It does not introduce new functions, but only helps us organize the developed structure more reasonably, so as to separate presentation from model, process control logic, business logic call and presentation logic. As shown in the figure below:
  
Concept of MVC (model view controller)
First, let's understand the concept of MVC (model view controller):

Model: the data model provides the data to be displayed, so it contains data and behavior. It can be considered as a domain model or JavaBean component (including data and behavior), but now it is generally separated: Value Object (data) and service layer (behavior). That is, the model provides functions such as model data query and model data status update, including data and business.

View: it is responsible for displaying the model, which is generally the user interface we see and what customers want to see.

Controller: receives the user's request and delegates it to the model for processing (state change). After processing, the returned model data is returned to the view, which is responsible for displaying it. In other words, the controller does the work of a dispatcher.

In standard MVC, the model can actively push data to the view for updating (observer design pattern, register the view on the model, and automatically update the view when the model is updated), but in Web development, the model cannot actively push to the view (the user interface cannot be actively updated), because in Web development, it is a request response model.

The Servlet+JSP+JavaBean architecture can actually be regarded as what we call the Web MVC model, except that the controller adopts Servlet, the model adopts JavaBean and the view adopts JSP, as shown in the figure:

Note: in model 1, the JSP page alone responds to the request and returns the processing results to the customer. The JSP should be responsible for both business process control and providing presentation layer data, and act as a view and controller at the same time. In model 2, the Servlet accepts the request, creates the JavaBean object to be used by the JSP page, and selects the appropriate JSP page to return to the user according to the user's request. There is no processing logic in the JSP page. It is only responsible for retrieving the JavaBean object originally created by the Servlet, extracting dynamic content from the Servlet and inserting it into the static template.

Implement the user registration function according to the idea of model 2
Implementation steps
(1) Create a project and write a JavaBean
  ① write UserBean class

package cn.itcast.chapter11.model2.domain;
/**
 * Used to encapsulate the user's basic parameters
 * @author apple
 *
 */
public class UserBean {
	private String name;
	private String password;
	private String email;
	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;
	}
	
	
}  

② Write the RegisteFormBean class

package cn.itcast.chapter11.model2.domain;

import java.util.HashMap;
import java.util.Map;

public class RegisterFormBean {

	//1. Used to encapsulate registration parameters
	private String name;
	private String password;
	private String password2;
	private String email;
	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;
	}
	//------------Data of the server-----------------------
	//2. Define variables to receive user verification information, such as whether the user name and mailbox meet the specifications,
	//The first parameter is the attribute name, and the second parameter is whether the attribute value conforms to the specification information, such as ("email", "incorrect mailbox format");
	private Map<String,String> errors = new HashMap<String,String>();
	public boolean validate(){
		//2. Define variables to judge whether the data meets the specification. If it meets the specification, it returns true, and if not, it returns false
		boolean flag = true;
		if(name == null || name.trim().equals("")){
			errors.put("name","enter one user name");
			flag = false;
			return flag;
		}
		if(password == null || password.trim().equals("")){
			errors.put("password","Please input a password");
			flag = false;
			return flag;
		}else if(password.length()>12 || password.length()<6){
			errors.put("password","Please enter 6-12 Characters");
			flag = false;
			return flag;
		}
		if(password != null && !password.equals(password2)){
			errors.put("password2","The two passwords are inconsistent");
			flag = false;
			return flag;
		}
		//Verify whether the mailbox format meets the specification
		  String regex = "[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\\.[a-zA-Z0-9_-]+)+";
		  if(email == null || email.trim().equals("")){
				errors.put("email","Please enter email address");
				flag = false;
				return flag;
		 }else if(!email.matches(regex)){
				errors.put("email","Mailbox format error");
				flag = false;
				return flag;
		}
		
			return flag;
	}
	//Method for obtaining error information
	public Map<String, String> getErrors() {
		return errors;
	}
	//Provides error information for adding to the map collection
	public void setErrorMsg(String err,String errMsg){
		if((err != null) && (errMsg!=null)){
			errors.put(err, errMsg);
		}
	}
}

(2) Create DBUtil tool class

package cn.itcast.chapter11.model2.util;

import java.util.HashMap;

import cn.itcast.chapter11.model2.domain.UserBean;

/*
 * Simulation database
 */
/*
 * Simulation database
 */
public class DBUtil {
	private static DBUtil instance = new DBUtil();
	public static  DBUtil getInstance(){
		return instance;
	}
	//Define a collection to store user registered data
	private HashMap<String, UserBean> users = new HashMap<String, UserBean>();
	
	//Insert 2 pieces of data
	public DBUtil(){
		UserBean user1 = new UserBean();
		user1.setName("Jack");
		user1.setPassword("123456");
		user1.setEmail("jack@it315.org");
		users.put("Jack",user1);
		UserBean user2 = new UserBean();
		user2.setName("Rose");
		user2.setPassword("abcdefr");
		user2.setEmail("rose@it315.org");
		users.put("Rose",user2);
	
	}
	//Method to get value
	public UserBean getUser(String username){
		UserBean user = users.get(username);
		return user;
	}
	//Provides a method to insert a database
	public boolean insertUser(UserBean user){
		//The user is null and cannot be inserted
		if(user == null){
			return false;
		}
		//Determine whether the user name is duplicate
		String username = user.getName();//Parameters of registration submitted by the user
		//String usernameDB = users.get(username).getName();// User name queried from the database
		UserBean userDB = users.get(username);
		if(userDB !=null){//Query the user object in the database according to the registration parameters, indicating that the user name exists
			return false;
		}
		users.put(username,user);
		return true;
		
	}
}

(3) Create Servlet

package cn.itcast.chapter11.model.web;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.BeanUtils;

import cn.itcast.chapter11.model2.domain.RegisterFormBean;
import cn.itcast.chapter11.model2.domain.UserBean;
import cn.itcast.chapter11.model2.util.DBUtil;

/**
 * Servlet implementation class ControllerServlet
 */
@WebServlet("/ControllerServlet")
public class ControllerServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.setContentType("text/html;charset=utf-8");
		request.setCharacterEncoding("utf-8");
		//BeanUtils.populate(new RegisterFormBean(), request.getParameterMap());
		String name=request.getParameter("name");
		String password=request.getParameter("password");
		String password2=request.getParameter("password2");
		String email=request.getParameter("email");
		
		RegisterFormBean formBean=new RegisterFormBean();
		formBean.setName(name);
		formBean.setPassword(password);
		formBean.setPassword2(password2);
		formBean.setEmail(email);
		
		if(!formBean.validate()) {
			request.setAttribute("formBean", formBean);
			request.getRequestDispatcher("/register.jsp").forward(request, response);
			return;
		}
		
		UserBean userBean=new UserBean();
		
		userBean.setName(name);
		userBean.setPassword(password);
		userBean.setEmail(email);
		//If a real database is connected, this is the operation or calling dao to operate the database
		//We are simulations
		boolean b=DBUtil.getInstance().insertUser(userBean);
		
		if(!b) {
			
			request.setAttribute("DBMes", "User name already exists");
			request.setAttribute("formBean", formBean);
			request.getRequestDispatcher("/register.jsp").forward(request, response);
			return;
		}
		
		//It has been inserted successfully
		
		response.getWriter().print("Congratulations on your successful registration. Jump automatically in 3 seconds");
		
		request.getSession().setAttribute("userBean", userBean);
		
		response.setHeader("refresh", "3,url=loginSuccess.jsp");
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}

(4) Create JSP page
  ① write register JSP file

<%@ 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>

② Write loginsuccess JSP file

<%@ page language="java" pageEncoding="GBK" import="cn.itcast.chapter11.model2.domain.UserBean"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core"  prefix="c" %>
<!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>
	   
	    <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>

Operation results

Enter a different password

login was successful

Keywords: Java

Added by mauri_gato on Sat, 08 Jan 2022 18:07:17 +0200