今天讲的知识是使用Session完成用户登陆 ,利用Session实现验证码校验,下面是我写的代码:
servlet文件----------------
package com.hbsi.servlet;
import java.io.IOException;
import java.io.PrintWriter;import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.hbsi.dao.UserDao;
import com.hbsi.domain.User;
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");
PrintWriter out = response.getWriter();
String username = request.getParameter("username");
String password = request.getParameter("password");
String checkcode = request.getParameter("checkcode");
String imgcode = (String) request.getSession().getAttribute("imgcode");
System.out.println(imgcode);
if(checkcode!=null && imgcode!=null && checkcode.equals(imgcode)){
UserDao udao = new UserDao();
User user = udao.find(username, password);
if(user!=null){
request.getSession().setAttribute("user",user);
response.sendRedirect("/BookHistory/servlet/IndexServletShopping");
}
out.print("用户名密码错误");
}else{
out.print("验证码错误");
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
html文件--------------------------
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Login.html</title>
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="this is my page">
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<script type="text/javascript">
function change(img){
img.src = img.src + "?" + new Date().getTime();
}
</script>
</head>
<body>
<form action="/BookHistory/servlet/LoginServlet" method="post">
用户名:<input type="text" name="username"/><br/>
密码:<input type="password" name="password"/><br/>
验证码:<input type="text" name="checkcode"/><img src="/BookHistory/servlet/Response3" Xοnclick="change(this)"/><br/>
<input type="submit" value="登陆"/>
</form>
</body>
</html>