[JavaWeb] MVC design pattern introduction and Servlet detailed explanation


One MVC design pattern:

M Odel model : the application is a part of the application data processing logic . Usually model objects are responsible for accessing data in the database . (Implementedusing JavaBean .)

V IEW view : the application is part of the process data displayed . Usually views are created based on model data . (For display and interaction with users, using front-end technologies such as html, css, js, jsp, jquery, etc. )

C ontroller controller : is the part of the application that handles user interaction . Usually the controller is responsible for reading data from the view , controlling user input , and sending data to the model . (Receive the request, jump the request to the model for processing, after the model is processed, the result of the processing is returned to the request, it is recommended to use Servlet )


Two Servlet detailed explanation:

1 Servlet definition:

Servlet is a Java class that conforms to certain specifications:
    (1) It must inherit javax.servlet.http.HttpServlet
    (2) Rewrite the doGet () method, doPost () method

doGet( ) : Receive and process all get submission method requests
doPost( ) : Receive and process all post submission method requests


2 Servlet configuration:

(1) Servlet 2.5 :

若为Servlet 2.5 :配置 web.xml 文件
Steps: (can be automatically generated by creating a new Servlet)

write a class, inherited HttpServlet
override the doGet () method, doPost () method
write servlet mapping in web.xml relations


Process:
Request (the root directory of the project) ➡ url-pattern ➡ Match the servlet-name in the servlet according to the servlet-name in the servlet-mapping, then find the servlet-class, and finally submit the request to the servlet-class for execution


Code:

index.jsp: (run separately at mothod=get and pos t)

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
		<form action="WelcomeServlet" method="get"> //get方法
			<input type="submit" value="提交">
		</form>
</body>
</html>

WelcomeServlet.java:

package org.lanqiao.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class WelcomeServlet extends HttpServlet{
     
     
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
     
     
		System.out.println("this is doGet!!!"); 
	}
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
     
     
		System.out.println("this is doPost!!!");
	}
}

web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>Servlet25Project</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  
  <servlet>
    <servlet-name>WelcomeServlet</servlet-name>
    <servlet-class>org.lanqiao.servlet.WelcomeServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>WelcomeServlet</servlet-name>
    <url-pattern>/WelcomeServlet</url-pattern>
  </servlet-mapping>
</web-app>

Run results (jsp method run with get and post respectively):

Insert picture description here



(2) Servlet 3.0 :

若为Servlet 3.0 :@WebServlet 注解
the difference:

No need to configure in web.xml , but need to write annotation @WebServlet("url-pattern") in Servlet class


Matching process:

Request address and a value of @WebServlet match , if the matching is successful, then the request is the annotation of the corresponding class .

Code:

index.jsp file (unchanged):

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
		<form action="WelcomeServlet" method="get">
			<input type="submit" value="提交">
		</form>
</body>
</html>

WelcomeServlet.java

package org.lanqiao.Servlet;

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;

/**
 * Servlet implementation class WelcomeServlet
 */
@WebServlet("/WelcomeServlet")
public class WelcomeServlet extends HttpServlet {
     
     
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
     
     
		System.out.println("this is Servlet3.0");
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
     
     
		doGet(request, response);
	}
}

web.xml (no need to configure servlet and servlet-mapping)

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>Servlet30Project</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
</web-app>
operation result:

Insert picture description here





3 Servlet life cycle (5 stages):

1 Load (servlet is executed automatically)

2 Initialization : init(), this method will be executed after the Servlet is loaded and instantiated

(1) By default, it is executed when the Servlet is accessed for the first time (executed only once)
(2) It can be modified to be automatically executed when Tomcat starts:

   ① Add the Servlet configuration in web.xml in Servlet 2.5

<load-on-startup>1</load-on-startup>

   ② Modify the annotation in Servlet 3.0 to:

@WebServlet(value="/WelcomeServlet" , loadOnStartup=1)

3 Service : service()➡doGet() doPost(): execute several times after several calls

4 Destroy : destroy(), this method is executed when the servlet is recycled by the system

5 Uninstall (servlet is executed automatically)

operation result:

Insert picture description here





4 Servlet API :

It is composed of two software packages: the software package corresponding to the HTTP protocol , which corresponds to other software packages except the HTTP protocol . ( Applicable to any communication protocol )


5 Servlet inheritance relationship

(1) ServletConfig: Interface

ServletContext getServletContext(): Get the Servlet context object

String getInitParamter(String name): Get the parameter value of name (initialization parameter) in the current Servlet range

(2) Common methods in ServletContext (application is an object):

① getContextPath(): relative path
② getRealPath(): absolute path
③ setAttribute():
④ getAttribute():
⑤ String getInitParameter(String name): Get the parameter value of name (initialization parameter) within the scope of the current web container

(3) Method (request) in HttpServletRequest:

(The request in jsp is HttpServletRequest, so the method is the same)
For example: setAttribute(), getCookies(), getMethod()

(4) Methods in HttpServletResponse (response):

(Same as response in jsp)

Guess you like

Origin blog.csdn.net/weixin_45260385/article/details/109440647