javaWeb_session案例一:09-利用session完成用户登陆

session案例一:09-利用session完成用户登陆
session完成用户登陆

login.html

			

LoginServlet      关键:request.getSession().setAttribute("user", user);//登录成功,向session存入一个登录标记  

@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=UTF-8");
		PrintWriter out = response.getWriter();
		String username = request.getParameter("username");
		String pwd = request.getParameter("pwd");
		
		List list = DB.getAll();
		for(User user:list){
			if(user.getUsername().equals(username) && user.getPwd().equals(pwd)){
				request.getSession().setAttribute("user", user);//登录成功,向session存入一个登录标记
				response.sendRedirect("login_ok.jsp");
				return;
			}
		}
		out.write("用户名或密码不正确!");
		
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}

class DB{
	public static List list = new ArrayList();
	static{
		list.add(new User("aaa","123"));
		list.add(new User("bbb","123"));
		list.add(new User("ccc","123"));
	}
	public static List getAll(){
		return list;
	}
	
}
			

User

			public class User {

	private String username;
	private String pwd;
	
	public User() {
		super();
		// TODO Auto-generated constructor stub
	}
	public User(String username, String pwd) {
		super();
		this.username = username;
		this.pwd = pwd;
	}
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getPwd() {
		return pwd;
	}
	public void setPwd(String pwd) {
		this.pwd = pwd;
	}
	
}

			

login_ok.jsp

 
     
欢迎您:${user.username }
重新登录
登出

LoginOut   关键:session.removeAttribute("user");

			@WebServlet("/LoginOut")
public class LoginOut extends HttpServlet {
	private static final long serialVersionUID = 1L;
  
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession(false);
		if(session == null){
			response.sendRedirect("login.html");
			return;
		}
		session.removeAttribute("user");
		response.sendRedirect("login.html");
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}

			

你可能感兴趣的:(javaWeb,servlet)