- 登录页面:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%
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">
-->
<script type="text/javascript">
//让图片刷新
function _click() {
var d = new Date();
//当路径有变化时,就会刷新图片,而get方法后面加上一个?号就会刷新,以这里创建一个事件对象,然后通过组合让路径不断变化
document.getElementById("img").src = "${pageContext.request.contextPath}/img?"+ d.getMilliseconds();
}
//修改同一个表单的提交地址
function chaAction(v){
var form3=document.getElementById("form3");
if(v==1){
form3.action="${pageContext.request.contextPath}/login";
}
if(v==2){
form3.action="register.jsp";
}
form3.submit();
}
function save(){
var save=document.getElementById("savepwd");
var hid=document.getElementById("hid");
if(save.checked)
{
//选中了,表示保存用户 密码
hid.setAttribute("value","1");
}
}
</script>
<style type="text/css">
table{
margin: 30px auto;
border:1px solid #B3CDDB;
font-family:"微软雅黑";
color:white;
}
td{
padding:10px;
height:40px;
}
.but{
background-color: white;
border:0 none;
height:30px;
width:70px;
font:15px bold ;
font-family:"微软雅黑";
color:#2088B7;
font-weight:bold;
}
#img{
vertical-align:middle;
}
body{
background: url("2.jpg");
}
</style>
</head>
<body>
<%
//获取保存在session中的用户名,将用户名放到输入栏中
//String username =(String)request.getSession().getAttribute("username");
// 获取cookie的数组
Cookie[] arr=request.getCookies();
String name =null;
String pwd=null;
//遍历数组
if(arr!=null)
{
for(Cookie c : arr)
{
String name1=c.getName();
String value=c.getValue();
//这里的顺序需要注意,判断中的username是cookie中的username
if("name".equals(name1))
{
name=value;
}
if("pwd".equals(name1))
{
pwd=value;
}
}
}
%>
<form action="" method="post" id="form3">
<table>
<tr align="center">
<td colspan="2"><font color="#FF00FF"><b><font color="white">用户登录</font></b></font></td>
</tr>
<tr>
<td colspan="2"><font color=red>${errMsg}</font></td>
</tr>
<tr>
<td>用户名:</td>
<td><input type="text" name="name" value="<%=name==null?"":name%>"></td>
</tr>
<tr>
<td>密码:</td>
<td><input type="password" name="password" value="<%=pwd==null?"":pwd%>" style="vertical-align:middle;"></td>
</tr>
<tr>
<td id="ctd">验证码</td>
<td>
<%-- 创建验证码的name属性,让servlet获取到验证码中输入的值 --%>
<input type="text" name="imgCode">
<img src="${pageContext.request.contextPath}/img" id="img" οnclick="_click() ">
<a href="javascript:void(0)" οnclick="_click()" style="text-decoration:none;"><font color="#B3CDDB">看不清,换一张</font></a>
</td>
</tr>
<tr>
<%-- 通过修改value的值来达到目的 --%>
<td><input type="hidden" name="hid" id="hid" value="0"></td>
<td><input type="checkbox" οnclick="save()" id="savepwd">是否保存用户密码</td>
</tr>
<tr >
<td align="center" colspan="2"><input type="submit" class="but" value="登录" οnclick="chaAction(1)">
<input type="submit" class="but" value="注册" οnclick="chaAction(2)"></td>
</tr>
</table>
</form>
</body>
</html>
2.注册成功页面:
<%@ 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 'welcome.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="refresh" content="3;login.jsp">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
<style type="text/css">
body{
background: url("2.jpg");
}
div{
height: 200px;
margin-top: 90px;
}
</style>
</head>
<body>
<div align="center" ><font color="white" size="4"><b>注册成功,3秒钟后跳转到登录页面</b></font></div>
</body>
</html>
3.注册页面:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<c:set var="root" value="${pageContext.request.contextPath}"/>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>注册页面</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<script type="text/javascript">
function _changImg(){
document.getElementById("img").src = "${root}/img?" + new Date().getTime();
}
function chaAction(v){
var form1=document.getElementById("form1");
if(v==1){
form1.action="${root}/registerServlet";
}
if(v==2){
form1.action="login.jsp";
}
form1.submit();
}
</script>
<style type="text/css">
table{
margin: 30px auto;
border:1px solid #B3CDDB;
font-family:"微软雅黑";
color:white;
}
td{
padding:5px;
height:33px;
}
.but{
background-color: white;
border:0 none;
height:30px;
width:70px;
font:15px bold ;
font-family:"微软雅黑";
color:#2088B7;
font-weight:bold;
}
#img{
vertical-align:middle;
}
body{
background: url("2.jpg");
}
</style>
</head>
<body>
<center>
<%-- 这里可以使用${root} 或者${pageContext.Request.contextPath} 来获取当前项目路径 --%>
<form action="" method="post" id="form1">
<table>
<tr align="center">
<td colspan="2"><font color="#FF00FF"><b><font color="white">用户注册</font></b></font></td>
</tr>
<tr>
<td name="errMsg" align="center"><font color="red">${errMsg }</font></td>
</tr>
<tr>
<td>用户名<font color="red">*</font></td>
<td><input type="text" name="name"/></td>
</tr>
<tr>
<td>密码</td>
<td><input type="password" name="password"/></td>
</tr>
<tr>
<td>确认密码</td>
<td><input type="password" name="repassword"/></td>
</tr>
<tr>
<td>年龄</td>
<td><input type="text" name="age"/></td>
</tr>
<tr>
<td>性别</td>
<td>
<input type="radio" name="sex" value="男"/>男
<input type="radio" name="sex" value="女"/>女
</td>
</tr>
<tr>
<td>邮箱</td>
<td><input type="text" name="email"/></td>
</tr>
<tr>
<td>生日</td>
<td><input type="text" name="birthday" id="birthday"/></td>
</tr>
<tr>
<td>爱好</td>
<td>
<input type="checkbox" name="hobby" value="C"/>C
<input type="checkbox" name="hobby" value="C++"/>C++
<input type="checkbox" name="hobby" value="Java"/>Java
<input type="checkbox" name="hobby" value="IOS"/>IOS
<input type="checkbox" name="hobby" value="PHP"/>PHP
<input type="checkbox" name="hobby" value="Android"/>Android
</td>
</tr>
<tr>
<td>地址</td>
<td>
<select name="address">
<option value="none">--请选择地址--</option>
<option value="北京">北京</option>
<option value="上海">上海</option>
<option value="南京">南京</option>
<option value="广州">广州</option>
<option value="深圳">深圳</option>
</select>
</td>
</tr>
<tr>
<td>自我描述</td>
<td>
<textarea cols="40" rows="10" name="description"></textarea>
</td>
</tr>
<tr>
<td>输入验证码</td>
<td>
<input type="text" name="checkImg" />
<img style="cursor: pointer;" alt="" src="${root }/img" id="img" οnclick="_changImg();"/>
<a href="javascript:void(0);" οnclick="_changImg();" style="text-decoration:none"><font color="#B3CDDB">看不清,换一张</font></a>
</td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" value="注册" class="but" οnclick="chaAction(1)"/>
<input type="submit" class="but" value="返回登录" οnclick="chaAction(2)"></td>
</tr>
</table>
</form>
</center>
</body>
</html>
4.登录页面:
<%@ 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">
-->
<style type="text/css">
body{
background: url("2.jpg");
}
div{
height: 200px;
margin-top: 90px;
}
</style>
</head>
<body>
<div align="center" ><marquee><font color="white" size="4"><b>登录成功</b></font></marquee></div>
</body>
</html>
5.用户类:
package com.yynh.domain;
import java.sql.Date;
/**
* @author wjn 与day13数据user表对应的实现类
*/
public class User {
private int id;
private String name;
private String password;
private int age;
private String sex;
private String email;
private String hobby;
private String address;
private String description;
private Date birthday;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getHobby() {
return hobby;
}
public void setHobby(String hobby) {
this.hobby = hobby;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
@Override
public String toString() {
return "User [id=" + id + ", name=" + name + ", password=" + password + ", age=" + age + ", sex=" + sex + ", email=" + email + ", hobby=" + hobby + ", address=" + address + ", description=" + description + ", birthday=" + birthday + "]";
}
}
6.工具类:
package com.yynh.utils;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import com.mchange.v2.c3p0.ComboPooledDataSource;
public class JDBCUtils {
// 创建c3p0开元连接池对象,传入指定配置
static ComboPooledDataSource cpds = new ComboPooledDataSource();
// 释放资源
public static void release(Connection conn, ResultSet rs, Statement stmt) {
try {
// 为了防止rs没有而报异常,进行判断
if (rs != null) {
rs.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
// 如果在判断中出现异常了,就直接将rs赋值null,避免问题
rs = null;
// 如果是select操作,就继续调用其他两个异常
release(conn, stmt);
}
// 释放资源二次优化,通过函数的重写,来区分是否是select操作
public static void release(Connection conn, Statement stmt) {
try {
if (stmt != null) {
stmt.close();
}
} catch (Exception e2) {
}
stmt = null;
try {
if (conn != null) {
conn.close();
}
} catch (Exception e2) {
}
conn = null;
}
public static Connection getCon() throws Exception {
// 通过连接池获得连接
Connection conn = cpds.getConnection();
// 将conn返回
return conn;
}
}
7.配置文件
<?xml version="1.0" encoding="UTF-8"?>
<c3p0-config>
<!-- 默认配置,c3p0框架默认加载这段默认配置 -->
<default-config>
<!-- 配置JDBC 四个基本属性 -->
<property name="driverClass">com.mysql.jdbc.Driver</property>
<property name="jdbcUrl">jdbc:mysql://localhost:3306/day13</property>
<property name="user">root</property>
<property name="password">123</property>
</default-config> <!-- This app is massive! -->
</c3p0-config>
8.验证码:
package com.yynh.web;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
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;
public class ImgServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 图片验证码
// 创建一张画布
// 设定长和宽
int width = 120;
int height = 35;
// imageType 指的是颜色的格式,这里用rgb
BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
// 从画布上获取画笔, getGraphics() graphics
Graphics2D g = bi.createGraphics();
// 填充背景颜色
g.setColor(Color.white);
// 填充范围
g.fillRect(0, 0, width, height);
// 绘制边框
g.setColor(Color.red);
// 填充边框
g.drawRect(0, 0, width - 1, height - 1);
// 生成四个随机数据
// 准备数据 ctrl+shift+x 将选中的文本大写, Ctrl + shift +y 将选中的文本小写
String data = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
// 设置一个随机对象
Random r = new Random();
// 设置一个变量保存验证码
String code = "";
// 循环
for (int i = 1; i < 5; i++) {
// 将画布旋转
// 获取一个随机值,先获取一个范围在-1-1 之间的随机数,再减0.5就能获得一个0-0.5之间的随机数
double theta = (Math.random() - 0.5);
// 旋转一定的角度
g.rotate(theta, 22 * i, height / 2);
// 设置字体,传一个字体对象
g.setFont(new Font("宋体", Font.ITALIC, 27));
// 设置随机颜色 通过color的构造函数来传参数
g.setColor(new Color(r.nextInt(255), r.nextInt(255), r.nextInt(255)));
// 根据字符串的长度随机获得一个下标,然后通过下标得到一个字符,然后变成字符串
String str = data.charAt(r.nextInt(data.length())) + "";
// 将字符写入到画布上,并调整位置
g.drawString(str, i * 22, 30);
// 将画布旋转回来
g.rotate(-theta, 22 * i, height / 2);
// 将每个字符拼接到一起
code += str;
}
// 设置session保存code
request.getSession().setAttribute("checkCode", code);
// 画干扰线
for (int i = 1; i < 7; i++) {
// 设置随机颜色
g.setColor(new Color(r.nextInt(100) + 100, r.nextInt(100) + 100, r.nextInt(100) + 100));
// 将线条画到画布上 两个值确定一个点,两个点确定一条线
g.drawLine(r.nextInt(width), r.nextInt(height), r.nextInt(width), r.nextInt(height));
}
// 将画布输出到浏览器
ImageIO.write(bi, "jpg", response.getOutputStream());
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
9.登录servlet
package com.yynh.web;
import java.io.IOException;
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 com.yynh.domain.User;
import com.yynh.service.ServiceLogin;
import com.yynh.service.ServiceUser;
public class LoginServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 解决乱码问题
response.setContentType("text/html;charset=utf-8");
request.setCharacterEncoding("utf-8");
// 获取保存在本地的验证码
String checkCode = (String) request.getSession().getAttribute("checkCode");
// 打印验证码
System.out.println(checkCode);
// 获取用户输入的验证码
String imgCode = request.getParameter("imgCode");
System.out.println(imgCode);
// 移除本地验证码
request.getSession().removeAttribute("checkCode");
// 第一步:判断验证码是否正确
if (imgCode == null || !imgCode.equalsIgnoreCase(checkCode)) {
// 当验证码没有输入或者和本地验证码不相同的时候,请求转发 转发不需要加项目名
request.setAttribute("errMsg", "验证码有误");
request.getRequestDispatcher("/login.jsp").forward(request, response);
return;
}
// 获取数据
User user = new User();
String name = request.getParameter("name");
String password = request.getParameter("password");
user.setName(name);
user.setPassword(password);
// 调用业务
ServiceUser su = new ServiceLogin();
int i = su.loginUser(user);
if (i == 1) {
// 代表登录成功
Cookie cookie = new Cookie("name", name);
// 设置时间
cookie.setMaxAge(60 * 60 * 24);
// 设置路径
cookie.setPath("/");
response.addCookie(cookie);
String hid = request.getParameter("hid");
System.out.println("woshi" + hid);
if (hid.equals("1")) {
Cookie coo = new Cookie("pwd", password);
// 设置时间
cookie.setMaxAge(60 * 2);
// 设置路径
cookie.setPath("/");
response.addCookie(coo);
}
// 将用户对象保存到session中
request.getSession().setAttribute("user", user);
// 重定向到成功页面
response.sendRedirect(request.getContextPath());
return;
}
if (i == 0) {
// 代表用户名或者秘密错误
request.setAttribute("errMsg", "用户名或者密码有误");
request.getRequestDispatcher("/login.jsp").forward(request, response);
return;
}
if (i == -1) {
// 代表异常
request.setAttribute("errMsg", "服务器忙,稍后再试");
request.getRequestDispatcher("/login.jsp").forward(request, response);
return;
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
10 注册servlet
package com.yynh.web;
import java.io.IOException;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.beanutils.BeanUtils;
import com.yynh.domain.User;
import com.yynh.service.ServiceUser;
import com.yynh.service.ServiceUserCheck;
public class RegisterServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 解决乱码问题
response.setContentType("text/html;charset=utf-8");
request.setCharacterEncoding("utf-8");
// 获取保存在本地的验证码
String checkCode = (String) request.getSession().getAttribute("checkCode");
// 打印验证码
System.out.println(checkCode);
// 获取用户输入的验证码
String checkImg = request.getParameter("checkImg");
System.out.println(checkImg);
// 移除本地验证码
request.getSession().removeAttribute("checkCode");
// 第一步:判断验证码是否正确
if (checkImg == null || !checkImg.equalsIgnoreCase(checkCode)) {
// 当验证码没有输入或者和本地验证码不相同的时候,请求转发 转发不需要加项目名
request.setAttribute("errMsg", "验证码有误");
request.getRequestDispatcher("/register.jsp").forward(request, response);
return;
}
// 封装数据,调用业务层处理业务
User user = new User();
// 获取所有的属性
Map<String, String[]> map = request.getParameterMap();
// 获取javabean
try {
// 将数据封装到javaBean中
BeanUtils.populate(user, map);
} catch (Exception e) {
e.printStackTrace();
}
// 第二步:单独封装爱好
String[] hobby = request.getParameterValues("hobby");
String temp = "";
for (String s : hobby) {
temp = temp + "," + s;
}
// 去除开始的逗号
temp = temp.substring(1);
user.setHobby(temp);
System.out.println(user);
// 第三步:调用service层处理业务
ServiceUser sUser = new ServiceUserCheck();
// 接收返回的值
int i = sUser.register(user);
// 处理返回的值
if (i == 1) {
// 代表注册成功,跳转到成功页面
// 跳转需要项目名
response.sendRedirect(request.getContextPath() + "/welcome.jsp");
return;
} else if (i == 0) {
// 代表注册失败,用户名已存在
// 提示信息
request.setAttribute("errMsg", "用户名已被注册");
request.getRequestDispatcher("/register.jsp").forward(request, response);
return;
} else {
// 代表有异常
request.setAttribute("errMsg", "服务器忙,请稍后再试");
request.getRequestDispatcher("/register.jsp").forward(request, response);
return;
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 调用doGet方法
doGet(request, response);
}
}
11. 登录service
package com.yynh.service;
import com.yynh.dao.UserDao;
import com.yynh.dao.UserDaoReg;
import com.yynh.domain.User;
public class ServiceLogin implements ServiceUser {
@Override
public int register(User user) {
// TODO Auto-generated method stub
return 0;
}
@Override
public int loginUser(User user) {
UserDao ud = new UserDaoReg();
int i = ud.login(user);
if (i == 1) {
// 代表登录成功
return 1;
} else {
return i;
}
}
}
12.注册service
package com.yynh.service;
import com.yynh.dao.UserDao;
import com.yynh.dao.UserDaoReg;
import com.yynh.domain.User;
/**
* @author yynh_
* @注册业务
*/
public class ServiceUserCheck implements ServiceUser {
public int register(User user) {
UserDao ud = new UserDaoReg();
// 判断用户名是否已经注册
int i = ud.findUser(user.getName());
if (i == 1) {
// 代表可以注册用户
// 加密密码 加密后暂时还没有办法登录
// String pwd = MD5Utils.getPwd(user.getPassword());
// 将加密后的结果存入user中
// user.setPassword(pwd);
// 注册成功
return ud.registerUser(user);
} else {
// 代表用户名已经存在或者存在异常
return i;
}
}
public int loginUser(User user) {
return 0;
}
}
13. dao层
package com.yynh.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import com.yynh.domain.User;
import com.yynh.utils.JDBCUtils;
public class UserDaoReg implements UserDao {
// 用户登录
public int login(User user) {
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
try {
// 获取连接
conn = JDBCUtils.getCon();
String sql = "select * from user where name=? and password=?";
// 获取发送sql对象
stmt = conn.prepareStatement(sql);
// 设置属性
stmt.setString(1, user.getName());
stmt.setString(2, user.getPassword());
// 发送sql,接受返回值
rs = stmt.executeQuery();
if (rs.next()) {
// 代表密码用户名正确,可以登录
return 1;
} else {
// 代表不正确
return 0;
}
} catch (Exception e) {
e.printStackTrace();
return -1;
} finally {
JDBCUtils.release(conn, rs, stmt);
}
}
// 注册用户
public int registerUser(User user) {
Connection conn = null;
PreparedStatement stmt = null;
try {
// 获取连接
conn = JDBCUtils.getCon();
String sql = "insert into user values(null,?,?,?,?,?,?,?,?,?)";
// 获取发送sql对象
stmt = conn.prepareStatement(sql);
// 设置属性
stmt.setString(1, user.getName());
stmt.setString(2, user.getPassword());
stmt.setInt(3, user.getAge());
stmt.setString(4, user.getSex());
stmt.setString(5, user.getEmail());
stmt.setString(6, user.getHobby());
stmt.setString(7, user.getAddress());
stmt.setString(8, user.getDescription());
stmt.setDate(9, user.getBirthday());
stmt.executeUpdate();
return 1;
} catch (Exception e) {
e.printStackTrace();
return -1;
}
}
// 查询用户名是否存在
public int findUser(String name) {
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
try {
// 获取连接
conn = JDBCUtils.getCon();
String sql = "select * from user where name=?";
// 获取发送sql对象
stmt = conn.prepareStatement(sql);
// 设置属性
stmt.setString(1, name);
// 发送sql,接受返回值
rs = stmt.executeQuery();
if (rs.next()) {
// 代表有重复的用户名了
return 0;
} else {
// 代表没有重复的可以注册
return 1;
}
} catch (Exception e) {
e.printStackTrace();
return -1;
} finally {
JDBCUtils.release(conn, rs, stmt);
}
}
}
效果:
第一次在csdn发帖,唉,完全搞不懂这里的排版,不知道会排成什么样子.......
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%
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">
-->
<script type="text/javascript">
//让图片刷新
function _click() {
var d = new Date();
//当路径有变化时,就会刷新图片,而get方法后面加上一个?号就会刷新,以这里创建一个事件对象,然后通过组合让路径不断变化
document.getElementById("img").src = "${pageContext.request.contextPath}/img?"+ d.getMilliseconds();
}
//修改同一个表单的提交地址
function chaAction(v){
var form3=document.getElementById("form3");
if(v==1){
form3.action="${pageContext.request.contextPath}/login";
}
if(v==2){
form3.action="register.jsp";
}
form3.submit();
}
function save(){
var save=document.getElementById("savepwd");
var hid=document.getElementById("hid");
if(save.checked)
{
//选中了,表示保存用户 密码
hid.setAttribute("value","1");
}
}
</script>
<style type="text/css">
table{
margin: 30px auto;
border:1px solid #B3CDDB;
font-family:"微软雅黑";
color:white;
}
td{
padding:10px;
height:40px;
}
.but{
background-color: white;
border:0 none;
height:30px;
width:70px;
font:15px bold ;
font-family:"微软雅黑";
color:#2088B7;
font-weight:bold;
}
#img{
vertical-align:middle;
}
body{
background: url("2.jpg");
}
</style>
</head>
<body>
<%
//获取保存在session中的用户名,将用户名放到输入栏中
//String username =(String)request.getSession().getAttribute("username");
// 获取cookie的数组
Cookie[] arr=request.getCookies();
String name =null;
String pwd=null;
//遍历数组
if(arr!=null)
{
for(Cookie c : arr)
{
String name1=c.getName();
String value=c.getValue();
//这里的顺序需要注意,判断中的username是cookie中的username
if("name".equals(name1))
{
name=value;
}
if("pwd".equals(name1))
{
pwd=value;
}
}
}
%>
<form action="" method="post" id="form3">
<table>
<tr align="center">
<td colspan="2"><font color="#FF00FF"><b><font color="white">用户登录</font></b></font></td>
</tr>
<tr>
<td colspan="2"><font color=red>${errMsg}</font></td>
</tr>
<tr>
<td>用户名:</td>
<td><input type="text" name="name" value="<%=name==null?"":name%>"></td>
</tr>
<tr>
<td>密码:</td>
<td><input type="password" name="password" value="<%=pwd==null?"":pwd%>" style="vertical-align:middle;"></td>
</tr>
<tr>
<td id="ctd">验证码</td>
<td>
<%-- 创建验证码的name属性,让servlet获取到验证码中输入的值 --%>
<input type="text" name="imgCode">
<img src="${pageContext.request.contextPath}/img" id="img" οnclick="_click() ">
<a href="javascript:void(0)" οnclick="_click()" style="text-decoration:none;"><font color="#B3CDDB">看不清,换一张</font></a>
</td>
</tr>
<tr>
<%-- 通过修改value的值来达到目的 --%>
<td><input type="hidden" name="hid" id="hid" value="0"></td>
<td><input type="checkbox" οnclick="save()" id="savepwd">是否保存用户密码</td>
</tr>
<tr >
<td align="center" colspan="2"><input type="submit" class="but" value="登录" οnclick="chaAction(1)">
<input type="submit" class="but" value="注册" οnclick="chaAction(2)"></td>
</tr>
</table>
</form>
</body>
</html>
2.注册成功页面:
<%@ 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 'welcome.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="refresh" content="3;login.jsp">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
<style type="text/css">
body{
background: url("2.jpg");
}
div{
height: 200px;
margin-top: 90px;
}
</style>
</head>
<body>
<div align="center" ><font color="white" size="4"><b>注册成功,3秒钟后跳转到登录页面</b></font></div>
</body>
</html>
3.注册页面:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<c:set var="root" value="${pageContext.request.contextPath}"/>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>注册页面</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<script type="text/javascript">
function _changImg(){
document.getElementById("img").src = "${root}/img?" + new Date().getTime();
}
function chaAction(v){
var form1=document.getElementById("form1");
if(v==1){
form1.action="${root}/registerServlet";
}
if(v==2){
form1.action="login.jsp";
}
form1.submit();
}
</script>
<style type="text/css">
table{
margin: 30px auto;
border:1px solid #B3CDDB;
font-family:"微软雅黑";
color:white;
}
td{
padding:5px;
height:33px;
}
.but{
background-color: white;
border:0 none;
height:30px;
width:70px;
font:15px bold ;
font-family:"微软雅黑";
color:#2088B7;
font-weight:bold;
}
#img{
vertical-align:middle;
}
body{
background: url("2.jpg");
}
</style>
</head>
<body>
<center>
<%-- 这里可以使用${root} 或者${pageContext.Request.contextPath} 来获取当前项目路径 --%>
<form action="" method="post" id="form1">
<table>
<tr align="center">
<td colspan="2"><font color="#FF00FF"><b><font color="white">用户注册</font></b></font></td>
</tr>
<tr>
<td name="errMsg" align="center"><font color="red">${errMsg }</font></td>
</tr>
<tr>
<td>用户名<font color="red">*</font></td>
<td><input type="text" name="name"/></td>
</tr>
<tr>
<td>密码</td>
<td><input type="password" name="password"/></td>
</tr>
<tr>
<td>确认密码</td>
<td><input type="password" name="repassword"/></td>
</tr>
<tr>
<td>年龄</td>
<td><input type="text" name="age"/></td>
</tr>
<tr>
<td>性别</td>
<td>
<input type="radio" name="sex" value="男"/>男
<input type="radio" name="sex" value="女"/>女
</td>
</tr>
<tr>
<td>邮箱</td>
<td><input type="text" name="email"/></td>
</tr>
<tr>
<td>生日</td>
<td><input type="text" name="birthday" id="birthday"/></td>
</tr>
<tr>
<td>爱好</td>
<td>
<input type="checkbox" name="hobby" value="C"/>C
<input type="checkbox" name="hobby" value="C++"/>C++
<input type="checkbox" name="hobby" value="Java"/>Java
<input type="checkbox" name="hobby" value="IOS"/>IOS
<input type="checkbox" name="hobby" value="PHP"/>PHP
<input type="checkbox" name="hobby" value="Android"/>Android
</td>
</tr>
<tr>
<td>地址</td>
<td>
<select name="address">
<option value="none">--请选择地址--</option>
<option value="北京">北京</option>
<option value="上海">上海</option>
<option value="南京">南京</option>
<option value="广州">广州</option>
<option value="深圳">深圳</option>
</select>
</td>
</tr>
<tr>
<td>自我描述</td>
<td>
<textarea cols="40" rows="10" name="description"></textarea>
</td>
</tr>
<tr>
<td>输入验证码</td>
<td>
<input type="text" name="checkImg" />
<img style="cursor: pointer;" alt="" src="${root }/img" id="img" οnclick="_changImg();"/>
<a href="javascript:void(0);" οnclick="_changImg();" style="text-decoration:none"><font color="#B3CDDB">看不清,换一张</font></a>
</td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" value="注册" class="but" οnclick="chaAction(1)"/>
<input type="submit" class="but" value="返回登录" οnclick="chaAction(2)"></td>
</tr>
</table>
</form>
</center>
</body>
</html>
4.登录页面:
<%@ 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">
-->
<style type="text/css">
body{
background: url("2.jpg");
}
div{
height: 200px;
margin-top: 90px;
}
</style>
</head>
<body>
<div align="center" ><marquee><font color="white" size="4"><b>登录成功</b></font></marquee></div>
</body>
</html>
5.用户类:
package com.yynh.domain;
import java.sql.Date;
/**
* @author wjn 与day13数据user表对应的实现类
*/
public class User {
private int id;
private String name;
private String password;
private int age;
private String sex;
private String email;
private String hobby;
private String address;
private String description;
private Date birthday;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getHobby() {
return hobby;
}
public void setHobby(String hobby) {
this.hobby = hobby;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
@Override
public String toString() {
return "User [id=" + id + ", name=" + name + ", password=" + password + ", age=" + age + ", sex=" + sex + ", email=" + email + ", hobby=" + hobby + ", address=" + address + ", description=" + description + ", birthday=" + birthday + "]";
}
}
6.工具类:
package com.yynh.utils;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import com.mchange.v2.c3p0.ComboPooledDataSource;
public class JDBCUtils {
// 创建c3p0开元连接池对象,传入指定配置
static ComboPooledDataSource cpds = new ComboPooledDataSource();
// 释放资源
public static void release(Connection conn, ResultSet rs, Statement stmt) {
try {
// 为了防止rs没有而报异常,进行判断
if (rs != null) {
rs.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
// 如果在判断中出现异常了,就直接将rs赋值null,避免问题
rs = null;
// 如果是select操作,就继续调用其他两个异常
release(conn, stmt);
}
// 释放资源二次优化,通过函数的重写,来区分是否是select操作
public static void release(Connection conn, Statement stmt) {
try {
if (stmt != null) {
stmt.close();
}
} catch (Exception e2) {
}
stmt = null;
try {
if (conn != null) {
conn.close();
}
} catch (Exception e2) {
}
conn = null;
}
public static Connection getCon() throws Exception {
// 通过连接池获得连接
Connection conn = cpds.getConnection();
// 将conn返回
return conn;
}
}
7.配置文件
<?xml version="1.0" encoding="UTF-8"?>
<c3p0-config>
<!-- 默认配置,c3p0框架默认加载这段默认配置 -->
<default-config>
<!-- 配置JDBC 四个基本属性 -->
<property name="driverClass">com.mysql.jdbc.Driver</property>
<property name="jdbcUrl">jdbc:mysql://localhost:3306/day13</property>
<property name="user">root</property>
<property name="password">123</property>
</default-config> <!-- This app is massive! -->
</c3p0-config>
8.验证码:
package com.yynh.web;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
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;
public class ImgServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 图片验证码
// 创建一张画布
// 设定长和宽
int width = 120;
int height = 35;
// imageType 指的是颜色的格式,这里用rgb
BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
// 从画布上获取画笔, getGraphics() graphics
Graphics2D g = bi.createGraphics();
// 填充背景颜色
g.setColor(Color.white);
// 填充范围
g.fillRect(0, 0, width, height);
// 绘制边框
g.setColor(Color.red);
// 填充边框
g.drawRect(0, 0, width - 1, height - 1);
// 生成四个随机数据
// 准备数据 ctrl+shift+x 将选中的文本大写, Ctrl + shift +y 将选中的文本小写
String data = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
// 设置一个随机对象
Random r = new Random();
// 设置一个变量保存验证码
String code = "";
// 循环
for (int i = 1; i < 5; i++) {
// 将画布旋转
// 获取一个随机值,先获取一个范围在-1-1 之间的随机数,再减0.5就能获得一个0-0.5之间的随机数
double theta = (Math.random() - 0.5);
// 旋转一定的角度
g.rotate(theta, 22 * i, height / 2);
// 设置字体,传一个字体对象
g.setFont(new Font("宋体", Font.ITALIC, 27));
// 设置随机颜色 通过color的构造函数来传参数
g.setColor(new Color(r.nextInt(255), r.nextInt(255), r.nextInt(255)));
// 根据字符串的长度随机获得一个下标,然后通过下标得到一个字符,然后变成字符串
String str = data.charAt(r.nextInt(data.length())) + "";
// 将字符写入到画布上,并调整位置
g.drawString(str, i * 22, 30);
// 将画布旋转回来
g.rotate(-theta, 22 * i, height / 2);
// 将每个字符拼接到一起
code += str;
}
// 设置session保存code
request.getSession().setAttribute("checkCode", code);
// 画干扰线
for (int i = 1; i < 7; i++) {
// 设置随机颜色
g.setColor(new Color(r.nextInt(100) + 100, r.nextInt(100) + 100, r.nextInt(100) + 100));
// 将线条画到画布上 两个值确定一个点,两个点确定一条线
g.drawLine(r.nextInt(width), r.nextInt(height), r.nextInt(width), r.nextInt(height));
}
// 将画布输出到浏览器
ImageIO.write(bi, "jpg", response.getOutputStream());
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
9.登录servlet
package com.yynh.web;
import java.io.IOException;
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 com.yynh.domain.User;
import com.yynh.service.ServiceLogin;
import com.yynh.service.ServiceUser;
public class LoginServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 解决乱码问题
response.setContentType("text/html;charset=utf-8");
request.setCharacterEncoding("utf-8");
// 获取保存在本地的验证码
String checkCode = (String) request.getSession().getAttribute("checkCode");
// 打印验证码
System.out.println(checkCode);
// 获取用户输入的验证码
String imgCode = request.getParameter("imgCode");
System.out.println(imgCode);
// 移除本地验证码
request.getSession().removeAttribute("checkCode");
// 第一步:判断验证码是否正确
if (imgCode == null || !imgCode.equalsIgnoreCase(checkCode)) {
// 当验证码没有输入或者和本地验证码不相同的时候,请求转发 转发不需要加项目名
request.setAttribute("errMsg", "验证码有误");
request.getRequestDispatcher("/login.jsp").forward(request, response);
return;
}
// 获取数据
User user = new User();
String name = request.getParameter("name");
String password = request.getParameter("password");
user.setName(name);
user.setPassword(password);
// 调用业务
ServiceUser su = new ServiceLogin();
int i = su.loginUser(user);
if (i == 1) {
// 代表登录成功
Cookie cookie = new Cookie("name", name);
// 设置时间
cookie.setMaxAge(60 * 60 * 24);
// 设置路径
cookie.setPath("/");
response.addCookie(cookie);
String hid = request.getParameter("hid");
System.out.println("woshi" + hid);
if (hid.equals("1")) {
Cookie coo = new Cookie("pwd", password);
// 设置时间
cookie.setMaxAge(60 * 2);
// 设置路径
cookie.setPath("/");
response.addCookie(coo);
}
// 将用户对象保存到session中
request.getSession().setAttribute("user", user);
// 重定向到成功页面
response.sendRedirect(request.getContextPath());
return;
}
if (i == 0) {
// 代表用户名或者秘密错误
request.setAttribute("errMsg", "用户名或者密码有误");
request.getRequestDispatcher("/login.jsp").forward(request, response);
return;
}
if (i == -1) {
// 代表异常
request.setAttribute("errMsg", "服务器忙,稍后再试");
request.getRequestDispatcher("/login.jsp").forward(request, response);
return;
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
10 注册servlet
package com.yynh.web;
import java.io.IOException;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.beanutils.BeanUtils;
import com.yynh.domain.User;
import com.yynh.service.ServiceUser;
import com.yynh.service.ServiceUserCheck;
public class RegisterServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 解决乱码问题
response.setContentType("text/html;charset=utf-8");
request.setCharacterEncoding("utf-8");
// 获取保存在本地的验证码
String checkCode = (String) request.getSession().getAttribute("checkCode");
// 打印验证码
System.out.println(checkCode);
// 获取用户输入的验证码
String checkImg = request.getParameter("checkImg");
System.out.println(checkImg);
// 移除本地验证码
request.getSession().removeAttribute("checkCode");
// 第一步:判断验证码是否正确
if (checkImg == null || !checkImg.equalsIgnoreCase(checkCode)) {
// 当验证码没有输入或者和本地验证码不相同的时候,请求转发 转发不需要加项目名
request.setAttribute("errMsg", "验证码有误");
request.getRequestDispatcher("/register.jsp").forward(request, response);
return;
}
// 封装数据,调用业务层处理业务
User user = new User();
// 获取所有的属性
Map<String, String[]> map = request.getParameterMap();
// 获取javabean
try {
// 将数据封装到javaBean中
BeanUtils.populate(user, map);
} catch (Exception e) {
e.printStackTrace();
}
// 第二步:单独封装爱好
String[] hobby = request.getParameterValues("hobby");
String temp = "";
for (String s : hobby) {
temp = temp + "," + s;
}
// 去除开始的逗号
temp = temp.substring(1);
user.setHobby(temp);
System.out.println(user);
// 第三步:调用service层处理业务
ServiceUser sUser = new ServiceUserCheck();
// 接收返回的值
int i = sUser.register(user);
// 处理返回的值
if (i == 1) {
// 代表注册成功,跳转到成功页面
// 跳转需要项目名
response.sendRedirect(request.getContextPath() + "/welcome.jsp");
return;
} else if (i == 0) {
// 代表注册失败,用户名已存在
// 提示信息
request.setAttribute("errMsg", "用户名已被注册");
request.getRequestDispatcher("/register.jsp").forward(request, response);
return;
} else {
// 代表有异常
request.setAttribute("errMsg", "服务器忙,请稍后再试");
request.getRequestDispatcher("/register.jsp").forward(request, response);
return;
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 调用doGet方法
doGet(request, response);
}
}
11. 登录service
package com.yynh.service;
import com.yynh.dao.UserDao;
import com.yynh.dao.UserDaoReg;
import com.yynh.domain.User;
public class ServiceLogin implements ServiceUser {
@Override
public int register(User user) {
// TODO Auto-generated method stub
return 0;
}
@Override
public int loginUser(User user) {
UserDao ud = new UserDaoReg();
int i = ud.login(user);
if (i == 1) {
// 代表登录成功
return 1;
} else {
return i;
}
}
}
12.注册service
package com.yynh.service;
import com.yynh.dao.UserDao;
import com.yynh.dao.UserDaoReg;
import com.yynh.domain.User;
/**
* @author yynh_
* @注册业务
*/
public class ServiceUserCheck implements ServiceUser {
public int register(User user) {
UserDao ud = new UserDaoReg();
// 判断用户名是否已经注册
int i = ud.findUser(user.getName());
if (i == 1) {
// 代表可以注册用户
// 加密密码 加密后暂时还没有办法登录
// String pwd = MD5Utils.getPwd(user.getPassword());
// 将加密后的结果存入user中
// user.setPassword(pwd);
// 注册成功
return ud.registerUser(user);
} else {
// 代表用户名已经存在或者存在异常
return i;
}
}
public int loginUser(User user) {
return 0;
}
}
13. dao层
package com.yynh.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import com.yynh.domain.User;
import com.yynh.utils.JDBCUtils;
public class UserDaoReg implements UserDao {
// 用户登录
public int login(User user) {
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
try {
// 获取连接
conn = JDBCUtils.getCon();
String sql = "select * from user where name=? and password=?";
// 获取发送sql对象
stmt = conn.prepareStatement(sql);
// 设置属性
stmt.setString(1, user.getName());
stmt.setString(2, user.getPassword());
// 发送sql,接受返回值
rs = stmt.executeQuery();
if (rs.next()) {
// 代表密码用户名正确,可以登录
return 1;
} else {
// 代表不正确
return 0;
}
} catch (Exception e) {
e.printStackTrace();
return -1;
} finally {
JDBCUtils.release(conn, rs, stmt);
}
}
// 注册用户
public int registerUser(User user) {
Connection conn = null;
PreparedStatement stmt = null;
try {
// 获取连接
conn = JDBCUtils.getCon();
String sql = "insert into user values(null,?,?,?,?,?,?,?,?,?)";
// 获取发送sql对象
stmt = conn.prepareStatement(sql);
// 设置属性
stmt.setString(1, user.getName());
stmt.setString(2, user.getPassword());
stmt.setInt(3, user.getAge());
stmt.setString(4, user.getSex());
stmt.setString(5, user.getEmail());
stmt.setString(6, user.getHobby());
stmt.setString(7, user.getAddress());
stmt.setString(8, user.getDescription());
stmt.setDate(9, user.getBirthday());
stmt.executeUpdate();
return 1;
} catch (Exception e) {
e.printStackTrace();
return -1;
}
}
// 查询用户名是否存在
public int findUser(String name) {
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
try {
// 获取连接
conn = JDBCUtils.getCon();
String sql = "select * from user where name=?";
// 获取发送sql对象
stmt = conn.prepareStatement(sql);
// 设置属性
stmt.setString(1, name);
// 发送sql,接受返回值
rs = stmt.executeQuery();
if (rs.next()) {
// 代表有重复的用户名了
return 0;
} else {
// 代表没有重复的可以注册
return 1;
}
} catch (Exception e) {
e.printStackTrace();
return -1;
} finally {
JDBCUtils.release(conn, rs, stmt);
}
}
}
效果: