Servlet & HTTP & request notes


#Today’s content:
    1. Servlet
HTTP protocol
    3. Request

## Servlet:
1. Concept
Step 2.
3. Execution principle
4. Life cycle
5. Servlet 3.0 annotation configuration
6. Servlet architecture
Servlet — Interface
Genericservlet — abstract class
Httpservlet — abstract class

Generic servlet: the default null implementation of other methods in the servlet interface, only the service () method as an abstract
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
Definition class inherits httpservlet
Copy doget / dopost method
7. Servlet related configuration
Urlpartten: servlet access path
A servlet can define multiple access paths: @ webservlet ({“/ D4”, “/ DD4”, “/ ddd4”})
Path definition rules:
1. / XXX: path matching
2. / xxx / XXX: multi layer path, directory structure
*. Do: extension matching

## HTTP:
Concept: Hyper Text Transfer Protocol
Transport protocol: defines the format of data sent when the client and server communicate.
1. Advanced protocol based on TCP / IP
2. Default port number: 80
3. Based on the request / response model: one request corresponds to one response
Stateless: each request is independent of each other and cannot interact with data

Historical version:
* 1.0: new connection will be established for each request response
1.1: multiplexing connection

Request message data format
Request line
Request URL request protocol / version
            GET /login.html    HTTP/1.1

Request method:
HTTP protocol has 7 request modes, and there are 2 common ones
                    * GET:
Request parameters are in the request line, after the URL.
The requested URL length is limited.
3. Not very safe
                    * POST:
Request parameters in the request body
There is no limit to the URL length of the request
Relative security
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 can access the version information of the browser you are using.
The information of the header can be obtained on the server side to solve the compatibility problem of the browser.

                2. Referer:http://localhost/login.html
Tell the server where I (the current request) come from?
1. Anti theft chain:
Statistical work:
Request empty line
An empty line is used to split the request header and the request body of a post request.
Request body (body):
That encapsulates the request parameters of the post 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

## Request:
Principle of request object and response object
The request and response objects are created by the server. Let’s use them
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
HttpServletRequest — Interface
Org.apache.catalina.connector.requestfacade class (Tomcat)

3. Request function:
Get request message data
Get request line data
                * GET /day14/demo1?name=zhangsan HTTP/1.1
Get request method: get
                        * String getMethod()  
Get virtual directory / day14
                        * String getContextPath()
Get servlet path / Demo1
                        * String getServletPath()
Get get method request parameter: name = Zhangsan
                        * String getQueryString()
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
Get protocol and version: http / 1.1
                        * String getProtocol()

Get the IP address of the client:
                        * String getRemoteAddr()
Get request header data
String getheader (string name): get the value of the request header by the name of the request header
                    * EnumerationGetheadernames(): get all request header names
Get request body data:
Request body: only post request mode has a request body, which encapsulates the request parameters of post request.
Get stream object
Get character input stream, only character data can be operated.
Get byte input stream, can operate all types of data
Explain after uploading knowledge points

Take data from the stream object
Other functions:
General way to get the request parameters: the following methods can be used to get the request parameters in both get and post request modes
String getparameter (string name): get the parameter value according to the parameter name (username = ZS & password = 123)
String [] getparametervalues (string name): get the array of parameter values according to the parameter name. Hobby = XX & Hobby = game
                3. EnumerationGetparameternames(): get parameter names of all requests
                4. MapGetparametermap(): get the map collection of all parameters

Chinese code scrambling problem:
Get mode: Tomcat 8 has solved the problem of getting mode scrambling
Post mode: random code
Solution: before obtaining the parameters, set the code request.setcharacterencoding (“UTF-8”) of the request;
Request forwarding: a method of resource jump within the server
Get request forwarder object through request object: requestdispatcher getrequestdispatcher (string path)
Use requestdispatcher object to forward (ServletRequest request, servletresponse response)

Browser address bar path does not change
You can only forward to the internal resources of the current server.
Forward is a request

3. Shared data:
Domain object: an object with scope that can share data within the scope
Request domain: represents the scope of a request, which is generally used to share data among multiple resources for request forwarding.
Void setAttribute (string name, object obj): store data
Object getattribute (string name): get the value through the key
Void removeaattribute (string name): remove key value pair by key

Get ServletContext:
                * ServletContext getServletContext()

##Case: user login
* user login case requirements:
1. Write login.html login page
Two input fields: username & password
2. Use Druid database connection pool technology to operate MySQL and user table in day14 database
3. Using jdbctemplate technology to encapsulate JDBC
4. Log in successfully and jump to the successservlet display: log in successfully! User name, welcome
5. Login failure jump to failservlet display: login failure, user name or password error

* analysis

Development steps
1. Create project, import HTML page, configuration file, jar package
Create database environment

             USE day14;
             CREATE TABLE USER(
                 username VARCHAR(32) UNIQUE NOT NULL,
                 PASSWORD VARCHAR(32) NOT NULL



Create package cn.itcast.domain, create user class

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 and write tool class JDBC utils

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 configuration file
                         Properties pro = new Properties();
                         //Use classloader to load configuration file and get byte input stream
                         InputStream is = JDBCUtils.class.getClassLoader().getResourceAsStream("");
                         //2. Initialize connection pool object
                         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();



Create package cn.itcast.dao, create class userdao, and 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;
              *Class of user table in operation database
             public class UserDao {
                 //Declare JDBC template object sharing
                 private JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());
                  *Login method
                  *@ param loginuser only has user name and password
                  *@ return user contains all the data of the user, but it is not found. Null is returned.
                 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.class),
                                 loginUser.getUsername(), loginUser.getPassword());
                         return user;
                     } catch (DataAccessException e) {
                         E.printstacktrace(); // log
                         return null;



6. 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 code
                     //2. Get request parameters
                     String username = req.getParameter("username");
                     String password = req.getParameter("password");
                     //3. Encapsulate user object
                     User loginUser = new User();
                     //4. Call the login method of userdao
                     UserDao dao = new UserDao();
                     User user = dao.login(loginUser);
                     //5. Judge user
                     if(user == null){
                         //Login failed
                         //Login successful
                         //Store data
                         // forwarding
                 protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {



7. Write failservlet and successservlet classes

             public class SuccessServlet extends HttpServlet {
                 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
                     //Get the user object shared in the request domain
                     User user = (User) request.getAttribute("user");
                     if(user != null){
                         //Write a sentence to the page
                         //Set encoding
                         // output
                         Response. Getwriter(). Write ("login succeeded! "+ 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
                     // output
                     Response. Getwriter(). Write ("login failed, wrong user name or password");
                 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {



Action path of form form in login.html
Resource path of virtual directory + Servlet

9. BeanUtils tool class to simplify data encapsulation
For encapsulating JavaBeans
JavaBean: a standard Java class
Class must be modified by public
Constructor with null parameter must be provided
Member variables must be modified with private
Provide public setter and getter methods
Function: encapsulate data

Member variable:
Property: the result of intercepting setter and getter methods
E.g. getusername() — > username — > username

                1. setProperty()
                2. getProperty()
3. Populate (object obj, map map): encapsulate the key value pair information of the map set into the corresponding JavaBean object

Recommended Today

The way of nonlinear optimization

Mathematical knowledge 1、 Nonlinear functionLinear function is another name of a function of first degree, then nonlinear function means that the function image is not a function of a straight line.Nonlinear functions include exponential function, power function, logarithmic function, polynomial function and so on. 2、 Taylor expansion1. Taylor formula:Taylor’s formula is to add a_ The […]