java day38【Servlet 、HTTP协议 、Request】

The first chapter   Servlet

1. Concept
2. Step
3. Perform principle
4. Life Cycle
5. Servlet3.0 annotation configuration
6. Servlet architecture
Servlet - Interface
|
the GenericServlet - abstract class
|
the HttpServlet - abstract class

* GenericServlet: The Servlet interface are other ways to do a default empty implementation, only the service () method as an abstract
* When defining the future Servlet class can inherit GenericServlet, achieve service () method can be

* HttpServlet: A package of the http protocol, to simplify the operation
1. Define class inherits the HttpServlet
2. replication doGet / doPost method

7. The Servlet configuration
1. urlpartten: Servlet access path
1. Servlet can define a plurality of access paths: @WebServlet ({ "/ D4", "/ DD4", "/ DDD4"})
2. Path define rules:
1 . / xxx: matching path
2. / xxx / xxx: multilayer path, directory structure
3. * .do: extension matches

Chapter   HTTP

* The concept: Hyper Text Transfer Protocol Hypertext Transfer Protocol
* Transfer Protocol: defined, the client and server-side communications, sending data format
* Features:
1. advanced protocol based on TCP / IP is
2. The default port number: 80
3 based on a request / response model: a primary response corresponding to the request
4. stateless: requests each independent of each other, the data can not interact

* Version history:
* 1.0: respond to every request will establish a new connection
* 1.1: Multiple Access

* Data format of the request message
1 request line
request url request protocol mode request / release
GET /login.html HTTP / 1.1

* Request mode:
* in the HTTP protocol has requested 7 embodiment, there are two commonly used
* the GET:
1. request parameters in the request line, after the url.
2. The length of the request url limited
3. less secure
* the POST:
1. request parameter in the request body
2. The length of url requests, without limitation
3. relatively safe
2. The request header: the client tells the server to the browser of some information
request header name: request header value
* common request headers:
1. the User-Agent: browser tells the server, I access the browser version you are using information
* you can obtain information on the server side of the head, resolve compatible browser issues

Referer 2.: HTTP: //localhost/login.html
* tells the server, I (the current request) come from?
* Function:
1. anti-theft chain:
2. statistics:
3. Request blank lines
blank lines, that is, for dividing the request header POST request, and the request body.
4. The request body (body):
* Packaging POST Request message parameter is

* 字符串格式:
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 format data

Chapter III   Request

Principle 1. request and response objects of
1. request and response objects are created by the server. We use them
2. request is subject to the acquisition request message, response message in response to the object is set to

2. request object inherits architecture:
ServletRequest - Interface
| inherit
HttpServletRequest - Interface
| achieve
org.apache.catalina.connector.RequestFacade class (tomcat)

3. request features:
1. Data acquisition request message
1 request line data acquisition
* the GET / Day14 / name = zhangsan the demo1 the HTTP / 1.1?
* Method:
1. Get request method: the GET
* getMethod String ()
2. (*) Gets the virtual directory: / Day14
* getContextPath String ()
3. Get Servlet path: / the demo1
* getServletPath String ()
4. get acquisition mode request parameters: name = zhangsan
* String the getQueryString ()
5. The (*) acquisition 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 the protocol and version: HTTP / 1.1
* String getProtocol ()

7. acquired client IP address:
* getRemoteAddr String ()

2. Data acquisition request header
* Method:
* (*) getHeader String (String name): Gets the value of the request header request header by name
* Enumeration <String> getHeaderNames (): Get the name of all request header

3. the volume data acquisition request:
* request body: POST request only mode, only the request body, encapsulating the POST request request parameters in the request body
* steps:
1. obtain the stream object
* BufferedReader getReader (): get the character input stream, only character data manipulation
* ServletInputStream getInputStream (): Gets the byte input stream, can operate all types of data
* explain the knowledge points after file upload

2. Take data from another stream object

2. Other functions:
1. Get request parameter general manner: whether still get post requests embodiment can use the following methods to obtain the request parameters
1. String getParameter (String name): Get the name of the parameter according to the parameter value username password = 123 & ZS =
2. String [] getParameterValues (String name) : Gets an array hobby parameter value = xx & hobby = game by parameter name
3. Enumeration <String> getParameterNames () : Get parameter name all requested
4. Map <String, String [] > getParameterMap ( ): get the map collection of all parameters

* Chinese garbage problem:
* GET way: tomcat 8 get garbled way the problem has been solved
* post by: garbled
* Fix: Before acquisition parameters, set the encoding of request.setCharacterEncoding request ( "utf-8");

2. Request Forwarding: A server resources inside jump method
1. Step:
1. acquiring request forwarder object through the request object: RequestDispatcher the getRequestDispatcher (String path)
2. Use RequestDispatcher object to forward: forward (ServletRequest request, ServletResponse response)

2. Features:
1. browser address bar does not change the path
2. only be forwarded to the current server internal resources.
3. The first request is forwarded

3. Shared Data:
* domain objects: a scope of the object data can be shared in the range
* request field: range represents a request, typically a plurality of resource requests forwarded shared data
* Method:
1. void setAttribute (String name, Object obj) : store data
2. Object getAttitude (String name): Gets the value through the key
3. void removeAttribute (String name): removal of the key by key

4. 获取ServletContext:
* ServletContext getServletContext()

Chapter IV   Case: User Login

* User login requirements Case:
1. Log in page write login.html
username & password two input boxes
2. Druid database connection pooling, operation mysql, day14 user database tables
3. JdbcTemplate art package the JDBC
4. hop successful login go SuccessServlet show: a successful login! User name, you are welcome
5. Jump to FailServlet show login failure: Login failed for user name or password is incorrect

