JSP简单实现登录和注销

原文链接: https://www.mk2048.com/blog/blog.php?id=h0j2jk2kak2j&title=JSP%E7%AE%80%E5%8D%95%E5%AE%9E%E7%8E%B0%E7%99%BB%E5%BD%95%E5%92%8C%E6%B3%A8%E9%94%80

JSP简单实现登录和注销

需求:用户登录成功后跳转到欢迎页面

          用户登录失败跳转到初始的登录界面

          用户点击注销,用户退出登录状态需要重新登录

登录页面的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>登录页面</title>
</head>
<body>
<form action="do_login.jsp" method="post">
用户名:<input type="text" name="username">
密码:<input type="password" name="password">
<br>
<input type="submit" value="确认">
<input type="reset" value="重置">
</form>
</body>
</html>

处理登录的JSP代码:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%
String username=request.getParameter("username");
String password=request.getParameter("password");
if(username.equals("xiongda")&&password.equals("123")){
    session.setAttribute("username", username);
    response.setHeader("Refresh", "2,URL=welcome.jsp");
}else{
    response.setHeader("Refresh", "2,URL=login.jsp");
}
%>

欢迎界面的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>欢迎页面</title>
</head>
<body>
<%if(session.getAttribute("username")!=null){ %>
你好,<%=session.getAttribute("username") %>
<a href="logout.jsp">注销</a>
<br>
<%}else{%>
请先登录:<a href="login.jsp">登录</a>
<br>
<%} %>
<% if(session.isNew()){ %>
欢迎新用户!
<%}else{ %>
欢迎老用户!
<%} %>
</body>
</html>

注销的JSP代码:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    <%session.invalidate();
    response.setHeader("Refresh", "2,URL=welcome.jsp");
    %>

核心思想:

登陆成功后就将用户的信息存入session中,如果用户需要注销的时候就清除session对象


更多专业前端知识,请上 【猿2048】www.mk2048.com

猜你喜欢

转载自blog.csdn.net/QDY5945/article/details/102751537