产生随机字符串进行验证,如果产生的和Session存储的相同则可以提交,提交后删除session对应的属性值;否则表单提交不成功
一、产生随机字符串的工具类
package web10.util;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;
public class TokenProcessor {
private static TokenProcessor tokenProcessor;
private TokenProcessor(){
}
public static TokenProcessor getInstance(){
if(tokenProcessor==null){
tokenProcessor=new TokenProcessor();
}
return tokenProcessor;
}
public String getToken(){
String token="";
String temp=System.currentTimeMillis()+"";
try {
MessageDigest digest=MessageDigest.getInstance("MD5");
byte[] tokens=digest.digest(temp.getBytes());
token=Base64.encode(tokens);
System.out.println(token+" +++");
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return token;
}
}
二、login.jsp
<h3>用户登录</h3>
<form action="./login.do?oper=login" method="post">
<table>
<tr>
<td>用户名:</td>
<td><input type="text" name="name" /></td>
</tr>
<tr>
<td>密码:</td>
<td><input type="password" name="pass"></td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="登录"/></td>
</tr>
</table>
<input type="hidden" name="token" value="${token}"/>
</form>
三、LoginServlet.java(./login.do)
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
HttpSession session=request.getSession();
String oper=request.getParameter("oper");
if("pre".equals(oper)){
session.setAttribute("token", TokenProcessor.getInstance().getToken());
request.getRequestDispatcher("./login.jsp").forward(request, response);
}else if("login".equals(oper)){
String rtoken=request.getParameter("token");
String stoken=(String) session.getAttribute("token");
if(stoken==null||"".equals(stoken)){
System.out.println("不能提交表单");
}else{
if(stoken.equals(rtoken)){
String name=request.getParameter("name");
String pass=request.getParameter("pass");
System.out.println(name+"=============="+pass);
session.removeAttribute("token");
}else{
System.out.println("不能提交表单");
}
}
}
}