欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

session实现登陆/登出效果(初识session基础练习)

程序员文章站 2024-03-20 12:55:28
...

1.在Eclipse下创建项目文件: ActionServlet.java、login.jsp、index.jsp 

2.ActionServlet.java代码:

package web03;

import java.io.IOException;
import java.io.PrintWriter;
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;

@WebServlet("*.do")
public class ActionServlet extends HttpServlet {
	@Override
	protected void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
		
		req.setCharacterEncoding("UTF-8");
		res.setContentType("text/html;charset=utf-8");
		PrintWriter out = res.getWriter();
		
		String uri = req.getRequestURI();
		String action = uri.substring(uri.lastIndexOf("/")+1, uri.lastIndexOf("."));
		HttpSession session = req.getSession();
		System.out.println(session.getId());
		
		if(action.equals("login")){
			String uname = req.getParameter("uname");
			String pwd = req.getParameter("pwd");
			
			if(uname.equals("admin") && pwd.equals("12345")){
				session.setAttribute("uname", uname);
				res.sendRedirect("index.jsp");
			} else {
				req.setAttribute("msg", "用户名或密码错误");
				req.getRequestDispatcher("login.jsp").forward(req, res);
			}
		} else if(action.equals("logout")){
			session.invalidate();
			res.sendRedirect("login.jsp");
		}
		out.close();
	}
}

3.login.jsp代码:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%
	String msg = (String)request.getAttribute("msg");
	if(msg == null){
		msg = "";
	}
%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>登陆页面</title>
<style type="text/css">
div{
	/* border: 1px solid #CCC; */
	margin: 0 auto;
	width: 300px;
}
span{
	margin-right: 10px;
}
h1{
	text-align: center;
	width:220px;
	/* border: 1px solid #000; */
}
</style>
</head>
<body>
	<div>
		<h1>登陆</h1>
		<form action="login.do" method="post">
			<h3><%=msg %></h3>
			<p><span>账号:</span><input name="uname" type="text" /></p>
			<p><span>密码:</span><input name="pwd" type="password" /></p>
			<input type="submit" value="Login" />
		</form>
	</div>
</body>
</html>

4.index.jsp代码:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<% 
	Object uname = session.getAttribute("uname");
	if(uname == null){
		response.sendRedirect("login.jsp");
		return;
	}
%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
	<div style="width: 150px; margin: 0 auto;">
		<h1>首页</h1>欢迎您:<%=uname.toString() %><br><br>
		<a href="logout.do"><button>登出</button></a>
	</div>
</body>
</html>

5.在Eclipse中启动Tomcat,localhost:8080/HAHA直接先访index.jsp页面,自己做测试