这个是jsp的文件------------------------------------------------------------------------------------------------------------
<%@ page language="java" import="java.net.URLDecoder" pageEncoding="utf-8"%>
<%
String username="";
String password="";
Cookie cookies[]=request.getCookies();
if(cookies!=null){
for(int i=0;i<=cookies.length;i++){
if(cookies[i].getName().equals("Name")){
username=URLDecoder.decode(cookies[i].getValue(),"utf-8");
};
if(cookies[i].getName().equals("Password")){
password=cookies[i].getValue();
};
};
};
%>
<html>
<head><title>登陆页面</title></head>
<body>
<form action="LoginServlet" method="post">
用户名:<input type="text" name="username" value="<%out.print(username); %>">
密码:<input type="password" name="password" value="<%out.print(password); %>">
Cookies:
<select name="cookietime">
<option value="0">不保存</option>
<option value="1">一整天</option>
<option value="30">一整月</option>
<option value="365">一整年</option>
</select>
<input type="submit" name="login" value="登陆">
<input type="reset" value="重置">
</form>
</body>
</html>
下面这个是java的文件------------------------------------------------------------------------------------------------------
import java.io.*;
import java.net.URLEncoder;
import java.util.Calendar;
import java.util.Date;
import javax.servlet.*;
import javax.servlet.http.*;
public class LoginServlet extends HttpServlet {
public LoginServlet() {
super();
}
public void destroy() {
super.destroy();
}
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
String cookietime=req.getParameter("cookietime");
int cookietimes=Integer.parseInt(cookietime.trim());
Cookie c=new Cookie("Name",URLEncoder.encode(req.getParameter("username"),"utf-8"));
c.setMaxAge(cookietimes*60*60*24);
c.setPath("/");
res.addCookie(c);
Cookie a=new Cookie("Password",req.getParameter("password"));
a.setMaxAge(cookietimes*68*60*24);
a.setPath("/");
res.addCookie(a);
Calendar calendar=null;
String message=null;
calendar=Calendar.getInstance();
Date trialTime=new Date();
calendar.setTime(trialTime);
int hour=calendar.get(Calendar.HOUR_OF_DAY);
if(hour<12){
message="Good morning!";
}
else{
message="Good afternoon!";
}
if(req.getParameter("username").equals("张三")&&req.getParameter("password").equals("1234")){
req.setAttribute("message", message);
req.getRequestDispatcher("/MyJsp.jsp").forward(req, res);
}
else
{
res.sendRedirect("http://localhost:8080/index1/index.jsp?message=sorry please register");
}
}
public void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
this.doGet(req, res);
}
public void init() throws ServletException {
}
}
逆光之羽
相关分类