服务器:tomact8.5 工具:Eclipse
登录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>登录界面</title>
<link rel="stylesheet" type="text/css" href="css/login.css"/>
</head>
<body>
<form action="/my_project/login_servlet" class="login-form" method="post">
<h1>登录</h1>
<div class="textb">
<input id="username" type="text" placeholder="请输入用户名" style="font-weight: bold" name="username">
</div>
<div class="textb">
<input id="password" type="password" placeholder="请输入密码" style="font-weight: bold" name="password">
</div>
<div class="textb">
<input type="text" name="checkcode" id="check_codes" placeholder="请输入验证码" style="font-weight: bold" size="4">
<a href="javascript:reloadcheckimg()" title="看不清,换一张"><img src="img.jsp"/></a>
</div>
<input type="submit" class="logbtn" value="登录"/>
<div class="bottom-text">
没有注册? <a href="register.jsp">注册</a>
</div>
<script type="text/javascript" src="js/jquery-3.4.1.min.js">
</script>
<script type="text/javascript">
function reloadcheckimg(){
$("img").attr("src","img.jsp?t="+Math.random());
//"?"为参数,重新发送请求,加载验证码,
}
$(document).ready(function(){
$("#check_codes").blur(function(){
//校验:文本框输入的值发送到服务器
//服务端 :获取文本框输入的值和真实验证码图片的值对比,并返回验证结果
var $checkcode=$("#check_codes".val());
});
});
</script>
</form>
<script type="text/javascript">
//动态创建和删除div
$(".txtb input").on("focus",function(){
$(this).addClass("focus");
});
$(".txtb input").on("blur",function(){
if($(this).val()=='')
$(this).removeClass("focus");
});
</script>
</body>
</html>
注册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>注册页面</title>
<link rel="stylesheet" type="text/css" href="css/register.css"/>
<link rel="stylesheet" type="text/css" href="css/bootstrap.min.css">
</head>
<body>
<img src="img/ps9.jpg">
<form action="/my_project/Register_servlet" id="reg_form" method="post">
<h1>注册</h1>
<div class="txtb">
<input id="username" type="text" placeholder="请输入用户名" name="username">
</div>
<div class="txtb">
<input id="pwd" type="password" placeholder="请输入密码" name="password">
</div>
<div class="txtb">
<input id="pwd2" type="password" placeholder="请再次确认密码" name="password">
</div>
<div class="txtb">
<input type="text" placeholder="请输电话" name="phone">
</div>
<div class="submit_btn">
<button class="btn btn-success" onclick="checkDate(this)">注册</button>
<button class="btn btn-info" type="reset">重置</button>
<!-- <input type="button" value="注册" style="width=20px;height=10;" onclick="checkDate(this)"/>
<input type="reset" value="重置"/>
-->
</div>
<div class="bottom-text">
已经注册? <a href="Login.jsp">登录</a>
</div>
<script type="text/javascript">
function checkDate(){
//1获取用户名,密码,确认密码;
var username=document.getElementById("username");
var pwd=document.getElementById("pwd");
var pwd2=document.getElementById("pwd2");
if(username.value==""){
alert("请输入用户名");
return;
}
if(pwd.value==""){
alert("请输入密码");
return;
}
if(pwd2.value==""){
alert("请再次输入密码");
return;
}
//两次的密码是否一样
if(pwd.value==pwd2.value){
//发送请求form ,获取form;
var form=document.getElementById("reg_form");
form.submit();//通过js执行表单
}else{
alert("两次输入密码不一样");
}
}
</script>
</form>
</body>
</html>
验证码jsp页面:img.jsp
<%@ page import="java.awt.*" %>
<%@ page import="java.awt.image.BufferedImage"%>
<%@ page import="javax.imageio.*"%>
<%@ page import="java.util.Random" %>
<%@ page language="java" contentType="image/jpeg; charset=UTF-8"
pageEncoding="UTF-8"%>
<%!
//随机产生颜色
public Color getColor(){
Random ran=new Random(); //Math.random() 0-1
int r=ran.nextInt(256);
int g=ran.nextInt(256);
int b=ran.nextInt(256);
return new Color(r,g,b);//red green blue 0-255
}
//产生验证码值
public String getNum(){
//Math.random() 0-1 ,0-8999, 1000-9999
int ran=(int)(Math.random()*9000)+1000;
return String.valueOf(ran);
}
%>
<%
//禁止验证码缓存,防止验证码过期
response.setHeader("pragma", "no-cache");
response.setHeader("Cache-Control", "no-cache");
response.setHeader("Expires","0"); //过期时间:0s
//绘制验证码
BufferedImage image=new BufferedImage(80,30,BufferedImage.TYPE_INT_RGB);
//画笔
Graphics graphics=image.getGraphics();
graphics.fillRect(0, 0, 80, 30);
//绘制干扰线
for(int i=0;i<60;i++)
{
Random ran=new Random();
int xBegin=ran.nextInt(80);
int yBegin=ran.nextInt(30);
int xEnd=ran.nextInt(xBegin+10);
int yEnd=ran.nextInt(yBegin+10);
//设置画笔颜色
graphics.setColor(getColor());
//绘制线条
graphics.drawLine(xBegin, yBegin, xEnd, yEnd);
}
//设置字体
graphics.setFont(new Font("seif",Font.BOLD,20));
//绘制验证码
graphics.setColor(Color.black);
String checkCode=getNum();//2 1 3 4
StringBuffer s=new StringBuffer();//拼接
//将每个数字提出来
for(int i=0;i<checkCode.length();i++){
s.append(checkCode.charAt(i)+" ");//验证码的每一位数字
}
graphics.drawString(s.toString(), 15, 20);//绘制验证码的位置
//将验证码真实值保存在session中,使用时比较真实性
session.setAttribute("CKECKCODE",checkCode);
//真实产生的图片
ImageIO.write(image,"jpeg",response.getOutputStream());
//关闭
out.clear();
out=pageContext.pushBody();//<input type="image" src="xxx"/>
%>
User
package com.it.domain;
public class User {
private String id;
private String username;
private String password;
private String phone;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String toString() {
return "User [id="+id+",username="+username+",password="+password+",phone="+phone+"]";
}
}
JDButil
package com.it.jdbc.util;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import com.alibaba.druid.pool.DruidDataSource;
public class JDBCUtil {
//通过连接池连接数据
//在使用mysql 数据库的时候如果需要批量添加,修改,删除功能则要设置rewriteBatchedStatements参数,这样才能真正起到批量添加的功能
public static String url="jdbc:mysql://localhost:3306/user?rewriteBatchedStatements=true";
public static String user="root";
public static String pwd="密码";
public static String driverName="com.mysql.jdbc.Driver";
public static DruidDataSource ds=null;//Druid连接池
//static方法只有类被加载到jvm时,才会执行一次,在连接池中对象直接调用方法
static {
ds=new DruidDataSource();//Druid连接池
ds.setDriverClassName(driverName);
ds.setUsername(user);
ds.setPassword(pwd);
ds.setUrl(url);
}
//设置成静态,别人可以通过类名直接调用,连接数据库
public static Connection getConn(){
try {
//2.连接数据库
return ds.getConnection();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
//关闭资源
public static void close(Connection conn,Statement st,ResultSet rs) {
if(rs!=null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(conn!=null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(st!=null) {
try {
st.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
登录servlet
package com.it.servlet;
import java.io.IOException;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import com.it.domain.User;
import com.it.jdbc.util.JDBCUtil;
/**
* Servlet implementation class login_servlet
*/
@WebServlet("/login_servlet")
public class login_servlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#service(HttpServletRequest request, HttpServletResponse response)
*/
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//设置请求编码;
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
//获取用户验证码
String checkcodeClient=request.getParameter("checkcode");
//真实验证码值
String CheckCodeServlet=(String)request.getSession().getAttribute("CKECKCODE");
//获取用户名,密码
String name=request.getParameter("username");
String pwd=request.getParameter("password");
System.out.print(name+pwd);
//到数据库当中查询有没有该用户,
// DbUtils类:启动类
//ResultSetHandler接口:转换类型接口
//
//MapListHandler类:实现类,把记录转化成List
//
//BeanListHandler类:实现类,把记录转化成List,使记录为JavaBean类型的对象
//
//Query Runner类:执行SQL语句的类
QueryRunner qr=new QueryRunner(JDBCUtil.ds);//使用DbUtils
String sql="select * from user where username=? and password=?";
User u=null;
try {
u = qr.query(sql, new BeanHandler<User>(User.class),name,pwd);//BeanHandler将查到的东西封装成对象
} catch (SQLException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
//1.有值
if(u!=null&&(CheckCodeServlet.equals(checkcodeClient))) {
response.getWriter().write("登录成功");
//跳转到登录;
response.setHeader("refresh","3;url=/my_project"+ "/list.jsp");//刷新页面,3秒后跳转
//request.getRequestDispatcher("/register.jsp").forward(request,response);
}
else {
response.getWriter().write("登录失败,用户名错误或者密码错误,验证码错误");
跳转到登录;http
response.setHeader("refresh","3;url=/my_project"+"/Login.jsp");刷新页面,3秒后跳转
//request.getRequestDispatcher("/Login.jsp").forward(request,response);
}
}
}
注册servlet
package com.it.servlet;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.sql.SQLException;
import java.util.Map;
import java.util.UUID;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.dbutils.QueryRunner;
import com.it.domain.User;
import com.it.jdbc.util.JDBCUtil;
/**
* Servlet implementation class Register_servlet
*/
@WebServlet("/Register_servlet")
public class Register_servlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#service(HttpServletRequest request, HttpServletResponse response)
*/
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//设置请求编码
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
//1.接收所有参数
Map<String,String[]> parameterMap=request.getParameterMap();
User u=new User();
try {
BeanUtils.populate(u,parameterMap);//这个方法会遍历map<key, value>中的key,如果bean中有这个属性,就把这个key对应的value值赋给bean的属性。
} catch (IllegalAccessException | InvocationTargetException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
//随机设置id;
u.setId(UUID.randomUUID().toString());
//写入数据库
QueryRunner qr=new QueryRunner(JDBCUtil.ds);
String sql="insert into user value(?,?,?,?)";
try {
qr.update(sql,u.getId(),u.getUsername(),u.getPassword(),u.getPhone());
//:增删改都可用Query对象的update方法。
} catch (SQLException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
response.getWriter().write("注册成功");
request.getRequestDispatcher("/Login.jsp").forward(request,response);
}
}
login.css
@charset "UTF-8";
*{
margin: 0;
padding: 0;
text-decoration: none;
font-family: montserrat;
box-sizing: border-box;
}
body{
min-height: 100vh;
background:url(../img/8.jpg);
}
.login-form{
width: 360px;
background:url(../img/9.jpg);
height: 580px;
padding: 80px 40px;
border-radius: 10px;
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%,-50%);
}
.login-form h1{
text-align: center;
margin-bottom: 60px;
}
.textb{
border-bottom: 2px solid#adadad;
position: relative;
margin: 30px 0;
}
.textb input{
font-size: 15px;
color: #333;
border:none;
width: 100%;
outline: none;
background: none;
padding: 0 5px;
height: 40px;
}
.textb span::before{
content: attr(data-placeholder);
position: absolute;
top: 50%;
left: 5px;
color: #adadad;
transform: translateY(-50%);
z-index: -1;
transition: .5s;
}
.textb span::after{
content: '';
position: absolute;
width: 0%;
height: 2px;
background:linear-gradient(#72bdb8,#33cccc,#8e44ad);
transition: .5s;
}
.focus + span::before{
top: -5px;
}
.focus + span::after{
width: 100%;
}
.logbtn{
display: block;
width: 100%;
height: 50px;
border: none;
background:linear-gradient(#33cccc,#3ebbb8,#72bdb8,#33cccc);
background-size:200%;
color: #fff;
outline: none;
cursor: pointer;
transition: .5s;
}
.logbtn:hover{
background-position: right;
}
.bottom-text{
margin-top: 60px;
text-align: center;
font-size: 13px;
}
register.css
@charset "UTF-8";
*{
margin: 0;
padding: 0;
text-decoration: none;
font-family: montserrat;
box-sizing: border-box;
}
body{
min-height: 100vh;
}
#reg_form{
width: 360px;
background:url(../img/ps11.jpg);
height: 580px;
padding: 80px 40px;
border-radius: 10px;
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%,-50%);
}
#reg_form h1{
text-align: center;
margin-bottom: 60px;
}
txtb{
border-bottom: 2px solid#adadad;
position: relative;
margin: 30px 0;
}
.txtb input{
font-size: 15px;
color: #333;
border:none;
width: 100%;
outline: none;
background: none;
padding: 0 5px;
height: 70px;
}
.logbtn:hover{
background-position: right;
}
.bottom-text{
margin-top: 60px;
text-align: center;
font-size: 13px;
}