项目的整体布局
用到的库(有些不一定用到,写者懒得删了,按需加入)
连接数据库:DBUtil.java
package com.DBUtil.java;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class DBUtil {
//数据库URL和账号密码
public static final String connectionURL="jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=GMT&allowPublicKeyRetrieval=true";
public static final String username="root";
public static final String password="123456";
//数据库连接
public static Connection getConnection()
{
try {
Class.forName("com.mysql.cj.jdbc.Driver");
//Class.forName("com.mysql.cj.jdbc.Driver");
return DriverManager.getConnection(connectionURL, username, password);
} catch (Exception e) {
// TODO: handle exception
System.out.println("数据库连接失败");
e.printStackTrace();
}
return null;
}
public static boolean Signin(String username,String password,String name,String sex,String province,String mobile,String email)
{
Connection con=null;
PreparedStatement pstmt=null;
try {
con=getConnection();
String sql="insert into signin_users (username,password,name,sex,province,mobile,email) values (\'"+
username+"\',\'"+password+"\',\'"+name+"\',\'"+sex+"\',\'"+province+"\',\'"+mobile+"\',\'"+email+"\')";
//System.out.println(sql);
pstmt=con.prepareStatement(sql);
pstmt.executeUpdate();
return true;
}
catch(SQLException e)
{
e.printStackTrace();
}
return false;
}
public static boolean getUsername(String username)
{
Connection connection=null;
PreparedStatement preparedStatement=null;
ResultSet rSet=null;
try {
connection=getConnection();
String sql="select * from signin_users where username="+"\'"+username+"\'";
//System.out.println(sql);
preparedStatement=connection.prepareStatement(sql);
rSet=preparedStatement.executeQuery();
if(rSet.next())
return true;
else
return false;
}
catch(SQLException e)
{
e.printStackTrace();
}
return false;
}
public static boolean getMobile(String mobile)
{
Connection connection=null;
PreparedStatement preparedStatement=null;
ResultSet rSet=null;
try {
connection=getConnection();
String sql="select * from signin_users where mobile="+"\'"+mobile+"\'";
//System.out.println(sql);
preparedStatement=connection.prepareStatement(sql);
rSet=preparedStatement.executeQuery();
if(rSet.next())
return true;
else
return false;
}
catch(SQLException e)
{
e.printStackTrace();
}
return false;
}
public static boolean getEmail(String email)
{
Connection connection=null;
PreparedStatement preparedStatement=null;
ResultSet rSet=null;
try {
connection=getConnection();
String sql="select * from signin_users where email="+"\'"+email+"\'";
//System.out.println(sql);
preparedStatement=connection.prepareStatement(sql);
rSet=preparedStatement.executeQuery();
if(rSet.next())
return true;
else
return false;
}
catch(SQLException e)
{
e.printStackTrace();
}
return false;
}
public static boolean getId(String id)
{
Connection connection=null;
PreparedStatement preparedStatement=null;
ResultSet rSet=null;
try {
connection=getConnection();
String sql="select * from signin_users where id="+"\'"+id+"\'";
//System.out.println(sql);
preparedStatement=connection.prepareStatement(sql);
rSet=preparedStatement.executeQuery();
if(rSet.next())
return true;
else
return false;
}
catch(SQLException e)
{
e.printStackTrace();
}
return false;
}
public static boolean addInformation(String username,String password,String sex,String name,String id,String email,String agency,String major,String classnum,String year,String birthplace,String text)
{
Connection con=null;
PreparedStatement pstmt=null;
try {
con=getConnection();
String sql="insert into signin_users (username,password,sex,name,id,email,agency,major,classnum,year,birthplace,text) values (\'"+
username+"\',\'"+password+"\',\'"+sex+"\',\'"+name+"\',\'"+id+"\',\'"+email+"\',\'"+agency+"\',\'"+major+"\',\'"+classnum+"\',\'"+year+"\',\'"+birthplace+"\',\'"+text+"\')";
//System.out.println(sql);
pstmt=con.prepareStatement(sql);
pstmt.executeUpdate();
return true;
}
catch(SQLException e)
{
e.printStackTrace();
}
return false;
}
public static boolean addInformation2(String username,String password)
{
Connection con=null;
PreparedStatement pstmt=null;
try {
con=getConnection();
String sql="insert into signin_admin (username,password) values (\'"+
username+"\',\'"+password+"\')";
//System.out.println(sql);
pstmt=con.prepareStatement(sql);
pstmt.executeUpdate();
return true;
}
catch(SQLException e)
{
e.printStackTrace();
}
return false;
}
/*public static void main(String[] args) {
addInformation("1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1");
}*/
}
Servlet的操作:
Signin_do
package com.manage.servlet;
import java.io.IOException;
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 com.DBUtil.java.DBUtil;
/**
* Servlet implementation class Signin_do
*/
@WebServlet("/Signin_do")
public class Signin_do extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
request.setCharacterEncoding("UTF-8");
String username=request.getParameter("username");
String password=request.getParameter("password");
String sex=request.getParameter("sex");
String name=request.getParameter("name");
String id=request.getParameter("id");
String email=request.getParameter("email");
String agency=request.getParameter("agency");
String major=request.getParameter("major");
String classnum=request.getParameter("classnum");
String year=request.getParameter("year");
String birthplace=request.getParameter("birthplace");
String text=request.getParameter("text");
if(DBUtil.addInformation(username,password,sex,name,id,email,agency,major,classnum,year,birthplace,text))
response.sendRedirect("register.jsp?result=true");
else
response.sendRedirect("register.jsp?result=false");
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
判断用户是否唯一:UserServlet
package com.manage.servlet;
import java.io.IOException;
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 com.DBUtil.java.DBUtil;
/**
* Servlet implementation class UserServlet
*/
@WebServlet("/UserServlet")
public class UserServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String username=request.getParameter("username");
//System.out.println(username);
//DBUtil.getUsername(username);
if(DBUtil.getUsername(username))
response.getWriter().write("no");
else
response.getWriter().write("yes");
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
判断Id是否存在:IdServlet
package com.manage.servlet;
import java.io.IOException;
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 com.DBUtil.java.DBUtil;
/**
* Servlet implementation class IdServlet
*/
@WebServlet("/IdServlet")
public class IdServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String id=request.getParameter("id");
if(DBUtil.getId(id))
response.getWriter().write("no");
else
response.getWriter().write("yes");
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
判断Email是否存在:EmailServlet
package com.manage.servlet;
import java.io.IOException;
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 com.DBUtil.java.DBUtil;
/**
* Servlet implementation class EmailServlet
*/
@WebServlet("/EmailServlet")
public class EmailServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String email=request.getParameter("email");
if(DBUtil.getEmail(email))
response.getWriter().write("no");
else
response.getWriter().write("yes");
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
验证码的操作:PictureCheckCode
package com.manage.servlet;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.AffineTransform;
import java.awt.geom.Line2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;
import javax.imageio.ImageIO;
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 javax.servlet.http.HttpSession;
/**
* Servlet implementation class PictureCheckCode
*/
@WebServlet("/PictureCheckCode")
public class PictureCheckCode extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public PictureCheckCode() {
super();
// TODO Auto-generated constructor stub
}
public void destroy() {
super.destroy();
}
public void init() throws ServletException {
super.init();
}
/*该方法主要作用是获得随机生成的颜色*/
public Color getRandColor(int s,int e){
Random random=new Random ();
if(s>255) s=255;
if(e>255) e=255;
int r,g,b;
r=s+random.nextInt(e-s); //随机生成RGB颜色中的r值
g=s+random.nextInt(e-s); //随机生成RGB颜色中的g值
b=s+random.nextInt(e-s); //随机生成RGB颜色中的b值
return new Color(r,g,b);
}
@Override
public void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//设置不缓存图片
response.setHeader("Pragma", "No-cache");
response.setHeader("Cache-Control", "No-cache");
response.setDateHeader("Expires", 0);
//指定生成的响应图片,一定不能缺少这句话,否则错误.
response.setContentType("image/jpeg");
int width=86,height=28; //指定生成验证码的宽度和高度
BufferedImage image=new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB); //创建BufferedImage对象,其作用相当于一图片
Graphics g=image.getGraphics(); //创建Graphics对象,其作用相当于画笔
Graphics2D g2d=(Graphics2D)g; //创建Grapchics2D对象
Random random=new Random();
g.setColor(getRandColor(200,250));
g.fillRect(0, 0, width, height); //绘制背景
//g.setFont(mfont); //设置字体
g.setColor(getRandColor(180,200));
//绘制100条颜色和位置全部为随机产生的线条,该线条为2f
for(int i=0;i<100;i++){
int x=random.nextInt(width-1);
int y=random.nextInt(height-1);
int x1=random.nextInt(6)+1;
int y1=random.nextInt(12)+1;
BasicStroke bs=new BasicStroke(2f,BasicStroke.CAP_BUTT,BasicStroke.JOIN_BEVEL); //定制线条样式
Line2D line=new Line2D.Double(x,y,x+x1,y+y1);
g2d.setStroke(bs);
g2d.draw(line); //绘制直线
}
//输出由英文,数字随机组成的验证文字,具体的组合方式根据生成随机数确定。
String sRand="";
String ctmp="";
int itmp=0;
//制定输出的验证码为四位
for(int i=0;i<4;i++){
switch(random.nextInt(3)){
case 1: //生成A-Z的字母
itmp=random.nextInt(26)+65;
ctmp=String.valueOf((char)itmp);
break;
default:
itmp=random.nextInt(10)+48;
ctmp=String.valueOf((char)itmp);
break;
}
sRand+=ctmp;
Color color=new Color(20+random.nextInt(110),20+random.nextInt(110),random.nextInt(110));
g.setColor(color);
//将生成的随机数进行随机缩放并旋转制定角度 PS.建议不要对文字进行缩放与旋转,因为这样图片可能不正常显示
/*将文字旋转制定角度*/
Graphics2D g2d_word=(Graphics2D)g;
AffineTransform trans=new AffineTransform();
trans.rotate((45)*3.14/180,15*i+8,7);
g2d_word.setTransform(trans);
g.drawString(ctmp, 15*i+18, 14);
}
HttpSession session=request.getSession(true);
session.setAttribute("randCheckCode", sRand);
g.dispose(); //释放g所占用的系统资源
ImageIO.write(image,"JPEG",response.getOutputStream()); //输出图片
}
}
管理员的操作:Signin_admin
package com.manage.servlet;
import java.io.IOException;
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 com.DBUtil.java.DBUtil;
/**
* Servlet implementation class Signin_do
*/
@WebServlet("/Signin_admin")
public class Signin_admin extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
request.setCharacterEncoding("UTF-8");
String username=request.getParameter("username");
String password=request.getParameter("password");
if(DBUtil.addInformation2(username,password))
response.sendRedirect("admin_register.jsp?result=true");
else
response.sendRedirect("admin_register.jsp?result=false");
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
管理员的操作:ContactServlet
分别对应增、改、删处理页面的请求
package com.manage.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
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 javax.servlet.http.HttpSession;
import com.DatebaseO.Contact;
import com.DatebaseO.ContactService;
/**
* Servlet implementation class ContactServlet
*/
@WebServlet("/ContactServlet")
public class ContactServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public ContactServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request,response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
request.setCharacterEncoding("utf-8");
HttpSession session = request.getSession();
PrintWriter out = response.getWriter();
ContactService ud = new ContactService();
// 获得do属性
String dos = request.getParameter("do");
if (dos == null || dos.equals("")) {
dos = "inde";
}
// 主页
if (dos.equals("inde")) {
List<Contact> ulist = ud.GetAllContact();
request.setAttribute("ulist", ulist);
request.getRequestDispatcher("/inde.jsp").forward(request, response);
return;
}
if(dos.equals("add")) {
String username=request.getParameter("username");
String password=request.getParameter("password");
String sex=request.getParameter("sex");
String name=request.getParameter("name");
String id=request.getParameter("id");
String email=request.getParameter("email");
String agency=request.getParameter("agency");
String major=request.getParameter("major");
String classnum=request.getParameter("classnum");
String year=request.getParameter("year");
String birthplace=request.getParameter("birthplace");
String text=request.getParameter("text");
Contact contact = new Contact(username,password,sex,name,id,email,agency,major,classnum,year,birthplace,text);
ud.AddContact(contact);
out.print("<script>alert('新增成功!');window.location='ContactServlet?do=inde';</script>");
}
if(dos.equals("del")) {
String id = request.getParameter("id");
//String id = Integer.parseInt(id);
ud.DeleteContact(id);
out.print("<script>alert('删除成功!');window.location='ContactServlet?do=inde';</script>");
}
if(dos.equals("editbefore")) {
//int id = Integer.parseInt(request.getParameter("id"));
String id=request.getParameter("id");
Contact f = ud.GetContact(id);
session.setAttribute("edituser", f);
response.sendRedirect("edit.jsp");
return;
}
if(dos.equals("edit")) {
String username=request.getParameter("username");
String password=request.getParameter("password");
String sex=request.getParameter("sex");
String name=request.getParameter("name");
String id=request.getParameter("id");
String email=request.getParameter("email");
String agency=request.getParameter("agency");
String major=request.getParameter("major");
String classnum=request.getParameter("classnum");
String year=request.getParameter("year");
String birthplace=request.getParameter("birthplace");
String text=request.getParameter("text");
Contact contact = new Contact(username,password,sex,name,id,email,agency,major,classnum,year,birthplace,text);
ud.UpdateContact(contact);
out.print("<script>alert('修改成功!');window.location='ContactServlet?do=inde';</script>");
}
}
}
对数据库的操作:
数据库的连接:BaseDao
package com.DatebaseO;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class BaseDao {
private static final String DRIVER = "com.mysql.cj.jdbc.Driver";
public static final String URL = "jdbc:mysql://localhost:3306/test?rewriteBatchedStatements=true&useUnicode=true&characterEncoding=utf8&allowMultiQueries=true&serverTimezone=GMT%2B8";
public static final String USER = "root";
public static final String PASSWORD = "123456";
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
public void getConnection() {
try {
// 加载数据库驱动
Class.forName(DRIVER);
// 获得数据库连接
conn = DriverManager.getConnection(URL, USER, PASSWORD);
}
catch (ClassNotFoundException e) {
e.printStackTrace();
}
catch (SQLException e) {
e.printStackTrace();
}
}
public int executeUpdate(String sql, Object... obj) {
int num = 0;
getConnection();
try {
PreparedStatement pstmt = conn.prepareStatement(sql);
for (int i = 0; i < obj.length; i++) {
pstmt.setObject(i + 1, obj[i]);
}
num = pstmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
} finally {
closeAll();
}
return num;
}
public ResultSet executeQuery(String sql, Object... obj) {
getConnection();
try {
PreparedStatement pstmt = conn.prepareStatement(sql);
for (int i = 0; i < obj.length; i++) {
pstmt.setObject(i + 1, obj[i]);
}
rs = pstmt.executeQuery();
} catch (SQLException e) {
e.printStackTrace();
}
return rs;
}
public void closeAll() {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
try {
pstmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
对应的属性及函数:Contact
package com.DatebaseO;
public class Contact {
public Contact(String username,String password,String sex,String name,String id,String email,String agency,String major,String classnum,String year,String birthplace,String text) {
super();
this.username=username;
this.password=password;
this.sex=sex;
this.name=name;
this.id=id;
this.email=email;
this.agency=agency;
this.major=major;
this.classnum=classnum;
this.year=year;
this.birthplace=birthplace;
this.text=text;
}
private String username;
private String password;
private String sex;
private String name;
private String id;
private String email;
private String agency;
private String major;
private String classnum;
private String year;
private String birthplace;
private String text;
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 getSex() {
return sex;
}
public void setSex(String sex) {
this.sex=sex;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name=name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id=id;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email=email;
}
public String getAgency() {
return agency;
}
public void setAgency(String agency) {
this.agency= agency;
}
public String getMajor() {
return major;
}
public void setMajor(String major) {
this.major=major;
}
public String getClassnum() {
return classnum;
}
public void setClassnum(String classnum) {
this.classnum=classnum;
}
public String getYear() {
return year;
}
public void setYear(String year) {
this.year=year;
}
public String getBirthplace() {
return birthplace;
}
public void setBirthplace(String birthplace) {
this.birthplace=birthplace;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text=text;
}
}
SQL语句的操作:ContactService
package com.DatebaseO;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class ContactService extends BaseDao{
ResultSet rs = null;
public List<Contact> GetAllContact(){
@SuppressWarnings({ "unchecked", "rawtypes" })
List<Contact> list = new ArrayList();
String sql = "select * from signin_users";
rs = executeQuery(sql);
try {
while (rs.next()) {
Contact f = new Contact(rs.getString(1), rs.getString(2),
rs.getString(3), rs.getString(4), rs.getString(5),
rs.getString(6),rs.getString(7),rs.getString(8),
rs.getString(9),rs.getString(10),rs.getString(11),
rs.getString(12));
list.add(f);
}
} catch (SQLException e) {
e.printStackTrace();
}
return list;
}
public int AddContact(Contact contact)
{
int num = 0;
String sql = "insert into signin_users(username,password,sex,name,id,email,agency,major,classnum,year,birthplace,text) "
+ " values(?,?,?,?,?,?,?,?,?,?,?,?)";
try {
num = executeUpdate(sql, contact.getUsername(), contact.getPassword(), contact.getSex(),
contact.getName(), contact.getId(),contact.getEmail(),contact.getAgency(),
contact.getMajor(),contact.getClassnum(),contact.getYear(),contact.getBirthplace(),contact.getText());
} catch (Exception e) {
e.printStackTrace();
}
return num;
}
public int DeleteContact(String id)
{
int num = 0;
String sql = "delete from signin_users where id = ?";
try {
num = executeUpdate(sql, id);
}
catch(Exception ex) {
ex.printStackTrace();
}
return num;
}
public Contact GetContact(String id) {
String sql = "select * from signin_users where id = ?";
Contact contact = null;
rs = executeQuery(sql, id);
try {
while(rs.next()) {
contact = new Contact(rs.getString(1), rs.getString(2),
rs.getString(3), rs.getString(4), rs.getString(5),
rs.getString(6),rs.getString(7),rs.getString(8),
rs.getString(9),rs.getString(10),rs.getString(11),
rs.getString(12));
}
}
catch(SQLException ex){
ex.printStackTrace();
}
return contact;
}
public int UpdateContact(Contact contact) {
int num = 0;
String sql = "update signin_users set username = ?,password = ?,sex = ?,name = ?,email = ?,agency = ?,major = ?,classnum = ?,year = ?,birthplace = ?,text = ? where id = ?";
try {
num = executeUpdate(sql, contact.getUsername(), contact.getPassword(), contact.getSex(),
contact.getName(),contact.getEmail(),contact.getAgency(),
contact.getMajor(),contact.getClassnum(),contact.getYear(),contact.getBirthplace(),contact.getText(), contact.getId());
}
catch(Exception ex) {
ex.printStackTrace();
}
return num;
}
}
页面jsp:
首页:index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>首页</title>
<style>
h2{
border-bottom:5px solid pink;
padding-bottom:10px;
text-align:center;
width:100%;
}
</style>
</head>
<body>
<div id="container" style="width:100%;">
<div id="header" style="background-color:#FFA500;">
<h2 style="margin-bottom:0;">学生信息管理首页</h2></div>
<div id="menu" style="background-color:#FFD700;height:30px;width:100%;text-align:right;">
<a href="Login.jsp">学生登录</a>
<a href="register.jsp">学生注册</a>
</div>
<div id="menu" style="background-color:#FFD700;height:30px;width:100%;text-align:right;">
<a href="admin_login.jsp">管理员登录</a>
<a href="admin_register.jsp">管理员注册</a>
</div>
<div id="content" style="background-image:url(index.gif);height:375px;width:100%;">
</div>
<div id="footer" style="background-color:#FFA500;clear:both;text-align:center;">
版权 © Luomeng.com</div>
</div>
</body>
</html>
用户注册页面:register.jsp
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<!DOCTYPE html>
<html>
<head>
<title>用户注册</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/4.3.1/css/bootstrap.min.css">
<script src="https://cdn.staticfile.org/jquery/3.2.1/jquery.min.js"></script>
<style>
body{
background-image:url(bt.gif);
}
.container{
margin-top:100px;
border-radius:10px;
padding-top:50px;
padding-bottom:50px;
align:center;
background-color:white;
opacity:0.8;
width:500px;
}
form{
margin-top:20px;
}
.form-group{
align:center;
width:350px;
margin:auto;
position:relative;
}
h2{
border-bottom:5px solid red;
padding-bottom:10px;
text-align:center;
width:100%;
}
.label{
float:left;
width:80px;
margin-top:7px;
margin-right:5px;
text-align:left;
}
.form-control{
width:200px;
margin-top:7px;
}
.sex{
border:0px solid #000;
width:200px;
margin-top:7px;
}
.sign{
width:160px;
margin-top:10px;
}
.tip{
position:relative;
width:100%;
height:auto;
padding:5px;
}
.tip .tipicon{
float:left;
background-image:url(D:/Desktop/bt.gif);
background-repeat:no-repeat;
background-position:center;
background-size:cover;
width:20px;
height:20px;
}
.tipmessage{
color:red;
font-size:15px;
}
.tip{
display:none;
}
.righttip{
display:none;
position:absolute;
right:8px;
top:8px;
width:25px;
height:25px;
background-image:url(D:/Desktop/bt.gif);
background-repeat:no-repeat;
background-position:center;
background-size:cover;
}
</style>
<script type="text/javascript">
function isMobileNumber(phone) {
var flag = false;
var message = "";
var myreg = /^(((13[0-9]{1})|(14[0-9]{1})|(17[0-9]{1})|(15[0-3]{1})|(15[4-9]{1})|(18[0-9]{1})|(199))+\d{8})$/;
if (myreg.test(phone)){
flag = true;
}
return flag;
}
function GetQueryString(name) {
var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
var r = window.location.search.substr(1).match(reg); //获取url中"?"符后的字符串并正则匹配
var context = "";
if (r != null)
context = r[2];
reg = null;
r = null;
return context == null || context == "" || context == "undefined" ? "" : context;
}
function isEmail(email){
//对电子邮件的验证
var myreg = /^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/;
if(!myreg.test(email)){
return false;
}
else
return true;
}
function isPwd(password)
{
var myreg=/[0-9a-zA-Z]+/;
if(!myreg.test(password))
return false;
else
return true;
}
function isId(id)
{
if((id[0]=="2")&&(id[1]=="0")&&(id[2]=="1")&&(id[3]=="8"))
return true;
else
return false;
}
function inputusername()
{
var username=$("#usr").val();
var tip1=$("#tip1");
var tip_1=$("#tip_1");
if(!((username[0]>='a'&&username[0]<='z')||(username[0]>='A'&&username[0]<='Z')))
{
$("#usr").next().css("display","none");
tip1.css("display","block");
tip_1.html("用户名必须以英文字母开头!");
}
else if(username.length<6||username.length>12){
$("#usr").next().css("display","none");
tip1.css("display","block");
tip_1.html("用户名必须为6-12位字符!");
}
else
{
tip1.css("display","none");
$.post(
"UserServlet",
{username:username},
function(data){
if(data=="yes"){
tip1.css("display","none");
$("#usr").next().css("display","block");
}
else{
$("#usr").next().css("display","none");
tip1.css("display","block");
tip_1.html("用户名已被注册!");
}
},
"text"
);
}
}
function inputId()
{
var id=$("#id").val();
var tip4=$("#tip4");
var tip_4=$("#tip_4");
if(!isId(id))
{
$("#id").next().css("display","none");
tip4.css("display","block");
tip_4.html("学号必须以2018开头!");
}
else if(id.length!=8){
$("#id").next().css("display","none");
tip4.css("display","block");
tip_4.html("请输入8位学号!");
}
else
{
tip4.css("display","none");
$.post(
"IdServlet",
{id:id},
function(data){
if(data=="yes"){
tip4.css("display","none");
$("#id").next().css("display","block");
}
else{
$("#id").next().css("display","none");
tip4.css("display","block");
tip_4.html("该学号已存在!");
}
},
"text"
);
}
}
function inputpassword()
{
var password=$("#pwd").val();
var tip2=$("#tip2");
var tip_2=$("#tip_2");
if(password.length<6)
{
$("#pwd").next().css("display","none");
tip2.css("display","block");
tip_2.html("请输入6位以上密码!");
}
else if(!isPwd(password)){
$("#pwd").next().css("display","none");
tip2.css("display","block");
tip_2.html("密码仅由英文或数字组成!");
}
else{
tip2.css("display","none");
$("#pwd").next().css("display","block");
}
}
function inputmobile()
{
var mobile=$("#mobile").val();
var tip4=$("#tip4");
var tip_4=$("#tip_4");
if(mobile.length!=11)
{
$("#mobile").next().css("display","none");
tip4.css("display","block");
tip_4.html("请输入11位手机号!");
}
else if(isMobileNumber(mobile)==false){
$("#mobile").next().css("display","none");
tip4.css("display","block");
tip_4.html("手机号格式不正确!");
}
else
{
tip4.css("display","none");
$.post(
"MobileServlet",
{mobile:mobile},
function(data){
if(data=="yes"){
tip4.css("display","none");
$("#mobile").next().css("display","block");
}
else{
$("#usr").next().css("display","none");
tip4.css("display","block");
tip_4.html("手机号已被注册!");
}
},
"text"
);
}
}
function inputemail()
{
var email=$("#email").val();
var tip5=$("#tip5");
var tip_5=$("#tip_5");
if(!isEmail(email))
{
$("#email").next().css("display","none");
tip5.css("display","block");
tip_5.html("邮箱格式不正确!");
}
else
{
tip5.css("display","none");
$.post(
"EmailServlet",
{email:email},
function(data){
if(data=="yes"){
tip5.css("display","none");
$("#email").next().css("display","block");
}
else{
$("#email").next().css("display","none");
tip5.css("display","block");
tip_5.html("邮箱已被注册!");
}
},
"text"
);
}
}
function isEmpty()
{
if($("#usr").val()==""||$("#pwd").val()==""||$("#name").val()==""||$('input[name="sex"]:checked').val()==""||$("#sel1").val()==""||
$("#agency").val()==""||$("#major").val()==""||$("#classnum").val()==""||$("#birthplace").val()==""
||$("#email").val()==""||$("#id").val()==""||$("#text").val()=="")
{
alert("请将信息填写完整!");
return false;
}
return true;
}
function getResult()
{
if(GetQueryString("result")=="true")
alert("添加成功!");
else if(GetQueryString("result")=="false")
alert("添加失败!");
}
var inputs=document.getElementsByTagName("input");
for(var i=0;i<inputs.length;i++)
{
inputs[i].onkeyup=function(event){
if(event.keyCode=13){
var next=this.nextElementSibling.nextElementSibling;
next.focus();
}
}
}
</script>
</head>
<body onload="getResult()">
<div class="container">
<h2>用户注册<a href="Login.jsp">登陆</a></h2>
<form action="Signin_do" method="post">
<div class="form-group">
<label for="usr" class="label">账号:</label>
<input type="text" class="form-control" id="usr" name="username" oninput="inputusername()" placeholder="请输入用户名">
<div class="righttip"></div>
<div class="tip" id="tip1">
<div class="tipicon"></div>
<div id="tip_1" class="tipmessage"></div>
</div>
</div>
<div class="form-group">
<label for="pwd" class="label">密码:</label>
<input type="password" class="form-control" id="pwd" name="password" placeholder="请输入密码" oninput="inputpassword()">
<div class="righttip"></div>
<div class="tip" id="tip2">
<div class="tipicon"></div>
<div id="tip_2" class="tipmessage"></div>
</div>
</div>
<div class="form-group">
<label class="label" for="sex">性别:</label>
<div class="sex form-control" id="sex">
<label class="radio-inline"><input type="radio" name="sex" value="男">男</label>
<label class="radio-inline"><input type="radio" name="sex" value="女">女</label>
</div>
</div>
<div class="form-group">
<label for="name" class="label">姓名:</label>
<input type="text" class="form-control" id="name" name="name" placeholder="请输入姓名">
</div>
<div class="form-group">
<label for="name" class="label">学号:</label>
<input type="text" class="form-control" id="id" name="id" placeholder="请输入学号" oninput="inputId()">
<div class="righttip"></div>
<div class="tip" id="tip4">
<div class="tipicon"></div>
<div id="tip_4" class="tipmessage"></div>
</div>
</div>
<div class="form-group">
<label for="email" class="label">电子邮件:</label>
<input type="text" class="form-control" id="email" name="email" placeholder="请输入邮箱" oninput="inputemail()">
<div class="righttip"></div>
<div class="tip" id="tip5">
<div class="tipicon"></div>
<div id="tip_5" class="tipmessage"></div>
</div>
</div>
<div class="form-group">
<label for="email" class="label">所在学院:</label>
<input type="text" class="form-control" id="agency" name="agency" placeholder="请输入学院" oninput="inputemail()">
</div>
<div class="form-group">
<label for="email" class="label">所在系:</label>
<input type="text" class="form-control" id="major" name="major" placeholder="请输入系" oninput="inputemail()">
</div>
<div class="form-group">
<label for="email" class="label">所在班级:</label>
<input type="text" class="form-control" id="classnum" name="classnum" placeholder="请输入班级" oninput="inputemail()">
</div>
<div class="form-group">
<label for="sel1" class="label">入学年份(届):</label>
<select class="form-control" id="sel1" name="year">
<option value="2018">2018</option>
<option value="2019">2019</option>
<option value="2020">2020</option>
<option value="2021">2021</option>
</select>
届
</div>
<div class="form-group">
<label for="email" class="label">生源地:</label>
<input type="text" class="form-control" id="birthplace" name="birthplace" placeholder="请输入生源地" oninput="inputemail()">
<div class="righttip"></div>
<div class="tip" id="tip5">
<div class="tipicon"></div>
<div id="tip_5" class="tipmessage"></div>
</div>
</div>
<div class="form-group">
<label for="email" class="label">备注:</label>
<input type="text" class="form-control" id="text" name="text" oninput="inputemail()">
<div class="righttip"></div>
<div class="tip" id="tip5">
<div class="tipicon"></div>
<div id="tip_5" class="tipmessage"></div>
</div>
</div>
<input type="submit" class="sign btn btn-primary btn-lg" value="添加" onclick="return isEmpty()">
</form>
</div>
</body>
</html>
用户登录页面:Login.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>登录</title>
<style>
h2{
border-bottom:5px solid red;
padding-bottom:10px;
text-align:center;
width:100%;
}
</style>
<script type="text/javascript">
function myReload()
{
document.getElementById("CreateCheckCode").src = document
.getElementById("CreateCheckCode").src
+ "?nocache=" + new Date().getTime();
}
</script>
</head>
<body style="background-image:url(login.gif)">
<div align="center" >
<h2>用户登录</h2>
<form action="${pageContext.request.contextPath}/check_login.jsp" method="post">
<p>用户名:
<input type="text" name="username"/>
</p>
<p>密码:
<input type="password" name="password"/>
</p>
<p>验证码:
<input name="checkCode" type="text" id="checkCode" title="验证码不区分大小写"
size="10" maxlength="8" />
<img src="PictureCheckCode" id="CreateCheckCode" align="middle">
<a onclick="myReload()"> 看不清,换一个</a>
</p>
<p><input type="submit" value="登录"> <input type="reset" value="重置"></p>
<p><a href="register.jsp">注册</a></p>
</form>
</div>
</body>
</html>
用户登录检查界面:check_login.jsp
<%@page import="java.sql.*" import="java.util.*"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
//用户名和密码验证
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
Class.forName("com.mysql.cj.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=GMT&allowPublicKeyRetrieval=true";
String userName = "root";
String Pwd = "123456";
conn = DriverManager.getConnection(url, userName, Pwd);
request.setCharacterEncoding("utf-8");
String username = request.getParameter("username");
String password = request.getParameter("password");
String sql = "SELECT *FROM signin_users WHERE username ='" + username + "'AND password = '" + password + "'";
ps = conn.prepareStatement(sql);
rs = ps.executeQuery();
HttpSession session2 = request.getSession();
session2.setAttribute("username", username);
//验证码验证
String checkcode=request.getParameter("checkCode");
boolean flag;
if(checkcode.equals("")||checkcode==null)
{
out.print("<script>alert('请输入验证码');window.location.href('Login.jsp')</script>");
flag=false;
}
else
{
if(!checkcode.equalsIgnoreCase((String)session.getAttribute("randCheckCode")))
{
out.print("<script>alert('验证码不正确,请重新输入');history.back(-1);</script>");
flag=false;
}
else
{
//out.print("登录成功");
flag=true;
}
}
if (rs.next() && flag==true) {
response.sendRedirect("./loginSucceed.jsp");
}
else{
response.sendRedirect("./loginFailed.jsp");
}
%>
用户登录成功页面:loginSucceed.jsp
<%@page import="java.sql.*"%>
<%@ page contentType="text/html;charset=UTF-8" language="java"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>登录成功</title>
</head>
<body >
<form style="height:100%;color:red;background-image:url(ht.gif)">
<p align="left">登录成功,欢迎您:${username}
<div align="right">
<a href="Login.jsp">退出</a>
<a href="index.jsp">回到首页</a>
</div>
</form>
</body>
</html>
用户登录失败页面:loginFailed.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>登录失败</title>
</head>
<body>
<h1>登录失败!</h1>
<p><a href="Login.jsp">返回学生登录</a></p>
<p><a href="admin_login.jsp">返回管理员登录</a></p>
</body>
</html>
管理员管理主页:inde.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ page import="com.DatebaseO.Contact"%>
<%@ page import="com.DatebaseO.ContactService"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://"
+ request.getServerName() + ":" + request.getServerPort()
+ path + "/";
//下面的语句初始为初始化页面,如果不加下面语句访问主页不会显示数据库中保存的数据
ContactService ud = new ContactService();
List<Contact> ulist = ud.GetAllContact();
request.setAttribute("ulist", ulist);
%>
<!DOCTYPE html>
<html>
<head>
<title>管理界面</title>
<base href="<%=basePath%>" rel="external nofollow" rel="external nofollow" rel="external nofollow" >
<meta charset="UTF-8">
<link rel="stylesheet"
href="https://cdn.bootcss.com/foundation/5.5.3/css/foundation.min.css" rel="external nofollow" rel="external nofollow" rel="external nofollow" >
<script src="https://cdn.bootcss.com/jquery/2.1.1/jquery.min.js"></script>
<script
src="https://cdn.bootcss.com/foundation/5.5.3/js/foundation.min.js"></script>
<script
src="https://cdn.bootcss.com/foundation/5.5.3/js/vendor/modernizr.js"></script>
<style type="text/css">
table {
margin: auto;
}
td {
text-align: center;
}
h1 {
margin-left: 40%;
}
a#add {
margin-left: 45%;
}
</style>
<title>Insert title here</title>
</head>
<body style="padding:20px;">
<h1>主页</h1>
<a id="add" href="add.jsp" rel="external nofollow" >新增</a>
<table>
<thead>
<tr>
<th>用户名</th>
<th>密码</th>
<th>性别</th>
<th>名字</th>
<th>学号</th>
<th>邮箱</th>
<th>学院</th>
<th>系</th>
<th>班别</th>
<th>届</th>
<th>籍贯</th>
<th>其他</th>
</tr>
<c:forEach var="U" items="${ulist}">
<tr>
<th>${U.username}</th>
<th>${U.password}</th>
<th>${U.sex}</th>
<th>${U.name}</th>
<th>${U.id}</th>
<th>${U.email}</th>
<th>${U.agency}</th>
<th>${U.major}</th>
<th>${U.classnum}</th>
<th>${U.year}</th>
<th>${U.birthplace}</th>
<th>${U.text}</th>
<th><a href="ContactServlet?do=editbefore&id=${U.id}" rel="external nofollow" >修改</a> <a href="ContactServlet?do=del&id=${U.id}" rel="external nofollow" >删除</a> </th>
</tr>
</c:forEach>
</thead>
<%--<c:forEach/>标签遍历List--%>
</table>
</body>
</html>
对用户新增操作:add.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%>" rel="external nofollow" rel="external nofollow" rel="external nofollow" >
<title>My JSP 'add.jsp' starting page</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet"
href="https://cdn.bootcss.com/foundation/5.5.3/css/foundation.min.css" rel="external nofollow" rel="external nofollow" rel="external nofollow" >
<script src="https://cdn.bootcss.com/jquery/2.1.1/jquery.min.js"></script>
<script
src="https://cdn.bootcss.com/foundation/5.5.3/js/foundation.min.js"></script>
<script
src="https://cdn.bootcss.com/foundation/5.5.3/js/vendor/modernizr.js"></script>
</head>
<body>
<h1>新增页面</h1>
<form action="ContactServlet?do=add" method="post" style="width:50%;">
<fieldset>
<label>用户名 <input type="text" placeholder="username" required="required" name="username" /> </label>
<label>密码 <input type="password" placeholder="password" required="required" name="password" /> </label>
<label>性别<input type="text" placeholder="sex" required="required" name="sex" /> </label>
<label>名字<input type="text" placeholder="name" required="required" name="name" /> </label>
<label>学号<input type="text" placeholder="id" required="required" name="id" /> </label>
<label>邮箱<input type="text" placeholder="email" required="required" name="email" /> </label>
<label>学院<input type="text" placeholder="agency" required="required" name="agency" /> </label>
<label>系<input type="text" placeholder="major" required="required" name="major" /> </label>
<label>班别<input type="text" placeholder="classnum" required="required" name="classnum" /> </label>
<label>届<input type="text" placeholder="year" required="required" name="year" /> </label>
<label>籍贯<input type="text" placeholder="birthplace" required="required" name="birthplace" /> </label>
<label>其他<input type="text" placeholder="text" required="required" name="text" /> </label>
<input type="submit" value="新增" class="button" />
<input type="reset" class="button" />
</fieldset>
</form>
</body>
</html>
对用户编辑操作:edit.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%>" rel="external nofollow" rel="external nofollow" rel="external nofollow" >
<title>My JSP 'add.jsp' starting page</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet"
href="https://cdn.bootcss.com/foundation/5.5.3/css/foundation.min.css" rel="external nofollow" rel="external nofollow" rel="external nofollow" >
<script src="https://cdn.bootcss.com/jquery/2.1.1/jquery.min.js"></script>
<script
src="https://cdn.bootcss.com/foundation/5.5.3/js/foundation.min.js"></script>
<script
src="https://cdn.bootcss.com/foundation/5.5.3/js/vendor/modernizr.js"></script>
</head>
<body>
<h1>修改页面</h1>
<form action="ContactServlet?do=edit&id=${edituser.id}" method="post" style="width:50%">
<fieldset>
<label>用户名 <input type="text" placeholder="username" name="username" value = "${edituser.username}"></label>
<label>密码 <input type="password" placeholder="password" name="password" value = "${edituser.password}"></label>
<label>性别<input type="text" placeholder="sex" name="sex" value = "${edituser.sex}">
</label>
<label>名字<input type="text" placeholder="name" name="name" value = "${edituser.name}">
</label>
<label>学号<input type="text" placeholder="id" name="id" value = "${edituser.id}">
</label>
<label>邮箱<input type="text" placeholder="email" name="email" value = "${edituser.email}">
</label>
<label>学院<input type="text" placeholder="agency" name="agency" value = "${edituser.agency}">
</label>
<label>系<input type="text" placeholder="major" name="major" value = "${edituser.major}">
</label>
<label>班别<input type="text" placeholder="classnum" name="classnum" value = "${edituser.classnum}">
</label>
<label>届<input type="text" placeholder="year" name="year" value = "${edituser.year}">
</label>
<label>籍贯<input type="text" placeholder="birthplace" name="birthplace" value = "${edituser.birthplace}">
</label>
<label>其他<input type="text" placeholder="text" name="text" value = "${edituser.text}">
</label>
<input type="submit" value="修改" class="button"> <input type="reset" class="button">
</fieldset>
</form>
</body>
</html>
管理员注册页面:admin_register.jsp
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<!DOCTYPE html>
<html>
<head>
<title>用户注册</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/4.3.1/css/bootstrap.min.css">
<script src="https://cdn.staticfile.org/jquery/3.2.1/jquery.min.js"></script>
<style>
body{
background-image:url(bt.gif);
}
.container{
margin-top:100px;
border-radius:10px;
padding-top:50px;
padding-bottom:50px;
align:center;
background-color:white;
opacity:0.8;
width:500px;
}
form{
margin-top:20px;
}
.form-group{
align:center;
width:350px;
margin:auto;
position:relative;
}
h2{
border-bottom:5px solid red;
padding-bottom:10px;
text-align:center;
width:100%;
}
.label{
float:left;
width:80px;
margin-top:7px;
margin-right:5px;
text-align:left;
}
.form-control{
width:200px;
margin-top:7px;
}
.sex{
border:0px solid #000;
width:200px;
margin-top:7px;
}
.sign{
width:160px;
margin-top:10px;
}
.tip{
position:relative;
width:100%;
height:auto;
padding:5px;
}
.tip .tipicon{
float:left;
background-image:url(D:/Desktop/bt.gif);
background-repeat:no-repeat;
background-position:center;
background-size:cover;
width:20px;
height:20px;
}
.tipmessage{
color:red;
font-size:15px;
}
.tip{
display:none;
}
.righttip{
display:none;
position:absolute;
right:8px;
top:8px;
width:25px;
height:25px;
background-image:url(D:/Desktop/bt.gif);
background-repeat:no-repeat;
background-position:center;
background-size:cover;
}
</style>
<script type="text/javascript">
function isMobileNumber(phone) {
var flag = false;
var message = "";
var myreg = /^(((13[0-9]{1})|(14[0-9]{1})|(17[0-9]{1})|(15[0-3]{1})|(15[4-9]{1})|(18[0-9]{1})|(199))+\d{8})$/;
if (myreg.test(phone)){
flag = true;
}
return flag;
}
function GetQueryString(name) {
var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
var r = window.location.search.substr(1).match(reg); //获取url中"?"符后的字符串并正则匹配
var context = "";
if (r != null)
context = r[2];
reg = null;
r = null;
return context == null || context == "" || context == "undefined" ? "" : context;
}
function isEmail(email){
//对电子邮件的验证
var myreg = /^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/;
if(!myreg.test(email)){
return false;
}
else
return true;
}
function isPwd(password)
{
var myreg=/[0-9a-zA-Z]+/;
if(!myreg.test(password))
return false;
else
return true;
}
function isId(id)
{
if((id[0]=="2")&&(id[1]=="0")&&(id[2]=="1")&&(id[3]=="8"))
return true;
else
return false;
}
function inputusername()
{
var username=$("#usr").val();
var tip1=$("#tip1");
var tip_1=$("#tip_1");
if(!((username[0]>='a'&&username[0]<='z')||(username[0]>='A'&&username[0]<='Z')))
{
$("#usr").next().css("display","none");
tip1.css("display","block");
tip_1.html("用户名必须以英文字母开头!");
}
else if(username.length<6||username.length>12){
$("#usr").next().css("display","none");
tip1.css("display","block");
tip_1.html("用户名必须为6-12位字符!");
}
else
{
tip1.css("display","none");
$.post(
"UserServlet",
{username:username},
function(data){
if(data=="yes"){
tip1.css("display","none");
$("#usr").next().css("display","block");
}
else{
$("#usr").next().css("display","none");
tip1.css("display","block");
tip_1.html("用户名已被注册!");
}
},
"text"
);
}
}
function inputId()
{
var id=$("#id").val();
var tip4=$("#tip4");
var tip_4=$("#tip_4");
if(!isId(id))
{
$("#id").next().css("display","none");
tip4.css("display","block");
tip_4.html("学号必须以2018开头!");
}
else if(id.length!=8){
$("#id").next().css("display","none");
tip4.css("display","block");
tip_4.html("请输入8位学号!");
}
else
{
tip4.css("display","none");
$.post(
"IdServlet",
{id:id},
function(data){
if(data=="yes"){
tip4.css("display","none");
$("#id").next().css("display","block");
}
else{
$("#id").next().css("display","none");
tip4.css("display","block");
tip_4.html("该学号已存在!");
}
},
"text"
);
}
}
function inputpassword()
{
var password=$("#pwd").val();
var tip2=$("#tip2");
var tip_2=$("#tip_2");
if(password.length<6)
{
$("#pwd").next().css("display","none");
tip2.css("display","block");
tip_2.html("请输入6位以上密码!");
}
else if(!isPwd(password)){
$("#pwd").next().css("display","none");
tip2.css("display","block");
tip_2.html("密码仅由英文或数字组成!");
}
else{
tip2.css("display","none");
$("#pwd").next().css("display","block");
}
}
function inputmobile()
{
var mobile=$("#mobile").val();
var tip4=$("#tip4");
var tip_4=$("#tip_4");
if(mobile.length!=11)
{
$("#mobile").next().css("display","none");
tip4.css("display","block");
tip_4.html("请输入11位手机号!");
}
else if(isMobileNumber(mobile)==false){
$("#mobile").next().css("display","none");
tip4.css("display","block");
tip_4.html("手机号格式不正确!");
}
else
{
tip4.css("display","none");
$.post(
"MobileServlet",
{mobile:mobile},
function(data){
if(data=="yes"){
tip4.css("display","none");
$("#mobile").next().css("display","block");
}
else{
$("#usr").next().css("display","none");
tip4.css("display","block");
tip_4.html("手机号已被注册!");
}
},
"text"
);
}
}
function inputemail()
{
var email=$("#email").val();
var tip5=$("#tip5");
var tip_5=$("#tip_5");
if(!isEmail(email))
{
$("#email").next().css("display","none");
tip5.css("display","block");
tip_5.html("邮箱格式不正确!");
}
else
{
tip5.css("display","none");
$.post(
"EmailServlet",
{email:email},
function(data){
if(data=="yes"){
tip5.css("display","none");
$("#email").next().css("display","block");
}
else{
$("#email").next().css("display","none");
tip5.css("display","block");
tip_5.html("邮箱已被注册!");
}
},
"text"
);
}
}
function isEmpty()
{
if($("#usr").val()==""||$("#pwd").val()==""||$("#name").val()==""||$('input[name="sex"]:checked').val()==""||$("#sel1").val()==""||
$("#agency").val()==""||$("#major").val()==""||$("#classnum").val()==""||$("#birthplace").val()==""
||$("#email").val()==""||$("#id").val()==""||$("#text").val()=="")
{
alert("请将信息填写完整!");
return false;
}
return true;
}
function getResult()
{
if(GetQueryString("result")=="true")
alert("添加成功!");
else if(GetQueryString("result")=="false")
alert("添加失败!");
}
var inputs=document.getElementsByTagName("input");
for(var i=0;i<inputs.length;i++)
{
inputs[i].onkeyup=function(event){
if(event.keyCode=13){
var next=this.nextElementSibling.nextElementSibling;
next.focus();
}
}
}
</script>
</head>
<body onload="getResult()">
<div class="container">
<h2>管理员注册<a href="admin_login.jsp">登陆</a></h2>
<form action="Signin_admin" method="post">
<div class="form-group">
<label for="usr" class="label">账号:</label>
<input type="text" class="form-control" id="usr" name="username" oninput="inputusername()" placeholder="请输入用户名">
<div class="righttip"></div>
<div class="tip" id="tip1">
<div class="tipicon"></div>
<div id="tip_1" class="tipmessage"></div>
</div>
</div>
<div class="form-group">
<label for="pwd" class="label">密码:</label>
<input type="password" class="form-control" id="pwd" name="password" placeholder="请输入密码" oninput="inputpassword()">
<div class="righttip"></div>
<div class="tip" id="tip2">
<div class="tipicon"></div>
<div id="tip_2" class="tipmessage"></div>
</div>
</div>
<input type="submit" class="sign btn btn-primary btn-lg" value="添加" onclick="return isEmpty()">
</form>
</div>
</body>
</html>
管理员登录页面:admin_login.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>管理员登录</title>
<style>
h2{
border-bottom:5px solid red;
padding-bottom:10px;
text-align:center;
width:100%;
}
</style>
<script type="text/javascript">
function myReload()
{
document.getElementById("CreateCheckCode").src = document
.getElementById("CreateCheckCode").src
+ "?nocache=" + new Date().getTime();
}
</script>
</head>
<body style="background-image:url(login.gif)">
<div align="center" >
<h2>用户登录</h2>
<form action="${pageContext.request.contextPath}/check_admin_login.jsp" method="post">
<p>用户名:
<input type="text" name="username"/>
</p>
<p>密码:
<input type="password" name="password"/>
</p>
<p>验证码:
<input name="checkCode" type="text" id="checkCode" title="验证码不区分大小写"
size="10" maxlength="8" />
<img src="PictureCheckCode" id="CreateCheckCode" align="middle">
<a onclick="myReload()"> 看不清,换一个</a>
</p>
<p><input type="submit" value="登录"> <input type="reset" value="重置"></p>
<p><a href="admin_login.jsp">注册</a></p>
</form>
</div>
</body>
</html>
管理员登录检查页面:admin_check_login.jsp
<%@page import="java.sql.*" import="java.util.*"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
//用户名和密码验证
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
Class.forName("com.mysql.cj.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=GMT&allowPublicKeyRetrieval=true";
String userName = "root";
String Pwd = "123456";
conn = DriverManager.getConnection(url, userName, Pwd);
request.setCharacterEncoding("utf-8");
String username = request.getParameter("username");
String password = request.getParameter("password");
String sql = "SELECT *FROM signin_admin WHERE username ='" + username + "'AND password = '" + password + "'";
ps = conn.prepareStatement(sql);
rs = ps.executeQuery();
HttpSession session2 = request.getSession();
session2.setAttribute("username", username);
//验证码验证
String checkcode=request.getParameter("checkCode");
boolean flag;
if(checkcode.equals("")||checkcode==null)
{
out.print("<script>alert('请输入验证码');window.location.href('admin_login.jsp')</script>");
flag=false;
}
else
{
if(!checkcode.equalsIgnoreCase((String)session.getAttribute("randCheckCode")))
{
out.print("<script>alert('验证码不正确,请重新输入');history.back(-1);</script>");
flag=false;
}
else
{
//out.print("登录成功");
flag=true;
}
}
if (rs.next() && flag==true) {
response.sendRedirect("./inde.jsp");
}
else{
response.sendRedirect("./loginFailed.jsp");
}
%>
页面动图:
bt.gif
ht.gif
index.gif
login.gif
对数据库新建表的操作,本项目用到的是MySQL,并且直接在CMD下进行操作,如何用CMD对SQL的访问,笔者不再具体详述,需要的可以直接搜索相关教程。
1、首先创建一个数据库
create database test;
2、然后在此数据库下新建表
create table signin_users
(
username varchar(255) not null,
password varchar(255) not null,
sex varchar(255) not null,
name varchar(255) not null,
id varchar(255) not null,
email varchar(255) not null,
agency varchar(255) not null,
major varchar(255) not null,
classnum varchar(255) not null,
year varchar(255) not null,
birthplace varchar(255) not null,
text varchar(255) not null,
primary key(id)
);
create table signin_admin
(
username varchar(255) not null,
password varchar(255) not null,
primary key(username)
);
后记:
运行的效果截图(因为页面是动图,截图的效果没有自己直接运行那么有趣)
在浏览器下的效果图:
以上。。。