User表:
User.java
package user.domain;
import java.io.Serializable;
import java.util.Date;
public class User implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
private Integer id;
private String name;
private String pass;
private Date birth;
public User(){
super();
}
public User(Integer id, String name, String pass, Date birth) {
super();
this.id = id;
this.name = name;
this.pass = pass;
this.birth = birth;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPass() {
return pass;
}
public void setPass(String pass) {
this.pass = pass;
}
public Date getBirth() {
return birth;
}
public void setBirth(Date birth) {
this.birth = birth;
}
@Override
public String toString() {
return "User [id=" + id + ", name=" + name + ", pass=" + pass
+ ", birth=" + birth + "]";
}
}
UserDao.java
package user.dao;
import java.util.List;
import user.domain.User;
public interface UserDao {
/**
* 根据用户和密码查询用户信息
*/
User checkLogin(String name,String pass);
}
实现接口的类UserDaoImp.java
package user.imp;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import user.dao.UserDao;
import user.domain.User;
import util.DBConn;
public class UserDaoImp implements UserDao {
private Connection conn;
private PreparedStatement pstmt;
private ResultSet rs;
public User checkLogin(String name, String pass) {
User entity=null;
String sql="select id,name,pass from user where name=? and pass=?";
conn=DBConn.getConn();
try {
pstmt=conn.prepareStatement(sql);
int index=1;
pstmt.setString(index++,name);
pstmt.setString(index++,pass);
rs=pstmt.executeQuery();
while(rs.next()){
entity=new User();
entity.setId(rs.getInt("id"));
entity.setName(rs.getString("name"));
entity.setPass(rs.getString("pass"));
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
DBConn.release(rs, pstmt);
}
return entity;
}
}
工具包DBConn.java
package util;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;
public class DBConn {
private static Connection conn;
private DBConn(){
}
public static Connection getConn(){
if(conn==null){
//创建集合对象
Properties properties=new Properties();
try {
//装载
properties.load(DBConn.class.getClassLoader().getResourceAsStream("db.properties"));
//加载驱动程序
Class.forName(properties.getProperty("driverClassName"));
//获取连接对象
conn=DriverManager.getConnection(properties.getProperty("url"),properties.getProperty("user"),properties.getProperty("pass"));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return conn;
}
public static void update(String sql,Object params[],PreparedStatement pstmt) throws Exception{
pstmt=getConn().prepareStatement(sql);
for (int i = 0; i < params.length; i++) {
pstmt.setObject(i+1, params[i]);
}
pstmt.executeUpdate();
release(null,pstmt);
}
public static void release(ResultSet rs, PreparedStatement pstmt) {
if (rs!=null) {
try {
rs.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (pstmt!=null) {
try {
pstmt.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
工具包实现验证码RandomImage.java
package www.hbsi.csdn.util;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.util.Random;
import javax.servlet.http.HttpSession;
/**
* 验证码
* @author yanmei
*
*/
public class RandomImage {
private final static int W=80;
private final static int H=30;
public static BufferedImage createImage(HttpSession session){
//创建图片
BufferedImage image=new BufferedImage(W, H, BufferedImage.TYPE_INT_RGB);
//得到图形绘制的对象
Graphics g=image.getGraphics();
//设置背景颜色
setBackGroud(g);
//设置边框
setBorder(g);
//绘制内容
StringBuffer sb=drawContent(g);
session.setAttribute("checkCode", sb);
//绘制干扰线
drawDisturbline(g);
return image;
}
private static void drawDisturbline(Graphics g) {
g.setColor(Color.blue);
Random r=new Random();
for (int i = 0; i < 4; i++) {
int x1 = r.nextInt(W);
int y1 = r.nextInt(H);
int x2 = r.nextInt(W);
int y2 = r.nextInt(H);
g.drawLine(x1, y1, x2, y2);
}
}
private static StringBuffer drawContent(Graphics g) {
// TODO Auto-generated method stub
//字节资源
String re = "u7684u4e00u4e86u662fu6211u4e0du5728u4ebau4eecu6709u6765u4ed6u8fd9u4e0au7740u4e2au5730u5230u5927u91ccu8bf4u5c31u53bbu5b50u5f97u4e5fu548cu90a3u8981u4e0bu770bu5929u65f6u8fc7u51fau5c0fu4e48u8d77u4f60u90fdu628au597du8fd8u591au6ca1u4e3au53c8u53efu5bb6u5b66u53eau4ee5u4e3bu4f1au6837u5e74u60f3u751fu540cu8001u4e2du5341u4eceu81eau9762u524du5934u9053u5b83u540eu7136u8d70u5f88u50cfu89c1u4e24u7528u5979u56fdu52a8u8fdbu6210u56deu4ec0u8fb9u4f5cu5bf9u5f00u800cu5df1u4e9bu73b0u5c71u6c11u5019u7ecfu53d1u5de5u5411u4e8bu547du7ed9u957fu6c34u51e0u4e49u4e09u58f0u4e8eu9ad8u624bu77e5u7406u773cu5fd7u70b9u5fc3u6218u4e8cu95eeu4f46u8eabu65b9u5b9eu5403u505au53ebu5f53u4f4fu542cu9769u6253u5462u771fu5168u624du56dbu5df2u6240u654cu4e4bu6700u5149u4ea7u60c5u8defu5206u603bu6761u767du8bddu4e1cu5e2du6b21u4eb2u5982u88abu82b1u53e3u653eu513fu5e38u6c14u4e94u7b2cu4f7fu5199u519bu5427u6587u8fd0u518du679cu600eu5b9au8bb8u5febu660eu884cu56e0u522bu98deu5916u6811u7269u6d3bu90e8u95e8u65e0u5f80u8239u671bu65b0u5e26u961fu5148u529bu5b8cu5374u7ad9u4ee3u5458u673au66f4u4e5du60a8u6bcfu98ceu7ea7u8ddfu7b11u554au5b69u4e07u5c11u76f4u610fu591cu6bd4u9636u8fdeu8f66u91cdu4fbfu6597u9a6cu54eau5316u592au6307u53d8u793eu4f3cu58ebu8005u5e72u77f3u6ee1u65e5u51b3u767eu539fu62ffu7fa4u7a76u5404u516du672cu601du89e3u7acbu6cb3u6751u516bu96beu65e9u8bbau5417u6839u5171u8ba9u76f8u7814u4ecau5176u4e66u5750u63a5u5e94u5173u4fe1u89c9u6b65u53cdu5904u8bb0u5c06u5343u627eu4e89u9886u6216u5e08u7ed3u5757u8dd1u8c01u8349u8d8au5b57u52a0u811au7d27u7231u7b49u4e60u9635u6015u6708u9752u534au706bu6cd5u9898u5efau8d76u4f4du5531u6d77u4e03u5973u4efbu4ef6u611fu51c6u5f20u56e2u5c4bu79bbu8272u8138u7247u79d1u5012u775bu5229u4e16u521au4e14u7531u9001u5207u661fu5bfcu665au8868u591fu6574u8ba4u54cdu96eau6d41u672au573au8be5u5e76u5e95u6df1u523bu5e73u4f1fu5fd9u63d0u786eu8fd1u4eaeu8f7bu8bb2u519cu53e4u9ed1u544au754cu62c9u540du5440u571fu6e05u9633u7167u529eu53f2u6539u5386u8f6cu753bu9020u5634u6b64u6cbbu5317u5fc5u670du96e8u7a7fu5185u8bc6u9a8cu4f20u4e1au83dcu722cu7761u5174u5f62u91cfu54b1u89c2u82e6u4f53u4f17u901au51b2u5408u7834u53cbu5ea6u672fu996du516cu65c1u623fu6781u5357u67aau8bfbu6c99u5c81u7ebfu91ceu575au7a7au6536u7b97u81f3u653fu57ceu52b3u843du94b1u7279u56f4u5f1fu80dcu6559u70edu5c55u5305u6b4cu7c7bu6e10u5f3au6570u4e61u547cu6027u97f3u7b54u54e5u9645u65e7u795eu5ea7u7ae0u5e2eu5566u53d7u7cfbu4ee4u8df3u975eu4f55u725bu53d6u5165u5cb8u6562u6389u5ffdu79cdu88c5u9876u6025u6797u505cu606fu53e5u533au8863u822cu62a5u53f6u538bu6162u53d4u80ccu7ec6";
//获取字符的长度
int length=re.length();
//随机操作对象
Random r=new Random();
//存储字符的对象
StringBuffer sb=new StringBuffer();
for (int i = 0; i < 4; i++) {
//随机产生数字
int index=r.nextInt(length);
//获取字符
char c=re.charAt(index);
sb.append(c);
}
g.setColor(Color.black);
g.drawString(sb.toString(),20,20);
return sb;
}
private static void setBorder(Graphics g) {
g.setColor(Color.black);
g.drawRect(0, 0, W-2, H-2);
}
private static void setBackGroud(Graphics g) {
// 绘制矩形
g.setColor(Color.yellow);
g.fillRect(0, 0, W, H);
}
}
ImageServlet.java
package www.csdn.day36.servlet;
import java.awt.Color;
import java.awt.Graphics;
import java.io.IOException;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import www.hbsi.csdn.util.RandomImage;
public class ImageServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 禁止浏览器缓存数据
response.setHeader("expires", "0");
response.setHeader("Cache-Control", "no-cache");
response.setHeader("Pragma", "no-cache");
// 1.通知浏览器以图片的方式打开数据
response.setContentType("image/jpeg");
// 把图片显示给浏览器
ImageIO.write(RandomImage.createImage(request.getSession()), "jpeg",
response.getOutputStream());
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doGet(request, response);
}
}
db.properties
url=jdbc:mysql://localhost:3306/csdn?useUnicode=true&characterEncoding=UTF-8
user=root
pass=113
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
<display-name></display-name>
<servlet>
<servlet-name>DemoServlet</servlet-name>
<servlet-class>www.csdn.day36.servlet.DemoServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>ImageServlet</servlet-name>
<servlet-class>www.csdn.day36.servlet.ImageServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>Servlet1</servlet-name>
<servlet-class>www.csdn.day36.servlet.Servlet1</servlet-class>
</servlet>
<servlet>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>www.csdn.day36.servlet.LoginServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>ChaServlet</servlet-name>
<servlet-class>www.csdn.day36.servlet.ChaServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>DemoServlet</servlet-name>
<url-pattern>/servlet/DemoServlet</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>ImageServlet</servlet-name>
<url-pattern>/servlet/ImageServlet</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>Servlet1</servlet-name>
<url-pattern>/servlet/Servlet1</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/login.do</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>ChaServlet</servlet-name>
<url-pattern>/chalogin.do</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
ChaServlet.java
package www.csdn.day36.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ChaServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Cookie cookies[]=request.getCookies();
if(cookies!=null){
for(Cookie cookie:cookies){
if("loginData".equals(cookie.getName())){
String value=cookie.getValue();
String data[]=value.split(":");
String name=data[0];
String pass=data[1];
request.setAttribute("name", name);
request.setAttribute("pass", pass);
}
}
}
request.getRequestDispatcher("./login.jsp").forward(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doGet(request, response);
}
}
LoginServlet.java
package www.csdn.day36.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import user.dao.UserDao;
import user.domain.User;
import user.imp.UserDaoImp;
public class LoginServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
UserDao userDao = new UserDaoImp();
String checkCode = request.getParameter("checkCode");
StringBuffer createCheckCode = (StringBuffer) request.getSession()
.getAttribute("checkCode");
String ccode = createCheckCode.toString();
// System.out.println(ccode+"============="+checkCode);
response.setContentType("text/html");
response.setCharacterEncoding("UTF-8");
PrintWriter out = response.getWriter();
// 判断验证码
if (ccode.equals(checkCode)) {
// 获取登陆的名称
String name = request.getParameter("name");
// 获取登陆的密码
String pass = request.getParameter("pass");
User entity = userDao.checkLogin(name, pass);
if (entity != null) {
// 运行cookie保存数据
Cookie cookie = new Cookie("loginData", name + ":" + pass);
//System.out.println(cookie);
cookie.setMaxAge(7 * 24 * 60 * 60);
response.addCookie(cookie);
out.print("用户名存在");
} else {
out.print("用户名和密码错误");
}
} else {
out.print("验证码错误");
}
out.close();
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doGet(request, response);
}
}
login.js
var errorDom;
window.onload = function() {
//alert("12123");
errorDom = document.getElementById("error");
var loginBtnDom = document.getElementById("loginBtn");
loginBtnDom.onclick = loginCustomer;
};
var loginCustomer = function() {
var name=document.getElementById("cname").value;
var pass=document.getElementById("cpass").value;
var checkCode = document.getElementById("checkCode").value;
//alert(checkCode);
var xmlHttp = getXMLHttp();
var data="name="+encodeURIComponent(name)+"&pass="+encodeURIComponent(pass)+"&checkCode="+encodeURIComponent(checkCode)+"&oper=login";
xmlHttp.open("GET", "./login.do?"+data);
xmlHttp.send();
xmlHttp.onreadystatechange = checkLogin;
};
var checkLogin = function() {
if (this.readyState == 4 && this.status == 200) {
errorDom.innerText= this.responseText;
}
};
util.js
function getXMLHttp() {
var xmlHttp;
try {
// firefox Opera
xmlHttp = new XMLHttpRequest();
} catch (e) {
try {
// IE
xmlHttp = new ActiveXObject("MSXML2.XMLHTTP5.0");
} catch (ex) {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlHttp;
}
index.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'index.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
<a href="./chalogin.do">查询</a>
</body>
</html>
主页面login.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'login.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
<div align="center">
<form action="./login.do" method="post">
<table border="1px" cellpadding="0" cellspacing="0">
<tr>
<td>用户名:</td>
<td colspan="2"><input type="text" id="cname" value="${name}"/></td>
</tr>
<tr>
<td>密码:</td>
<td colspan="2"><input type="password" id="cpass" value="${pass}"/></td>
</tr>
<tr>
<td>验证码:</td>
<td colspan="2"><input type="text" id="checkCode" /></td>
<td><img alt="验证码" src="./servlet/ImageServlet" /></td>
</tr>
<tr align="center">
<td colspan="3"><input type="button" value="登录" id="loginBtn" />
<span id="error" style="font-size:12px; color: blue;"></span></td>
</tr>
</table>
</form>
</div>
</body>
</html>