servlet会话技术-session

session会话

存在服务器端,无大小限制、数据安全

练习:
访问带验证码页面(输入数据后,若有误跳转登录界面,若验证码有误提示验证码错误)

<%--
  Created by IntelliJ IDEA.
  User: carrmee
  Date: 2019/8/15
  Time: 18:01
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>


    login
    
    


    
用户名:
密码:
验证码:
<%=request.getAttribute("cc_error")%>
<%=request.getAttribute("login_error")%>
package com.carrmee.servlet;

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 javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/loginServlet")
public class loginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //设置编码
        request.setCharacterEncoding("utf-8");
        //获取参数
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String checkCode = request.getParameter("checkCode");
        //判断验证码是否正确
        HttpSession session = request.getSession();
        String checkCode_session = (String) session.getAttribute("checkCode_session");
        if (checkCode_session.equalsIgnoreCase(checkCode)){
            //忽略大小写比较
            if ("vhm".equals(username)&&"123".equals(password)){
//                登录成功
                session.setAttribute("user",username);
//                重定向到success。jsp
                response.sendRedirect(request.getContextPath()+"/success.jsp");

            }else {
                request.setAttribute("login_error","用户名密码错误");
                //转发到登录
                request.getRequestDispatcher("/login.jsp").forward(request,response);
            }
        }else {
            //不一致,存储信息到request
            request.setAttribute("cc_error","验证码错误");
            //转发到登录
            request.getRequestDispatcher("/login.jsp").forward(request,response);
        }
    }
}

你可能感兴趣的