在WEB开发中,服务器可以为每个用户浏览器创建一个会话对象(session对象),注意:一个浏览器独占一个session对象(默认情况下)。因此,在需要保存用户数据时,服务器程序可以把用户数据写到用户浏览器独占的session中,当用户使用浏览器访问其它程序时,其它程序可以从用户的session中取出该用户的数据为用户服务。
Session用于保存每个用户的专用信息,每个客户端用户访问时,服务器都为每个用户分配一个唯一的会话ID(Session ID) . 她的生存期是用户持续请求时间再加上一段时间(一般是20分钟左右)。
因为在登录的时候,前端浏览器会传回Session对象,所以只要通过invalidate():在销毁session对象同时销毁Session对象中存入的用户信息,下一次客户如果操作,后台获取到的session对象没有携带客户的登录信息,则客户无法登录,注销成功
再自己项目的src目录下分别创建controller、dao、domain、service、utils、validate文件,分别用来实现不同的工作
在WEB-INF文件下创建一个pages文件,里面实现前台效果
在web目录下创建以下jsp文件,实现前台效果
因为之前作者发布过注册与登录的实现这里就不再过多教程,请各位读者朋友跳转这篇文章进行查阅
Javaweb实现简易注册与登录功能(与数据库连接)_এ揽风挽你ꦿ໊ོ༊130的博客-CSDN博客
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
Title
主页: <%=session.getAttribute("username")%>登录成功!
<%
if (session.getAttribute("username")!=null){
%>
注销
<%
}else {
%>
登录
注册
<%
}
%>
显示用户信息
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
$Title$
<%request.getRequestDispatcher("/WEB-INF/pages/index.jsp").forward(request,response);%>
<%@ page import="java.util.HashMap" %><%--
Created by IntelliJ IDEA.
User: jinyj
Date: 2023/9/27
Time: 10:39
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
Title
<%
HashMap error = ((HashMap)request. getAttribute("error"));
String fail = (String) request.getParameter("fail");
String username = "";
String password = "";
Cookie[] cookies = request.getCookies();
if (cookies!=null && cookies.length>0){
for (Cookie cookie : cookies) {
String name = cookie.getName();
if ("username".equals(name)){
username = cookie.getValue();
}
if ("password".equals(name)){
password = cookie.getValue();
}
}
}
%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
Title
请先登录再查询,3秒后将跳转至登录界面,如果没有跳转请点击登录
<%
response.setHeader("refresh","3;url=login2.jsp");
%>
<%@ page import="java.util.HashMap" %>
<%@ page import="java.util.Map" %>
<%--
Created by IntelliJ IDEA.
User: jinyj
Date: 2023/9/21
Time: 11:47
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
Title
<%--
String registerfail = request.getParameter("registerfail");
--%>
<%
HashMap error = ((HashMap)request. getAttribute("error"));
String registerfail = request.getParameter("registerfail");
%>
<%=registerfail==null?"":registerfail%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
Title
注销成功,3秒后将跳转至登录界面,如果没有跳转请点击登录
<%
response.setHeader("refresh","3;url=login2.jsp");
%>
<%@ page import="java.util.List" %>
<%@ page import="com.xinhua.domain.User" %><%--
Created by IntelliJ IDEA.
User: jinyj
Date: 2023/10/7
Time: 11:50
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
Title
用户信息:
<%=request.getAttribute("infor")==null?"":request.getAttribute("infor")%>
ID
姓名
密码
年龄
爱好
备注
性别
操作
<%
List users = (List) request.getAttribute("users");
for (User user : users) {
%>
<%=user.getId()%>
<%=user.getUsername()%>
<%=user.getPassword()%>
<%=user.getAge()%>
<%=user.getHobbies()%>
<%=user.getRemark()%>
<%=user.getGender()%>
修改 删除
<%
}
%>
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("/ServletDome1")
public class ServletDome1 extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//判断是否登录
String username = (String)req.getSession().getAttribute("username");
if (username!=null){
req.getRequestDispatcher("/WEB-INF/pages/index.jsp").forward(req,resp);
}else {
resp.sendRedirect("/web002/login2.jsp");
}
}
}
import com.xinhua.domain.User;
import com.xinhua.service.UserService;
import com.xinhua.utils.ArrayToString;
import com.xinhua.validate.ValidateDome;
import org.apache.commons.beanutils.BeanUtils;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@WebServlet("/UserController")
public class UserController extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String userAction = req.getParameter("userAction");
String logout = req.getParameter("logout");
//处理中文乱码
req.setCharacterEncoding("utf-8");
resp.setContentType("text/html;charset=utf-8");
/**
* 注销
*/
if ("loginout".equals(userAction)){
HttpSession session = req.getSession();
session.removeAttribute("username");
req.getRequestDispatcher("/WEB-INF/pages/loginoutsuccess.jsp").forward(req,resp);
}
/**
* 查询用户信息
*/
if ("showAllUser".equals(userAction)){
String username = (String)req.getSession().getAttribute("username");
if (username!=null){
List users = new UserService().showAllUser();
if (users.isEmpty()){
req.setAttribute("infor","未查询到用户相关信息");
req.getRequestDispatcher("/WEB-INF/pages/showalluser.jsp").forward(req,resp);
}else {
req.setAttribute("users",users);
req.getRequestDispatcher("/WEB-INF/pages/showalluser.jsp").forward(req,resp);
}
}else {
resp.sendRedirect("/web002/loinfail.jsp");
}
}
/**
* 登录
*/
if ("login".equals(userAction)){
User user = new User();
try {
BeanUtils.populate(user,req.getParameterMap());
Map error = ValidateDome.validateUser(user);
if (error.isEmpty()){
UserService userService = new UserService();
boolean flag = userService.login(user.getUsername(),user.getPassword());
if (flag){
//判断是否需要记录用户名和密码
String[] autoLogins = req.getParameterValues("autoLogin");
if (autoLogins!=null && autoLogins.length>0){
//登录成功后记录cookie
Cookie usercookie = new Cookie("username", user.getUsername());
Cookie psdcookie = new Cookie("password", user.getPassword());
usercookie.setMaxAge(60);
psdcookie.setMaxAge(60);
usercookie.setPath("FirstWeb");
psdcookie.setPath("FirstWeb");
resp.addCookie(usercookie);
resp.addCookie(psdcookie);
//设置一个登录成功标注
//这个标志设置在session中比较合适
req.getSession().setAttribute("username",user.getUsername());
//resp.sendRedirect("index01.jsp?username="+ URLEncoder. encode(user.getUsername(),"utf-8"));
req.getRequestDispatcher("/WEB-INF/pages/index.jsp").forward(req,resp);
}else {
req.getSession().setAttribute("username",user.getUsername());
req.getRequestDispatcher("/WEB-INF/pages/index.jsp").forward(req,resp);
}
}else {
req.setAttribute("fail","登录失败");
req.getRequestDispatcher("login2.jsp").forward(req,resp);
}
}else {
req. setAttribute( "error", error);
req.getRequestDispatcher( "login2.jsp").forward(req,resp);
}
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
/**
* 注册
*/
if ("register".equals(userAction)){
User user = new User();
try {
BeanUtils.populate(user,req.getParameterMap());
user.setHobbies(ArrayToString.arrayToString(req.getParameterValues("hobbies")));
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
Map error = new HashMap<>();
if (error.isEmpty()){
//调用service
UserService userService = new UserService();
int state = userService.register(user);
if (state==0){
resp.sendRedirect("registerfail.jsp");
}
if (state==1){
resp.sendRedirect("refresh.jsp");
}
if (state==2){
resp.sendRedirect("register.jsp?registerfail="+ URLEncoder. encode( "该用户已经存在!", "utf-8"));
}
}else {
req. setAttribute( "error", error);
req.getRequestDispatcher( "/register.jsp").forward(req, resp);
}
}
}
}
最后谢谢大家借鉴阅读