day14_Servlet&HTTP&Request Notes

Keywords: Java SQL encoding Database

Today's content:

1. Servlet
 2. HTTP protocol
3. Request


1. Concepts
 2. Steps
 3. Principle of execution
 4. Life cycle
 5. Servlet3.0 Annotation Configuration
 6. Architecture of Servlet	
	GenericServlet -- Abstract Class
	HttpServlet -- Abstract Class

	* GenericServlet: Default empty implementation of other methods in the Servlet interface, using only the service() method as abstraction
		*When defining a Servlet class in the future, you can inherit the GenericServlet and implement the service() method

	* HttpServlet: An encapsulation of the http protocol to simplify operations
		1. Definition class inherits HttpServlet
		2. Override 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 Path, Directory Structure
			3. *.do: Extension matching


* Concepts: Hyper Text Transfer Protocol Hyper Text Transfer Protocol
	* Transport protocol: Defines the format in which data is sent when communicating between client and server
	* Characteristic:
		1. Be based on TCP/IP Advanced Agreements
		2. Default port number:80
		3. Request-based/Response model:One request corresponds to one 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: Multiplex connection

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

		* Request method:
			* HTTP The protocol has 7 request modes, and there are 2 commonly used
				* GET: 
					1. Request parameters are in the request line, in the url After.
					2. Requested url Limited length
					3. Not very safe
				* POST: 
					1. Request parameters in request body
					2. Requested url Unlimited length
					3. Relative Security
	2. Request header: Client browser tells 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 are using
				* This header can be retrieved on the server side to resolve browser compatibility issues

			2. Referer: http://localhost/login.html
				* Tell the server, I(Current Request)Where do you come from?
					* Effect:
						1. Anti-theft chain:
						2. Statistics:
	3. Request blank lines
		//An empty line is the request header used to split the POST request and the request body.
	4. Requestor(text): 
		* encapsulation POST Request parameter of the 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

* Response message data format


1. Principles of request and response objects
	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
		| Implementation
	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
				1. Get Request Method: GET
					* String getMethod()  
				2. (*) Get virtual directory: /day14
					* String getContextPath()
				3. Get Servlet Path: /demo1
					* String getServletPath()
				4. Get get mode request parameter: name=zhangsan
					* String getQueryString()
				5. (*) Get request URI:/day14/demo1
					* String getRequestURI():		/day14/demo1
					* StringBuffer getRequestURL()  :http://localhost/day14/demo1

					* URL: Uniform Resource Locator: http://localhost/day14/demo1 People's Republic of China
					* URI: Uniform Resource Identifier: /day14/demo1 Republic
				6. Get protocol and version: HTTP/1.1
					* String getProtocol()

				7. Get the IP address of the client:
					* String getRemoteAddr()
		2. Get request header data
				* (*) String getHeader(String name): Get the value of the request header by its name
				* Enumeration <String> getHeaderNames(): Get all request header names
		3. Get the requester data:
			*Request body: Only POST request mode can have a request body, which encapsulates the request parameters of a POST request
				1. Get 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 operate on all types of data
						*Explain after uploading knowledge points

				2. Retrieve data from streaming objects
	2. Other functions:
		1. The common 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 that gets the parameter value from the parameter name
			3. Enumeration <String> getParameterNames(): Get parameter names for all requests
			4. Map<String, String[]> getParameterMap(): Get a map collection of all parameters

			*Chinese scrambling problem:
				* get mode: tomcat 8 has solved the get mode scrambling problem
				* post mode: scrambling
					*Resolution: Set request's encoding request.setCharacterEncoding("utf-8") before getting parameters;
		2. Request Forwarding: A resource jump within the server
			1. Steps:
				1. Get the request forwarder object from the request object: RequestDispatcher getRequestDispatcher(String path)
				2. Use the RequestDispatcher object to forward: forward(ServletRequest request, ServletResponse response) 

			2. Features:
				1. Browser address bar path does not change
				2. Can only be forwarded to current server internal resources.
				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 single request and is typically used to share data among multiple resources for request forwarding
				1. void setAttribute(String name,Object obj): Store data
				2. Object getAttitude(String name): Get value by key
				3. void removeAttribute(String name): Remove key-value pairs by key

		4. Get the ServletContext:
			* ServletContext getServletContext()

