Javaweb--JSP development model (including practical projects)

Posted by makeITfunctional on Sat, 08 Jan 2022 16:47:05 +0100

Javaweb - JSP development model (including actual projects)


System development model, that is, system development architecture, is a large structure for integrating application systems. The common system structures are three-tier architecture and MVC. The two architectures are both related and different. The use of these two architectures is to reduce the coupling between system modules.

Four modes

Pure jsp, JSP+JavaBean [Model1], JSP+JavaBean+Servlet [Model2/MVC], MVC

Pure JSP
In the JSP programming mode, various functions can be realized directly in the JSP page by applying the script flag in the JSP. Although this model is easy to implement, its disadvantages are also very obvious. Because confusing most Java code with HTML code will bring many difficulties to program maintenance and debugging, and it is difficult to clarify the complete program structure.
This is like planning and managing a large enterprise. If all employees responsible for different tasks are arranged to work together, it is bound to cause many hidden dangers such as chaotic order and difficult management of the company. Therefore, the simple JSP page programming mode can not be applied to the development of large, medium and even small JSP Web applications.

JSP+JavaBean[Model1]
JSP+JavaBean programming mode is one of the classic design modes of JSP program development, which is suitable for the development of small or medium-sized websites. Using JavaBean technology, you can easily complete some business logic operations, such as database connection, user login and logout, etc.

JSP+JavaBean+Servlet[Model2/MVC]
Although the JSP+JavaBean design pattern has separated the business logic of the website from the display page, the JSP in this pattern should not only control most of the processes in the program, but also be responsible for the display of the page, so it is still not an ideal design pattern.

MVC
MVC (model view controller) is a programming concept, which is suitable for both simple and complex programs. Using this pattern, the application to be developed can be decomposed into three independent parts: model, view and controller. This design pattern is proposed mainly because the code (model, also known as "business logic") used to complete tasks in the application program is usually a relatively stable part of the program and will be reused, while the page (view) of the program interacting with users is often changed.

Actual combat JSP+JavaBean+Servlet [Model2/MVC]

Use JSP+JavaBean+Servlet [Model2/MVC] to realize user registration function
Writing JavaBean s
Writing UserBean classes

package 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;
	}
}

Write the RegisterFromBean class

 package 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;
 	}
 }

Create tool class

package chapter11.model2_util;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.HashMap;

import 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>();
//	public static Connection getCon() throws Exception{
//		Class.forName("com.mysql.cj.jdbc.Driver");
//		Connection users = DriverManager.getConnection("jdbc:mysql://localhost:3306/jdbc?useUnicode=true&characterEncoding=utf8&serverTimezone=UTC","root","123456");
//		return users;
//	}
	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;
	}
}

Create Servlet

package 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 chapter11.model2_domain.RegisterFormBean;
import chapter11.model2_domain.UserBean;
import 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");
	}
}

Create JSP page
Write register jso

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

<%@ page language="java" pageEncoding="GBK" import="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>

Operation effect

Enter your password and click Register

Topics: Java JavaEE mvc java web