Today’s content:

1. Servlet 2. HTTP 3Copy the code

The Servlet:

Concept 2. Step 3. Perform principle 4. 5. Life cycle Servlet3.0 annotation configuration 6. The architecture of the Servlet Servlet interface - | GenericServlet - abstract classes | HttpServlet - Abstract classes * GenericServlet: {GenericServlet}} {HttpServlet {GenericServlet}} {GenericServlet {HttpServlet}} {GenericServlet {GenericServlet}} An encapsulation of THE HTTP protocol, simplifying operations 1. 2. Duplicate doGet/doPost methods 7. Servlet configuration 1. A Servlet can define multiple access paths: @webservlet ({"/d4","/dd4","/ddd4"}) 2. Path definition rules: 1. / XXX: path matching 2. / XXX/XXX: multi-layer path with directory structure 3. *Copy the code

HTTP:

Hyper Text Transfer Protocol Hyper Text Transfer Protocol Hyper Text Transfer Protocol Hyper Text Transfer Protocol Hyper Text Transfer Protocol Hyper Text Transfer Protocol Hyper Text Transfer Protocol TCP/ IP-based advanced protocol 2. Default port number :80 3. Request/response model: One request corresponds to one response 4. Stateless: Each request is independent of each other and data cannot be exchanged * Historical version: * 1.0: Each request response establishes a new connection * 1.1: Reuse connection * Request message data format 1. Request line Request Mode Request URL Request Protocol/version GET/Login. HTML HTTP/1.1 * Request mode: * There are seven HTTP request modes, two of which are commonly used * GET: 1. The request parameters are in the request line, after the URL. 2. Requested URL with limited length 3. Not secure * POST: 1. Request parameters in the request body 2. The url length of the request is unlimited 3. Request header: The client browser tells the server something about the request header name: User-agent: the browser tells the server to access the version information of the browser you are using. This header information can be obtained on the server side to solve browser compatibility problems. http://localhost/login.html * tell the server, I () the request come from? * Function: 1. Anti-theft chain: 2. Statistical work: 3. Request empty line empty line, is used to split the POST request header, and the request body. 4. Request body (body) : * Request parameters that encapsulate 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; The rv: 60.0) Gecko / 20100101 Firefox 60.0 / Accept: text/HTML, application/XHTML + XML, application/XML. Q = 0.9 * / *; Q = 0.8 Accept - Language: useful - CN, useful; Q = 0.8, useful - TW; Q = 0.7, useful - 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 formatCopy the code

Request:

1. Principles of Request and Response objects 1. Request and Response objects are created by the server. The request object gets the request message, and the response object sets the response message. The Request object inherits the architecture: ServletRequest - interface | | inherit it - interface implementation org. Apache. Catalina. The RequestFacade class (tomcat). 3. Request function: 1. * GET /day14/demo1? Name =zhangsan HTTP/1.1 * 2. (*) To obtain the virtual directory: /day14 * String getContextPath() 3. /demo1 * String getServletPath() Name = Zhangsan * String getQueryString() 5. (*) Get request URI: /day14/demo1 * String getRequestURI(): Day14 / not * StringBuffer getRequestURL () : http://localhost/day14/demo1 * URL: uniform resource locator (URL) : http://localhost/day14/demo1 * URI of the People's Republic of China: uniform resource identifier: 6 / day14 / not republic. HTTP/1.1 * String getProtocol() * String getRemoteAddr() 2. GetHeader (String name): Obtains the value of the request header from the name of the request header * Enumeration<String> getHeaderNames(): Obtains all the request header names 3. Request body: Only POST request type, only have request body, in the request body encapsulates the REQUEST parameters of POST request * Step: 1. ServletInputStream getInputStream() : ServletInputStream getInputStream() : Get bytes input stream, can manipulate all types of data * 2. Other functions: 1. General way to obtain request parameters: String getParameter(String name): Username =zs&password=123 2. String[] GetParameterValues (String name): Array to obtain parameter values according to parameter names Hobby = xx&Hobby =game 3. Enumeration<String> 4. Map<String,String[]> getParameterMap() Tomcat 8 has get garbled problem solved * post: may be garbled * : before access parameters, set the request code request. SetCharacterEncoding (" utf-8 "); 2. Request forwarding: a resource forwarding mode within a server 1. Obtain the request forwarder object from the Request object: RequestDispatcher getRequestDispatcher(String path) 2. Forward (ServletRequest Request, ServletResponse Response) 2. Features: 1. The browser address bar path does not change. 2. 3. Forwarding is a request 3. Sharing data: * Domain object: a scoped object within which data can be shared * Request domain: represents the scope of a request and is generally used to share data among multiple resources that request forwarding * Methods: Void setAttribute(String name,Object obj): Stores data 2. Object getAttitude(String name): obtains values by keys 3 RemoveAttribute (String name): Remove key-value pairs by key 4. ServletContext getServletContext()Copy the code

