效果图如下
从数据库中随意使用一个账号登录
登陆成功来到人中心
返回登录界面
实现代码如下
package com.test.controller;import java.io.IOException;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;import com.test.service.UserService;/** * Servlet implementation class LoginServlet */@WebServlet("/login_do")public class LoginServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub request.setCharacterEncoding("UTF-8"); String username=request.getParameter("username"); String password=request.getParameter("password"); Cookie cookieUsername=new Cookie("username", username); Cookie cookiePassword=new Cookie("password", password); UserService userService=new UserService(); boolean isSuccess=userService.login(username, password); if(isSuccess) { request.setAttribute("msg", "登陆成功"); cookieUsername.setMaxAge(60*60*24*30); cookiePassword.setMaxAge(60*60*24*30); response.addCookie(cookieUsername); response.addCookie(cookiePassword); request.getRequestDispatcher("personCenter.jsp").forward(request, response);; }else { request.setAttribute("msg", "用户名或密码错误"); request.getRequestDispatcher("login.jsp").forward(request, response); } }}
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>??????? <%String username="";String password="";Cookie[] cookies=request.getCookies();if(cookies!=null&&cookies.length>0){ for(int i=0;i登录
${requestScope.msg }