Servlet&HTTP&Reques

Posted by kaveman50 on Thu, 15 Aug 2019 13:41:12 +0200

Servlet:

1. Concept
 2. Steps
 3. Executive Principle
 4. Life cycle
 5. Servlet 3.0 Annotation Configuration
 6. Servlet architecture	
	Servlet -- Interface
		|
	GenericServlet -- abstract class
		|
	HttpServlet -- abstract class

	* Generic Servlet: The other methods in the Servlet interface are implemented by default empty, and only the service() method is abstracted.
		* When defining Servlet classes in the future, you can inherit GenericServlet and implement the service() method.

	* HttpServlet: An encapsulation of http protocol to simplify operation
		1. Definition class inherits HttpServlet
		2. Rewriting doGet/doPost Method

7. Servlet-related configuration
	1. urlpartten:Servlet access path
		1. A Servlet can define multiple access paths: @WebServlet ({"/d4", / dd4", / ddd4"})
		2. Path Definition Rules:
			1. /xxx: Path matching
			2. /xxx/xxx: Multilayer paths, directory structure
			3. *.do: Extension matching

HTTP:

* Concept: Hyper Text Transfer Protocol Hyper Text Transfer Protocol
	* Transport protocol: Defines the format of sending data when communicating between client and server
	* Characteristic:
		1. Be based on TCP/IP High-level agreements
		2. Default port number:80
		3. Request-based/Response model:A request corresponds to a response
		4. Stateless: Each request is independent of each other and cannot interact with data

	* Historical Version:
		* 1.0: Each request response establishes a new connection
		* 1.1: Multiplexing connection

* Request message data format
	1. Request bank
		//Request mode request url request protocol/version
		GET /login.html	HTTP/1.1

		* Request method:
			* HTTP There are 7 request modes in the protocol, and there are 2 common ones.
				* GET: 
					1. The request parameters are in the request line, in the url Later.
					2. Requested url Limited length
					3. Not very safe
				* POST: 
					1. Request parameters are in the body of the request
					2. Requested url Length unrestricted
					3. Relative safety
	2. Request header: The client browser tells the server some information
		//Request Header Name: Request Header Value
		* Common request headers:
			1. User-Agent: The browser tells the server that I access the version information of the browser you use.
				* The information of the header can be obtained on the server side to solve the compatibility problem of browsers.

			2. Referer: http://localhost/login.html
				* Tell the server, I(Current request)Where do you come from?
					* Effect:
						1. Anti-theft Chain:
						2. Statistical work:
	3. Request blank line
		//The blank line is used to split the request header and body of the POST request.
	4. Requestor(text): 
		* encapsulation POST Request parameter of request message

	* String format:
		POST /login.html	HTTP/1.1
		Host: localhost
		User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:60.0) Gecko/20100101 Firefox/60.0
		Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
		Accept-Language: zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2
		Accept-Encoding: gzip, deflate
		Referer: http://localhost/login.html
		Connection: keep-alive
		Upgrade-Insecure-Requests: 1
		
		username=zhangsan	


* Response message data format

Request:

1. Principle of request object and response object
	1. request and response objects are created by the server. Let's use them.
	2. The request object is to get the request message, and the response object is to set the response message.

2. request object inheritance architecture:	
	ServletRequest -- Interface
		| Inheritance
	HttpServletRequest -- Interface
		| Realization
	org.apache.catalina.connector.RequestFacade class (tomcat)

