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

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 = "";
	}
%>




登陆页面



	

登陆

<%=msg %>

账号:

密码:


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;
	}
%>




Insert title here


	

首页

欢迎您:<%=uname.toString() %>


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

你可能感兴趣的:(Servlet/JSP)