LoginService.java
package edu.cn;
public class LoginService {
public static boolean login(String username, String password) {
if ("admin".equals(username) && "123456".equals(password)) {
return true;
} else {
return false;
}
}
}
Login.jsp登录页面:
<body>
<%@ page import= "edu.cn.LoginService,java.sql.*"%>
<%
//1.获取客户端的Cookie
Cookie[] cookies =request.getCookies();
String[] cooks = null;
String username = null;
String password = null;
if (cookies!=null&&cookies.length!=0) {
for (Cookie coo : cookies) {
//2.根据cookie的名字寻找cookie,并获取它的值。
if("user".equals(coo.getName())){
username =coo.getValue();
}
if("pass".equals(coo.getName())){
password=coo.getValue();
}
}
}
if (LoginService.login(username, password)) {
session.setAttribute("username", username);
response.sendRedirect("main.jsp");
}else{
//3.设计form表单
response.sendRedirect("MyHtml.html");
}
%>
<br>
</body>
LoginServlet.java中的核心代码
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
PrintWriter out = response.getWriter();
//1.获取form表单传递来的数据
String username=request.getParameter("username");
String password=request.getParameter("password");
String savetime=request.getParameter("time");
//2.如果输入的用户名和密码争取,则将用户名和密码设置为2个cookie,发送给客户端
if(LoginService.login(username, password)){
if(null!=savetime&&savetime.length()>0){
int saveTime=Integer.parseInt(savetime);
int seconds=saveTime*24*60*60;
//3.创建2个cookie,名字分别为user和password,并为它们设置相关内容
Cookie cookie =new Cookie("user",username);
cookie.setMaxAge(seconds);
cookie.setPath("/");
Cookie cookie2=new Cookie("pass",password);
cookie2.setMaxAge(seconds);
cookie2.setPath("/");
//4.添加cookie,发送给客户端
response.addCookie(cookie);
response.addCookie(cookie2);
}
request.getRequestDispatcher("/main.jsp").forward(request,response);
}else{
request.getRequestDispatcher("/index.jsp").forward(request,response);
}
}
}
main.jsp页面
<body>
登录成功,欢迎${username}的到来
</body>
index.jsp页面
<body>
<a href="Login.jsp"> 登陆</a>
</body>