servlet 登陆注销案例

public class UserDao {
private static Map userMap = new HashMap();
static{
userMap.put("溜得滑", "123");
userMap.put("锅副成", "123");
userMap.put("章靴有", "123");
userMap.put("张乾", "123");
}
public static boolean isUser(String name,String psw){
if(userMap.containsKey(name) && psw.equals(userMap.get(name))){
return true;
}
return false;
}

}

public class IndexServlet extends HttpServlet {


public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
request.setCharacterEncoding("utf-8");
PrintWriter out =response.getWriter();
if(request.getSession(false)== null || request.getSession().getAttribute("user") == null){
response.getWriter().write("欢迎光临!游客!登陆 注册");
}else{
response.getWriter().write("欢迎回来!"+request.getSession().getAttribute("user")+"!注销");
}
}


public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);


}


}



 
   
 
 
 

用户登陆



 

  用户名

  密码

 
 

 

public class LoginServlet extends HttpServlet {


public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
//1.获取请求参数中的用户名密码
String username = request.getParameter("username");
String psw = request.getParameter("password");
//2.校验用户名和密码是否正确
if(UserDao.isUser(username, psw)){
//登录
request.getSession().setAttribute("user", username);
//重定向到主页
response.sendRedirect(request.getContextPath()+"/servlet/IndexServlet");
}else{
response.getWriter().write("用户名密码错误!!3秒后回到主页,请重新登陆!");
response.setHeader("refresh", "3;url="+request.getContextPath()+"/servlet/IndexServlet");
}
}


public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);


}


}

public class LogoutServlet extends HttpServlet {


public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
request.setCharacterEncoding("utf-8");
if(request.getSession(false) != null){
request.getSession().invalidate();
}
response.sendRedirect(request.getContextPath()+"/servlet/IndexServlet");
}


public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);


}


}

你可能感兴趣的:(servlet 登陆注销案例)