1----login.jsp-------------------------------------------------------------------------------
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<div align="center">
<label style="color:red"> ${msg}</label>
<form action="login.do?method=login" method="post">
用户名: <input type="text" name="username" id="username" οnblur="send()"/><label id="label"></label><br />
密码: <input type="password" name="password"/><br />
验证码: <input type="text" name="verifyCode" />
<a href="javascript:getVeriCode()">
<img src="verifyCode.do?method=createVerifyCode" id="img"/>
</a>
<br />
<input type="submit" value="登录" />
<input type="button" value="注册" />
</form>
</div>
</body>
<script type="text/javascript">
function getVeriCode(){
var img = document.getElementById("img");
img.src = "login.do?method=createVerifyCode×trap="+new Date().getTime();
}
//创建XMLHttpRequest对象
function createXMLHttpRequest(){
var XMLHttp;
try{
//大多数浏览器,以及IE7和IE更高版本
XMLHttp = new XMLHttpRequest();
}catch(e){
try{
//IE5.5及以下的版本
XMLHttp = new ActiveXObject("Microsoft.XMLHTTP");
}catch(e){
try{
//IE6.0
XMLHttp = new ActiveXObject("Msxml2.XMLHTTP");
}catch(e){
//以上都不是,执行的代码
}
}
}
return XMLHttp;
}
function send(){
var username = document.getElementById("username").value;
var XMLHttp = createXMLHttpRequest();
//1.打开服务器的连接
XMLHttp.open("post","login.do?method=loginAjax&username="+username, true);
XMLHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
//2.发送请求
XMLHttp.send(null);
//3.接收服务器响应
XMLHttp.onreadystatechange = function(){
//4.表示服务器响应结束,200表示服务器成功响应
if(XMLHttp.readyState == 4 && XMLHttp.status == 200){
var label = document.getElementById("label");
label.innerHTML = XMLHttp.responseText;
}
}
}
</script>
</html>
2-----login.servlet------------------------------------------------------------------
package net.yaorange.controller;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.ArrayList;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import net.yaorange.dao.ProductDao;
import net.yaorange.dao.UserDao;
import net.yaorange.dao.impl.ProductDaoImpl;
import net.yaorange.dao.impl.UserDaoImpl;
import net.yaorange.entity.PageModel;
import net.yaorange.entity.Product;
import net.yaorange.entity.UserInfo;
import net.yaorange.utils.PageUtils;
import net.yaorange.utils.VerifyCodeUtils;
public class LoginServlet extends BaseServlet{
@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
String method=req.getParameter("method");
if("login".equals(method)){
login(req,resp);
}else if("loginAjax".equals(method)){
loginAjax(req,resp);
}
}
@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
public String login(HttpServletRequest req, HttpServletResponse res) throws IOException{
String username = req.getParameter("username");
String password = req.getParameter("password");
String verifyCode = req.getParameter("verifyCode");
UserDao userDao = new UserDaoImpl();
UserInfo userInfo = userDao.login(username, password);
if(userInfo != null){ //userInfo不为null时,说明数据库有此条记录
ProductDao productDao = new ProductDaoImpl();
HttpSession session = req.getSession();
String name = userInfo.getUsername();
// req.setAttribute("name_request", name);
session.setAttribute("name_session",name);
// PageModel pageModel = new PageModel();
// pageModel.setPageIndex(1);
// ArrayList<Product> productList = productDao.ShowByPage(pageModel);
// req.setAttribute("productList", productList);
if(verifyCode.equals(req.getSession().getAttribute("code_text"))){
PageUtils.queryByPage(req, res, productDao, new PageModel());
return "productList.jsp";
}else{
req.setAttribute("msg", "验证码错误!");
return "login.jsp";
}
}
else{
req.setAttribute("msg", "用户名或者密码错误!");
return "login.jsp";
}
}
//创建验证码
public String createVerifyCode(HttpServletRequest req, HttpServletResponse res){
System.out.println(">>>>>>>123");
VerifyCodeUtils verifyCode = new VerifyCodeUtils();
//1.获取验证码
BufferedImage image = verifyCode.getImage();
//2.把验证码的文本保存到session中
req.getSession().setAttribute("code_text", verifyCode.getText());
//3.把验证码写到流中
try {
verifyCode.output(image, res.getOutputStream());
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
//AJAX方式登录
public String loginAjax(HttpServletRequest req, HttpServletResponse res){
String username = req.getParameter("username");
UserDao userDao = new UserDaoImpl();
UserInfo userInfo = userDao.loginAjax(username);
if(userInfo != null){
//req.setAttribute("name", username+"正确!");
try {
res.getWriter().println(username+"正确!");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else{
//req.setAttribute("name", username+"不存在!");
// return "login.jsp";
try {
res.getWriter().println(username+"不存在!");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return null;
}
}
3--------userDao---------------------------------------------------------------------------------------
package net.yaorange.dao;
import net.yaorange.entity.UserInfo;
public interface UserDao {
public UserInfo login(String name, String password);
/*
* AJAX请求用户名
* */
public UserInfo loginAjax(String name);
}
4-----------UserDaoImpl-----------------------------------------------------------------------------------------
package net.yaorange.dao.impl;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import net.yaorange.dao.UserDao;
import net.yaorange.entity.UserInfo;
import net.yaorange.utils.DBUtils;
public class UserDaoImpl implements UserDao {
Connection conn;
public UserInfo login(String name, String password) {
conn = DBUtils.getConnection();
String sql = "select * from userinfo where username=? and password = ?";
PreparedStatement pstmt = null;
UserInfo userInfo = null;
try {
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, name);
pstmt.setString(2, password);
ResultSet rs = pstmt.executeQuery();
while(rs.next()){
userInfo = new UserInfo();
userInfo.setUsername(rs.getString("username"));
userInfo.setPassword(rs.getString("password"));
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
if(conn != null)
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return userInfo;
}
/*
* AJAX请求用户名
* */
@Override
public UserInfo loginAjax(String name) {
conn = DBUtils.getConnection();
String sql = "select * from userinfo where username=?";
PreparedStatement pstmt = null;
UserInfo userInfo = null;
try {
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, name);
ResultSet rs = pstmt.executeQuery();
while(rs.next()){
userInfo = new UserInfo();
userInfo.setUsername(rs.getString("username"));
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
if(conn != null)
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return userInfo;
}
}
5-----------------BaseServlet--------------------------------------------------------------------------------------
package net.yaorange.controller;
import java.io.IOException;
import java.lang.reflect.Method;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class BaseServlet extends HttpServlet{
protected void service(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
String method_str = req.getParameter("method");
Class<? extends BaseServlet> clazz = this.getClass();
try {
Method method = clazz.getMethod(method_str, HttpServletRequest.class, HttpServletResponse.class);
String page = (String)method.invoke(this,req,res);
if(page != null && !page.isEmpty())
req.getRequestDispatcher(page).forward(req,res);
} catch (Exception e) {
e.printStackTrace();
}
}
}