* Analysis

* Development steps
1. Create a project, import html pages, configuration files, jar package
2. Create a database environment,
the CREATE DATABASE Day14;
the USE Day14;
the CREATE TABLE the USER (

the above mentioned id INT PRIMARY KEY AUTO_INCREMENT,
username VARCHAR (32) UNIQUE the NOT NULL,
PASSWORD VARCHAR (32) the NOT NULL
);

3. Create package cn.itcast.domain, creating class the User
Package cn.itcast.domain;
/ **
* User entity class
* /
public class {the 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 a package cn.itcast.util, writing tools JDBCUtils
Package Penalty for cn.itcast.util;

com.alibaba.druid.pool.DruidDataSourceFactory Import;

Import the javax.sql.DataSource;
Import javax.xml.crypto.Data;
Import java.io.IOException;
Import a java.io.InputStream;
Import the java.sql.Connection;
Import Java .sql.SQLException;
Import the java.util.Properties;

/ **
* tools use the JDBC connection pool Durid
* /
public class JDBCUtils {

Private static the DataSource DS;

static {

the try {
// load configuration file. 1.
the Properties Pro new new = the Properties ();
// use ClassLoader load profile, obtaining input stream of bytes
the InputStream JDBCUtils.class.getClassLoader IS = () the getResourceAsStream ( "druid.properties");.
pro.load (IS);

// initialize connection pool 2. objects
DruidDataSourceFactory.createDataSource = DS (Pro);

} the catch (IOException E) {
e.printStackTrace ();
} the catch (Exception E) {
e.printStackTrace ();
}
}

/ **
* Gets connection pool object
* /
public static the DataSource getDataSource () {
return DS;
}

/ **
* Get connected Connection object
* /
public static Connection the getConnection () throws SQLException {
return ds.getConnection ();
}
}
5. The package created cn.itcast.dao, creating class UserDao, the login method provides

package cn.itcast. dao;

cn.itcast.domain.User Import;
Import cn.itcast.util.JDBCUtils;
Import org.springframework.dao.DataAccessException;
Import org.springframework.jdbc.core.BeanPropertyRowMapper;
Import org.springframework.jdbc.core.JdbcTemplate;

/ **
* user class operation database table
* /
public class UserDao {

// declare JDBCTemplate object shared
Private the JdbcTemplate the JdbcTemplate new new Template = (JDBCUtils.getDataSource ());

/ **
* Log method
* @param loginUser only the user name and password
* @return user contains the user all the data, there is no query that returns null
* /
public the Login the user (the user loginUser) {
the try {
// 1. write SQL
String SQL = "the SELECT * from the user the WHERE username =? and password =?" ;
// 2 call query method
User user = template.queryForObject(sql,
new BeanPropertyRowMapper<User>(User.class),
loginUser.getUsername(), loginUser.getPassword());

User return;
} the catch (the DataAccessException E) {
e.printStackTrace (); // log
null return;
}
}
}

6. The write cn.itcast.web.servlet.LoginServlet type
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.设置编码
req.setCharacterEncoding("utf-8");
//2.获取请求参数
String username = req.getParameter("username");
String password = req.getParameter("password");
//3.封装user对象
User loginUser = new User();
loginUser.setUsername(username);
loginUser.setPassword(password);

//4.调用UserDao的login方法
UserDao dao = new UserDao();
User user = dao.login(loginUser);

//5.判断user
if(user == null){
//登录失败
req.getRequestDispatcher("/failServlet").forward(req,resp);// store data// successful login
the else {}


req.setAttribute("user",user);
//转发
req.getRequestDispatcher("/successServlet").forward(req,resp);
}

}

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doGet(req,resp);
}
}

7. Preparation FailServlet and SuccessServlet class
@WebServlet ( "/ successServlet")
public class SuccessServlet the extends the HttpServlet {
protected void the doPost (the HttpServletRequest request, the HttpServletResponse Response) throws ServletException, IOException {
// Get request shared domain user object
User user = ( the User) the request.getAttribute ( "User");

! IF (User = null) {
// write word to the page

// set encoding
the response.setContentType ( "text / HTML; charset = UTF-. 8");
// output
. response.getWriter () write ( "login is successful!" + user.getUsername () + " , welcome");
}

 }

@WebServlet ( "/ failServlet")
public class FailServlet the extends the HttpServlet {
protected void the doPost (the HttpServletRequest Request, the HttpServletResponse Response) throws ServletException, IOException {
// Write word in the page

// set the encoding
response.setContentType ( "text / html; charset . 8-UTF = ");
// output
response.getWriter () write (." login failed, user name or password error ");

}

protected void the doGet (the HttpServletRequest Request, the HttpServletResponse Response) throws ServletException, IOException {
this.doPost ( Request, Response);
}
}

8. login.html wording action path in the form of a form
resource path * + Servlet's virtual directory

9. BeanUtils tools to simplify data encapsulation
* for packaging the JavaBean
1. JavaBean: standard Java class
1 claim:
1. The class must be public modified
2 must provide an empty argument constructor
3. The private member variables must be used modified
4. public setter and getter methods
2. function: data encapsulation

2. Concept:
member variables:
Attribute: The product was taken setter and getter methods
, for example: getUsername () -> Username - > username

3. Method:
1. the setProperty ()
2. getProperty ()
3. the populate (Object obj, the Map map): a set of keys for the map information corresponding to the packaged objects JavaBean

Guess you like

Origin www.cnblogs.com/xuweng/p/11264980.html