3. request function:
	1. Get request message data
		1. Get request row data
			* GET /day14/demo1?name=zhangsan HTTP/1.1
			* Methods:
				1. Access request mode: GET
					* String getMethod()  
				2. (*) Get the virtual directory: / day14
					* String getContextPath()
				3. Get the Servlet path: / demo1
					* String getServletPath()
				4. Get get mode request parameter: name=zhangsan
					* String getQueryString()
				5. (*) Get the request URI:/day14/demo1
					* String getRequestURI():		/day14/demo1
					* StringBuffer getRequestURL()  :http://localhost/day14/demo1

					* URL s: Unified Resource Locator: http://localhost/day14/demo1 People's Republic of China
					* URI: Unified Resource Identifier: / day14/demo1 Republic
				
				6. Access Protocol and Version: HTTP/1.1
					* String getProtocol()

				7. Get the IP address of the client:
					* String getRemoteAddr()
				
		2. Get the request header data
			* Methods:
				* (*) String getHeader(String name): Gets the value of the request header by the name of the request header
				* Enumeration < String > getHeaderNames (): Get all request header names
			
		3. Get the request body data:
			* Request body: Only the POST request mode can have the request body, which encapsulates the request parameters of the POST request.
			* Steps:
				1. Getting stream objects
					* BufferedReader getReader(): Gets the character input stream and can only operate on character data
					* ServletInputStream getInputStream(): Gets a byte input stream that can manipulate all types of data
						* Explain after uploading knowledge points

				2. Retrieve the data from the stream object
			
			
	2. Other functions:
		1. General way to get request parameters: either get or post request can use the following methods to get request parameters
			1. String getParameter(String name): Get the parameter value username = ZS & password = 123 based on the parameter name
			2. String[] getParameterValues(String name): Array hobby = XX & Hobby = game to get parameter values based on parameter names
			3. Enumeration < String > getParameterNames (): Get the parameter names of all requests
			4. Map < String, String []> getParameterMap (): Get the map set of all parameters

			* Chinese scrambling problem:
				* get mode: tomcat 8 has solved the problem of get mode scrambling
				* Posting: scrambling
					* Solution: Set the request encoding request.setCharacterEncoding("utf-8") before getting the parameters.
		
				
		2. Request Forwarding: A Resource Jumping Method within the Server
			1. Steps:
				1. Get the request forwarder object through the request object: RequestDispatcher getRequestDispatcher(String path)
				2. Use the RequestDispatcher object to forward: forward(ServletRequest request, ServletResponse response) 

			2. Characteristics:
				1. Browser Address Bar Path does not change
				2. It can only be forwarded to the internal resources of the current server.
				3. Forwarding is a request


		3. Sharing data:
			* Domain object: A scoped object that can share data within a scope
			* Request domain: Represents the scope of a request and is generally used to share data among multiple resources for request forwarding
			* Methods:
				1. void setAttribute(String name,Object obj): Store data
				2. Object getAttitude(String name): Get values by key
				3. void removeAttribute(String name): Remove key-value pairs by key

		4. Get ServletContext:
			* ServletContext getServletContext()

Case: User login

* User login case requirements:
	1.To write login.html Login page
		username & password Two input boxes
	2.Use Druid Database Connection Pool Technology,operation mysql,day14 Database user surface
	3.Use JdbcTemplate Technology Packaging JDBC
	4.Logon successfully jumped to SuccessServlet Show: Log in successfully! User name,Welcome
	5.Logon Failure Jump to FailServlet Show: Logon failure, user name or password error


* Analysis