Case: User Login

* User Logon Case Requirements:
	1.To write login.html Logon 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.Login successfully jumped to SuccessServlet Show: Sign in successfully!User name,Welcome
	5.Logon Failure Jump to FailServlet Show: Logon failure, incorrect username or password

* Analysis

* Development steps
	1. Create project, import html Page, Profile, jar package
	2. Create a database environment
		USE day14;
			username VARCHAR(32) UNIQUE NOT NULL,

	3. create package cn.itcast.domain,Create Class 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) {
 = 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;
		    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 javax.sql.DataSource;
		import javax.xml.crypto.Data;
		import java.sql.Connection;
		import java.sql.SQLException;
		import java.util.Properties;
		 * JDBC Tool class uses Durid connection pool
		public class JDBCUtils {
		    private static DataSource ds ;
		    static {
		        try {
		            //1. Load Profile
		            Properties pro = new Properties();
		            //Load the configuration file using ClassLoader to get the byte input stream
		            InputStream is = JDBCUtils.class.getClassLoader().getResourceAsStream("");
		            //2. Initialize connection pool objects
		            ds = DruidDataSourceFactory.createDataSource(pro);
		        } catch (IOException e) {
		        } catch (Exception e) {
		     * Get Connection Pool Object
		    public static DataSource getDataSource(){
		        return ds;
		     * Get Connection Object
		    public static Connection getConnection() throws SQLException {
		        return  ds.getConnection();
	5. create package cn.itcast.dao,Create Class 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 the database
		public class UserDao {
		    //Declare JDBCTemplate object sharing
		    private JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());
		     * Login Method
		     * @param loginUser User name and password only
		     * @return user Contains all user data, not queried, returns null
		    public User login(User loginUser){
		        try {
		            //1. Write 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) {
		            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;
		public class LoginServlet extends HttpServlet {
		    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		        //1. Set up encoding
		        //2. Get Request Parameters
		        String username = req.getParameter("username");
		        String password = req.getParameter("password");
		        //3. Encapsulate user objects
		        User loginUser = new User();
		        //4. Call UserDao's login method
		        UserDao dao = new UserDao();
		        User user = dao.login(loginUser);
		        //5. Judging user
		        if(user == null){
		            //Logon Failure
		            //Login Successful
		            //Store data
		    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

	7. To write FailServlet and SuccessServlet class
		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
		            //Set Encoding
		            response.getWriter().write("Login successful!"+user.getUsername()+",Welcome");

		public class FailServlet extends HttpServlet {
		    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		        //Write a sentence to the page
		        //Set Encoding
		        response.getWriter().write("Logon failure, incorrect username or password");
		    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

	8. login.html in form Form's action Writing Path
		* Virtual Directory+Servlet Resource Path

	9. BeanUtils Tool class to simplify data encapsulation
		* For encapsulation JavaBean Of
		1. JavaBean: Standard Java class
			1. Requirement:
				1. Class must be public Modification
				2. Constructors that must provide empty parameters
				3. Member variables must be used private Modification
				4. Provide Public setter and getter Method
			2. Function: Encapsulate data

		2. Concepts:
			//Member variables:
			//Attribute: The product intercepted by setter and getter methods
				//For example: getUsername () --> Username --> username

		3. Method:
			1. setProperty()
			2. getProperty()
			3. populate(Object obj , Map map):take map The key-value pair information of the collection, encapsulated in the corresponding JavaBean In object
Twenty-nine original articles were published. Approved 0. Visited 273
Private letter follow

Posted by bala_god on Thu, 05 Mar 2020 19:03:41 -0800