Test Development Series --mvc, jsp, jstl, el and session tracking technology

learning target

  1. MVC pattern
  2. jsp
  3. jstl and el expressions
  4. Session tracking technology

mvc mode

This mode is used for decoupling applications, layered development

  • Model: General data for processing, including reading and setting data, generally it refers to the database operations.
  • View: generally used to display data, that is, to put data, such as to show by HTML.
  • Controller: Because a module which may be provided by a plurality of view - model, the controller serves as a function of connecting model and view.

3-tier architecture software development

What is jsp

  • The full name java server page, the main servlet output to make up for the shortcomings of the page too much trouble.
    servlet pay attention to the process control and transaction processing
    jsp pay attention to the page display
  • JSP and Java code embedded into content-specific changes in static pages, to achieve a static page as a template to dynamically generate part of its contents

JSP run basic process

Synchronous dynamic resource request process

JSP Standard Tag Library (JSTL)

  • Standard.jar needs and jstl.jar (rookie)
  • The core tag library is the most commonly used JSTL tags.
  • 引用<%@ taglib prefix=“c” uri=“http://java.sun.com/jsp/jstl/core” %>
  • <C: forEach> tag on an iterative basis, accept a variety of types of collection
  • <C: if> with us if used in the same general procedure

JSP EL implicit objects

Supports JSP EL implicit objects listed in the following table:

Hidden objects description
pageScope Scope page
requestScope request scope
sessionScope session scope
applicationScope application scope

Session tracking technology session

  1. session is a server-side session cache technology.
  2. session created by the web server container, and stored on the server side.
  3. save session data: in the form of key-value pairs.
  4. Expired session: 30 minutes by default.

What is a cookie

No more than 4KB small text files that some Web sites to identify the user's identity, a Session tracking and data stored on the user's local terminal (usually encrypted).

  1. A cookie is a client-side caching technology
  2. cookie data generated by the server, sent to the browser save
  3. cookie data format: key-value pairs
  4. cookie expiration data mechanism: Cookie memory after the browser is closed disappear. Cookie hard disk in the hard disk, there is an expiration time, unless the user manually clean up or to the expiration time, the hard disk will not be deleted Cookie

Exercise: Log + js cookie operations

Screenshot operating results

The initial screen:
The initial interface
Enter the incorrect username and password:
Enter the incorrect username and password
returns the error:
Returns an error
Enter the correct user name and password:
Enter the correct user name and password
return to the ok:
Ok return
Cookie has been saved:
Cookie Saved
After returning user name is still cached:
After returning the user name is still cached

Project Screenshot

Project Screenshot

User.java

package com.one.pojo;

import lombok.Data;

@Data
public class User {
  private int userId;
  private String userName;
  private String userPwd;
  public User(int userId, String userName, String userPwd){
    super();
    this.userId = userId;
    this.setUserName(userName);
    this.setUserPwd(userPwd);
  }
  public User(String userName, String userPwd){
    super();
    this.setUserName(userName);
    this.setUserPwd(userPwd);
  }
  public String getUserName() {
    return userName;
  }
  public void setUserName(String userName) {
    this.userName = userName;
  }
  public String getUserPwd() {
    return userPwd;
  }
  public void setUserPwd(String userPwd) {
    this.userPwd = userPwd;
  }
}

UserServlet.java Code

package com.one.servlet;

import com.one.pojo.User;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * Servlet implementation class UserServlet
 */
@WebServlet("/userServlet")
public class UserServlet extends HttpServlet {
  private static final long serialVersionUID = 1L;
  List<User> list=null;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public UserServlet() {
      list = new ArrayList<>();
    list.add(new User(1,"zs","666"));
    list.add(new User(2,"lisi","888"));
    }

  /**
   * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
   */
  protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    String action = request.getParameter("action");
    if("login".equals(action)){
      login(request, response);
    }else if("findAll".equals(action)){
      findAll(request, response);
    }
  }

  private void findAll(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    //将list放入request值域中
    request.setAttribute("list", list);
    request.getRequestDispatcher("index.jsp").forward(request, response);
  }
  
  private void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // 接受请求并响应
    // 1.获取请求参数并封装为对象
    String username = request.getParameter("username");
    String userpwd = request.getParameter("userpwd");
    // 2.数据验证 非空 正则表达式
    // 3.登录业务处理,得到登陆业务结果
    boolean b = false;
    for(User user : list){
      if(user.getUserName().equals(username)&&user.getUserPwd().equals(userpwd)){
        b = true;     
      }
    }
    // 4.根据结果进行跳转
    if(b){
      //服务器内部转发,同一请求,地址栏不会变化,登陆成功后,将用户信息放入session值域
      request.getSession().setAttribute("user", new User(username, userpwd));
      //登录成功,记住密码,存放到cookie
      Cookie c = new Cookie("username",username);
      c.setMaxAge(1*24*60*60);//存放1天,以秒为单位
      response.addCookie(c);
      //response.getWriter().append("{data:'ok',status:1}");
      /**
      PrintWriter out = response.getWriter();
      String str = "{\"data\":\"ok\",\"status\":\"1\"}";
      out.println(str);
      out.flush();
      **/
      PrintWriter pw = response.getWriter();
      String jsonStr = "{status:1, message:\"ok\"}";
      pw.print(jsonStr);
      
      //从一个控制成跳到另一个控制层方法
      //服务器内部转发,同一请求,地址栏不会变化
      //request.getRequestDispatcher("userServlet?action=findAll").forward(request, response);
    }else{
      //重定向,二次请求,地址栏发生变化
      //response.getWriter().append("{data:'error',status:0}");
      PrintWriter out = response.getWriter();
      String str = "{\"data\":\"error\",\"status\":\"0\"}";
      out.println(str);
      out.flush();      
      //response.sendRedirect("login.jsp?msg=error");
    }
  }

  /**
   * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
   */
  protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    doGet(request, response);
  }
}

index.jsp Code

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
  <!-- 欢迎你,<%=request.getParameter("username") %> -->
  欢迎你,${sessionScope.user.userName}----${param.username}
  循环${requestScope.list}集合,取出每一个user 作业jsp ---jstl+el
  <c:forEach items="${requestScope.list}" var="user">
    ${user.userName}---${user.userPwd}
  </c:forEach>
</body>
</html>

login.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
  ${param.msg}
  <form action="userServlet" method="get">
    <input name="username" value = "${cookie.username.value}"/><br/>
    <input name="action" value="login" type="hidden"/><br/>
    <input name="userpwd" type="password" value = "${cookie.userpwd.value}"/><br/>
    <input type="submit" value="登陆"/>
  </form>
</body>
</html>
Published 14 original articles · won praise 1 · views 854

Guess you like

Origin blog.csdn.net/anniewhite/article/details/104078225