* Development steps
	1. Create projects, import html Pages, configuration files, jar package
	2. Creating a database environment
		CREATE DATABASE day14;
		USE day14;
		CREATE TABLE USER(
		
			id INT PRIMARY KEY AUTO_INCREMENT,
			username VARCHAR(32) UNIQUE NOT NULL,
			PASSWORD VARCHAR(32) NOT NULL
		);

	3. create package cn.itcast.domain,Create classes User
		package cn.itcast.domain;
		/**
		 * User's Entity Class
		 */
		public class User {
		
		    private int id;
		    private String username;
		    private String password;
		
		
		    public int getId() {
		        return id;
		    }
		
		    public void setId(int id) {
		        this.id = id;
		    }
		
		    public String getUsername() {
		        return username;
		    }
		
		    public void setUsername(String username) {
		        this.username = username;
		    }
		
		    public String getPassword() {
		        return password;
		    }
		
		    public void setPassword(String password) {
		        this.password = password;
		    }
		
		    @Override
		    public String toString() {
		        return "User{" +
		                "id=" + id +
		                ", username='" + username + '\'' +
		                ", password='" + password + '\'' +
		                '}';
		    }
		}
	4. create package cn.itcast.util,Writing Tool Classes JDBCUtils
		package cn.itcast.util;

		import com.alibaba.druid.pool.DruidDataSourceFactory;
		
		import javax.sql.DataSource;
		import javax.xml.crypto.Data;
		import java.io.IOException;
		import java.io.InputStream;
		import java.sql.Connection;
		import java.sql.SQLException;
		import java.util.Properties;
		
		/**
		 * JDBC Tool classes use the Durid connection pool
		 */
		public class JDBCUtils {
		
		    private static DataSource ds ;
		
		    static {
		
		        try {
		            //1. Loading configuration files
		            Properties pro = new Properties();
		            //Use ClassLoader to load the configuration file to get the byte input stream
		            InputStream is = JDBCUtils.class.getClassLoader().getResourceAsStream("druid.properties");
		            pro.load(is);
		
		            //2. Initialize connection pool objects
		            ds = DruidDataSourceFactory.createDataSource(pro);
		
		        } catch (IOException e) {
		            e.printStackTrace();
		        } catch (Exception e) {
		            e.printStackTrace();
		        }
		    }
		
		    /**
		     * Get the connection pool object
		     */
		    public static DataSource getDataSource(){
		        return ds;
		    }
		
		
		    /**
		     * Get the Connection object
		     */
		    public static Connection getConnection() throws SQLException {
		        return  ds.getConnection();
		    }
		}
	5. create package cn.itcast.dao,Create classes UserDao,provide login Method
		
		package cn.itcast.dao;

		import cn.itcast.domain.User;
		import cn.itcast.util.JDBCUtils;
		import org.springframework.dao.DataAccessException;
		import org.springframework.jdbc.core.BeanPropertyRowMapper;
		import org.springframework.jdbc.core.JdbcTemplate;
		
		/**
		 * Classes that operate on User tables in a database
		 */
		public class UserDao {
		
		    //Declare JDBCTemplate object sharing
		    private JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());
		
		    /**
		     * Login method
		     * @param loginUser Only username and password
		     * @return user Contains all user data, no query, return null
		     */
		    public User login(User loginUser){
		        try {
		            //1. Writing sql
		            String sql = "select * from user where username = ? and password = ?";
		            //2. Call query method
		            User user = template.queryForObject(sql,
		                    new BeanPropertyRowMapper<User>(User.class),
		                    loginUser.getUsername(), loginUser.getPassword());
		
		
		            return user;
		        } catch (DataAccessException e) {
		            e.printStackTrace();//Logging
		            return null;
		        }
		    }
		}
	
	6. To write cn.itcast.web.servlet.LoginServlet class
		package cn.itcast.web.servlet;

		import cn.itcast.dao.UserDao;
		import cn.itcast.domain.User;
		
		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 java.io.IOException;
		
		
		@WebServlet("/loginServlet")
		public class LoginServlet extends HttpServlet {
		
		
		    @Override
		    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		        //1. Setting Coding
		        req.setCharacterEncoding("utf-8");
		        //2. Get the request parameters
		        String username = req.getParameter("username");
		        String password = req.getParameter("password");
		        //3. Encapsulating user objects
		        User loginUser = new User();
		        loginUser.setUsername(username);
		        loginUser.setPassword(password);
		
		        //4. Call the login method of UserDao
		        UserDao dao = new UserDao();
		        User user = dao.login(loginUser);
		
		        //5. Judging user
		        if(user == null){
		            //Logon failure
		            req.getRequestDispatcher("/failServlet").forward(req,resp);
		        }else{
		            //Successful login
		            //Storage of data
		            req.setAttribute("user",user);
		            //Forward
		            req.getRequestDispatcher("/successServlet").forward(req,resp);
		        }
		
		    }
		
		    @Override
		    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		        this.doGet(req,resp);
		    }
		}

	7. To write FailServlet and SuccessServlet class
		@WebServlet("/successServlet")
		public class SuccessServlet extends HttpServlet {
		    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		        //Get the shared user object in the request domain
		        User user = (User) request.getAttribute("user");
		
		        if(user != null){
		            //Write a sentence to the page
		
		            //Setting Code
		            response.setContentType("text/html;charset=utf-8");
		            //output
		            response.getWriter().write("Log in successfully!"+user.getUsername()+",Welcome");
		        }
		
		
		    }		


		@WebServlet("/failServlet")
		public class FailServlet extends HttpServlet {
		    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		        //Write a sentence to the page
		
		        //Setting Code
		        response.setContentType("text/html;charset=utf-8");
		        //output
		        response.getWriter().write("Logon failure, user name or password error");
		
		    }
		
		    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		        this.doPost(request,response);
		    }
		}



	8. login.html in form Formal action Writing of Path
		* Virtual directory+Servlet Resource Path

	9. BeanUtils Tool class to simplify data encapsulation
		* Used for encapsulation JavaBean Of
		1. JavaBean: Standard Java class
			1. Requirement:
				1. Classes must be public Modification
				2. Constructors that must provide empty parameters
				3. Membership variables must be used private Modification
				4. Providing the public setter and getter Method
			2. Function: encapsulating data


		2. Concept:
			//Membership variables:
			//Attribute: The product of interception of setter and getter methods
				//For example: getUsername () --> Username --> username


		3. Method:
			1. setProperty()
			2. getProperty()
			3. populate(Object obj , Map map):take map The set's key-value pair information is encapsulated into the corresponding JavaBean Object

Topics: Java SQL Database JDBC