Example: User login

* 用户登录案例需求:
	1.编写login.html登录页面
		username & password 两个输入框
	2.使用Druid数据库连接池技术,操作mysql,day14数据库中user表
	3.使用JdbcTemplate技术封装JDBC
	4.登录成功跳转到SuccessServlet展示:登录成功!用户名,欢迎您
	5.登录失败跳转到FailServlet展示:登录失败,用户名或密码错误


* 分析

* 开发步骤
	1. 创建项目,导入html页面,配置文件,jar包
	2. 创建数据库环境
		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. 创建包cn.itcast.domain,创建类User
		package cn.itcast.domain;
		/**
		 * 用户的实体类
		 */
		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. 创建包cn.itcast.util,编写工具类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工具类 使用Durid连接池
		 */
		public class JDBCUtils {
		
		    private static DataSource ds ;
		
		    static {
		
		        try {
		            //1.加载配置文件
		            Properties pro = new Properties();
		            //使用ClassLoader加载配置文件,获取字节输入流
		            InputStream is = JDBCUtils.class.getClassLoader().getResourceAsStream("druid.properties");
		            pro.load(is);
		
		            //2.初始化连接池对象
		            ds = DruidDataSourceFactory.createDataSource(pro);
		
		        } catch (IOException e) {
		            e.printStackTrace();
		        } catch (Exception e) {
		            e.printStackTrace();
		        }
		    }
		
		    /**
		     * 获取连接池对象
		     */
		    public static DataSource getDataSource(){
		        return ds;
		    }
		
		
		    /**
		     * 获取连接Connection对象
		     */
		    public static Connection getConnection() throws SQLException {
		        return  ds.getConnection();
		    }
		}
	5. 创建包cn.itcast.dao,创建类UserDao,提供login方法
		
		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;
		
		/**
		 * 操作数据库中User表的类
		 */
		public class UserDao {
		
		    //声明JDBCTemplate对象共用
		    private JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());
		
		    /**
		     * 登录方法
		     * @param loginUser 只有用户名和密码
		     * @return user包含用户全部数据,没有查询到,返回null
		     */
		    public User login(User loginUser){
		        try {
		            //1.编写sql
		            String sql = "select * from user where username = ? and password = ?";
		            //2.调用query方法
		            User user = template.queryForObject(sql,
		                    new BeanPropertyRowMapper<User>(User.class),
		                    loginUser.getUsername(), loginUser.getPassword());
		
		
		            return user;
		        } catch (DataAccessException e) {
		            e.printStackTrace();//记录日志
		            return null;
		        }
		    }
		}
	
	6. 编写cn.itcast.web.servlet.LoginServlet类
		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);
		        }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. 编写FailServlet和SuccessServlet类
		@WebServlet("/successServlet")
		public class SuccessServlet extends HttpServlet {
		    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		        //获取request域中共享的user对象
		        User user = (User) request.getAttribute("user");
		
		        if(user != null){
		            //给页面写一句话
		
		            //设置编码
		            response.setContentType("text/html;charset=utf-8");
		            //输出
		            response.getWriter().write("登录成功!"+user.getUsername()+",欢迎您");
		        }
		
		
		    }		


		@WebServlet("/failServlet")
		public class FailServlet extends HttpServlet {
		    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		        //给页面写一句话
		
		        //设置编码
		        response.setContentType("text/html;charset=utf-8");
		        //输出
		        response.getWriter().write("登录失败,用户名或密码错误");
		
		    }
		
		    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		        this.doPost(request,response);
		    }
		}



	8. login.html中form表单的action路径的写法
		* 虚拟目录+Servlet的资源路径

	9. BeanUtils工具类,简化数据封装
		* 用于封装JavaBean的
		1. JavaBean:标准的Java类
			1. 要求:
				1. 类必须被public修饰
				2. 必须提供空参的构造器
				3. 成员变量必须使用private修饰
				4. 提供公共setter和getter方法
			2. 功能:封装数据


		2. 概念:
			成员变量:
			属性:setter和getter方法截取后的产物
				例如:getUsername() --> Username--> username


		3. 方法:
			1. setProperty()
			2. getProperty()
			3. populate(Object obj , Map map):将map集合的键值对信息,封装到对应的JavaBean对象中
Copy the code