为员工管理系统添加注册和登陆功能,注册时需要进行用户名是否存在的判断,如果存在则出现提示。登陆成功即可对员工信息进行增删改查操作。
CREATE TABLE `t_user` (
`id` int(4) NOT NULL AUTO_INCREMENT,
`username` varchar(20) NOT NULL,
`pwd` varchar(30) NOT NULL,
`name` varchar(50) DEFAULT NULL,
`gender` char(2) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=16 DEFAULT CHARSET=utf8;
新建一个员工表t_emp
CREATE TABLE `t_emp` (
`id` int(4) NOT NULL AUTO_INCREMENT,
`name` varchar(8) NOT NULL,
`salary` float(8,2) DEFAULT NULL,
`age` int(2) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8;
step2: 创建一个实体类entity.User类和一个实体类entity.Employee类
package entity;
public class Employee {
private int id;
private String name;
private float salary;
private int age;
@Override
public String toString(){
return id+" "+name+" "+salary+" "+age;
}
public Employee(){
super();
}
public Employee(int id,String name,float salary,int age){
super();
this.id=id;
this.name=name;
this.salary=salary;
this.age=age;
}
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 float getSalary() {
return salary;
}
public void setSalary(float salary) {
this.salary = salary;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
entity.User类
package entity;
public class User {
private int id;
private String username;
private String pwd;
private String name;
private String gender;
@Override
public String toString(){
return id+" "+username+" "+pwd+" "+name+" "+gender;
}
public User(){
super();
}
public User(int id,String username,String pwd,String name,String gender){
super();
this.id=id;
this.username=username;
this.pwd=pwd;
this.name=name;
this.gender=gender;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
}
step3:创建三个dao类
数据库连接类dao.DBUtil类
package dao;
import java.sql.Connection;
import java.sql.DriverManager;
public class DBUtil {
//新建一个连接
public static Connection getConnection()throws Exception{
Connection conn=null;
try {
//加载驱动
Class.forName("com.mysql.jdbc.Driver");
//创建实例
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "123456");
} catch (Exception e) {
e.printStackTrace();
throw e;
}
return conn;
}
//关闭数据库连接
public static void close(Connection conn)throws Exception{
if(conn!=null){
try {
conn.close();
} catch (Exception e) {
e.printStackTrace();
throw e;
}
}
}
}
dao.EmployeeDAO类
package dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import javax.swing.text.html.HTMLDocument.HTMLReader.ParagraphAction;
import entity.Employee;
public class EmployeeDAO {
//查询所有员工
public List findAll()throws Exception{
List emps=new ArrayList();
Connection conn=null;
PreparedStatement stmt=null; // PreparedStatement 实例包含已编译的 SQL 语句
ResultSet rs=null;
try {
conn=DBUtil.getConnection();
stmt=conn.prepareStatement("select * from t_emp");
rs=stmt.executeQuery();
while(rs.next()){
Employee emp=new Employee(
rs.getInt("id"),
rs.getString("name"),
rs.getFloat("salary"),
rs.getInt("age")
);
emps.add(emp);
}
} catch (Exception e) {
e.printStackTrace();
throw e;
}finally{
DBUtil.close(conn);
}
return emps;
}
//删除
public void delete(int id) throws Exception{
Connection conn=null;
PreparedStatement stmt=null;
try {
conn=DBUtil.getConnection();
stmt=conn.prepareStatement("delete from t_emp where id=?");
stmt.setInt(1, id);
stmt.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
throw e;
}finally{
DBUtil.close(conn);
}
}
//增加员工信息
public void save(Employee emp) throws Exception{
Connection conn=null;
PreparedStatement stmt=null;
try {
conn=DBUtil.getConnection();
stmt=conn.prepareStatement("insert into t_emp(name,salary,age) " +
"values(?,?,?)");
stmt.setString(1, emp.getName()); //stmt,使用set
stmt.setFloat(2, emp.getSalary());
stmt.setInt(3, emp.getAge());
stmt.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
throw e;
}finally{
DBUtil.close(conn);
}
}
//根据id查询员工信息
public Employee findById(int id) throws Exception{
Employee emp=null;
Connection conn=null;
PreparedStatement stmt=null;
ResultSet rs=null;
try {
conn=DBUtil.getConnection();
stmt=conn.prepareStatement("select * from t_emp where id=?");
stmt.setInt(1, id);
rs=stmt.executeQuery();
while(rs.next()){
emp=new Employee(
rs.getInt("id"), //结果集rs,使用get
rs.getString("name"),
rs.getFloat("salary"),
rs.getInt("age")
);
}
} catch (Exception e) {
e.printStackTrace();
throw e;
}finally{
DBUtil.close(conn);
}
return emp;
}
//修改
public void modify(Employee emp)throws Exception{ //对整条记录修改
Connection conn=null;
PreparedStatement stmt=null;
try {
conn=DBUtil.getConnection();
stmt=conn.prepareStatement("update t_emp set name=?,salary=?,age=? " +
"where id=?");
stmt.setString(1, emp.getName());
stmt.setFloat(2, emp.getSalary());
stmt.setInt(3, emp.getAge());
System.out.println(emp.getAge());
stmt.setInt(4, emp.getId());
stmt.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
throw e;
}finally{
DBUtil.close(conn);
}
}
}
dao.UserDAO类
package dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import com.sun.org.apache.xml.internal.dtm.ref.DTMDefaultBaseIterators.PrecedingIterator;
import entity.User;
public class UserDAO {
//按名字查找
public User findByUserName(String username)throws Exception{
User user=null;
Connection conn=null;
PreparedStatement stmt=null;
ResultSet rs=null;
try {
conn=DBUtil.getConnection();
stmt=conn.prepareStatement("select * from t_user where username=?");
stmt.setString(1, username);
rs=stmt.executeQuery();
while(rs.next()){ //数据加载进rs
user=new User(
rs.getInt("id"),
rs.getString("username"),
rs.getString("pwd"),
rs.getString("name"),
rs.getString("gender")
);
}
} catch (Exception e) {
e.printStackTrace();
throw e;
}finally{
DBUtil.close(conn);
}
return user;
}
//用户名不存在时保存用户信息(增加用户信息)
public void save(User user) throws Exception{
Connection conn=null;
PreparedStatement stmt=null;
try {
conn=DBUtil.getConnection();
stmt=conn.prepareStatement("insert into t_user(username,pwd,name,gender) " +
"values(?,?,?,?)");
stmt.setString(1, user.getUsername());
stmt.setString(2, user.getPwd());
stmt.setString(3, user.getName());
stmt.setString(4, user.getGender());
stmt.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
throw e;
}finally{
DBUtil.close(conn);
}
}
}
Step 4:创建一个Web.ActionServlet类
package web;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import dao.EmployeeDAO;
import dao.UserDAO;
import entity.Employee;
import entity.User;
public class ActionServlet extends HttpServlet {
public void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
PrintWriter out = response.getWriter();
//获取请求资源的路径,截取action动作
String uri=request.getRequestURI();
String action=uri.substring(uri.lastIndexOf("/")+1,uri.lastIndexOf("."));
//创建员工管理操作类
EmployeeDAO dao=new EmployeeDAO();
//创建用户操作类
UserDAO Udao=new UserDAO();
//判断请求动作种类,分不同种类情况处理
if(action.equals("list")){ //员工信息列表
try {
List emps=dao.findAll();
request.setAttribute("emps", emps); //绑定数据到request
request.getRequestDispatcher("listEmp.jsp").forward(request, response);//转发
} catch (Exception e){
e.printStackTrace();
}
}else if(action.equals("add")){
String name=request.getParameter("name");
float salary=Float.parseFloat(request.getParameter("salary"));
int age=Integer.parseInt(request.getParameter("age"));
Employee emp=new Employee();
emp.setName(name);
emp.setSalary(salary);
emp.setAge(age);
try {
dao.save(emp);
response.sendRedirect("list.do");
} catch (Exception e) {
e.printStackTrace();
}
}else if(action.equals("delete")){
int id=Integer.parseInt(request.getParameter("id"));
try {
dao.delete(id);
response.sendRedirect("list.do");
} catch (Exception e) {
e.printStackTrace();
}
}else if(action.equals("load")){//加载某个员工
int id=Integer.parseInt(request.getParameter("id")); //字符串转化为整型
try {
Employee emp=dao.findById(id);
request.setAttribute("emp", emp); //绑定数据到request
request.getRequestDispatcher("updateEmp.jsp").forward(request, response);//转发
} catch (Exception e) {
e.printStackTrace();
}
}else if(action.equals("update")){
int id=Integer.parseInt(request.getParameter("id")); //字符串转化为整型
String name=request.getParameter("name");
float salary=Float.parseFloat(request.getParameter("salary"));
int age=Integer.parseInt(request.getParameter("age"));
Employee emp=new Employee();
emp.setName(name);
emp.setSalary(salary);
emp.setAge(age);
emp.setId(id);
try {
dao.modify(emp);
response.sendRedirect("list.do");
} catch (Exception e) {
e.printStackTrace();
}
}else if(action.equals("regist")){//注册 。若直接用regit.do访问,会插入很多空值
String username=request.getParameter("username");
String name=request.getParameter("name");
String pwd=request.getParameter("pwd");
String gender=request.getParameter("gender");
try {
User user=Udao.findByUserName(username);
if(user!=null){
request.setAttribute("regis_err", "用户名已存在");
request.getRequestDispatcher("regist.jsp").forward(request, response);
}else{
user=new User();
user.setUsername(username);
user.setName(name);
user.setPwd(pwd);
user.setGender(gender);
Udao.save(user);
response.sendRedirect("login.jsp");
}
} catch (Exception e) {
e.printStackTrace();
throw new ServletException(e);
}
}else if(action.equals("login")){ //登陆
String username=request.getParameter("username");
String pwd=request.getParameter("pwd");
try {
User user=Udao.findByUserName(username);
//System.out.println(user.getUsername());
if(user==null||!user.getPwd().equals(pwd)){
request.setAttribute("login_err", "用户名不正确或者密码错误");
request.getRequestDispatcher("login.jsp").forward(request, response);
}else{
response.sendRedirect("list.do");
//out.print("登陆成功");
}
} catch (Exception e) {
e.printStackTrace();
throw new ServletException(e);
}
}
}
}
Step5: 页面设计
登陆界面login.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<HTML>
<HEAD>
<TITLE>用户登录TITLE>
<META http-equiv=Content-Type content="text/html; charset=UTF-8">
HEAD>
<BODY>
<form action="login.do" method="post">
<table>
<tr>
<td>用户名: td>
<td><input type="text" name="username"/>
tr>
<tr>
<td>密 码: td>
<td><INPUT type="password" name="pwd"/> td>
tr>
table>
<p><INPUT type="submit" class="button" value="Submit »" />p>
form>
BODY>
HTML>
注册界面regist.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<html>
<head>
<title>用户注册title>
<META http-equiv=Content-Type content="text/html; charset=UTF-8">
head>
<body>
<h1>注册h1>
<form action="regist.do" method="post">
<table cellpadding="0" cellspacing="0" border="1">
<tr>
<td>用户名: td>
<td><input type="text" name="username"/>
<%
String errorMsg=(String)request.getAttribute("regis_err");
%>
<span style="color:red;"><%=errorMsg==null?"":errorMsg%>span>
td>
tr>
<tr>
<td>真实姓名: td>
<td><input type="text" name="name"/>td>
tr>
<tr>
<td>密码: td>
<td><input type="password" name="pwd"/>td>
tr>
<tr>
<td>性别: td>
<td>
男<input type="radio" name="gender" checked="checked" value="m"/>
女<input type="radio" name="gender" checked="checked" value="f"/>
td>
tr>
table>
<p><INPUT type="submit" class="button" value="Submit »" />p>
form>
body>
html>
信息列表界面listEmp.jsp
<%@ page language="java" contentType="text/html;charset=UTF-8" pageEncoding="UTF-8"%>
<%@ page import="java.util.*,entity.*" %>
<html>
<head>
<title>员工信息title>
<meta http-equiv="content-Type" content="text/html;charset=utf-8">
<link rel="stylesheet" type="text/css" href="css/styles.css">
head>
<body>
<table class="imagetable">
<caption>员工信息caption>
<tr>
<td>编号td>
<td>姓名td>
<td>薪水td>
<td>年龄td>
tr>
<%
List emps=(List)request.getAttribute("emps");
for(int i=0;iget (i);
//System.out.println(emp.getId());
%>
<tr>
<td><%=emp.getId()%>td>
<td><%=emp.getName()%>td>
<td><%=emp.getSalary()%>td>
<td><%=emp.getAge()%>td>
<td><a href="delete.do?id=<%=emp.getId()%>"
onclick="return confirm('是否确认删除<%=emp.getName() %>的信息?');">删除a>
<a href="load.do?id=<%=emp.getId() %>">修改a>
td>
tr>
<%
}
%>
table>
<p>
<input type="button" class="button" value="增加员工" onclick="location='addEmp.jsp'"/>
p>
body>
html>
增加员工界面addEmp.jsp
<%@ page language="java" import="java.util.*,dao.*,entity.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<html>
<head>
<base href="<%=basePath%>">
<title>修改员工信息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">
<meta http-equiv="content-Type" content="text/html;charset=utf-8">
head>
<body style="font-size:24px">
<form action="add.do" method="post">
<fieldset>
<legend>增加员工legend>
姓名:<input name="name"/><br>
薪水:š<input name="salary"/><br>
年龄:<input name="age"/><br>
<input type="submit" value="增加">
fieldset>
form>
body>
html>
更新数据界面updateEmp.jsp
<%@ page language="java" contentType="text/html;charset=UTF-8" pageEncoding="UTF-8"%>
<%@ page import="java.util.*,entity.*" %>
<html>
<head>
<title>修改员工信息title>
<meta http-equiv="content-Type" content="text/html;charset=utf-8">
<link rel="stylesheet" type="text/css" href="css/styles.css">
head>
<body>
<h1>更新员工信息h1>
<%
Employee emp=(Employee)request.getAttribute("emp");
%>
<form action="update.do?id=<%=emp.getId()%>" method="post">
<table cellpadding="0" cellspacing="0" border="0">
<tr>
<td>编号: td><td><%=emp.getId() %>td>
tr>
<tr>
<td>姓名: td><td><input name='name' value='<%=emp.getName()%>'/>td>
tr>
<tr>
<td>薪水: td><td><input name='salary' value='<%=emp.getSalary()%>'/>td>
tr>
<tr>
<td>年龄: td><td><input name='age' value='<%=emp.getAge()%>'/>td>
tr>
table>
<p>
<input type="submit" class="button" value="修改" />
p>
form>
body>
html>
补充:
运行环境:
系统:win 7 32bit
IDE:MyEclipse 10
数据库:Mysql 5.6
能让上面的程序跑起来重要的两点:
1、使用JDBC连接Mysql 需要驱动包,
mysql-connector-java-5.1.7-bin.jar
mysql-connector-java-5.1.7-bin.jar
2、需要配置web.xml文件,如下:
<web-app version="3.0"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
<display-name>display-name>
<servlet>
<description>This is the description of my J2EE componentdescription>
<display-name>This is the display name of my J2EE componentdisplay-name>
<servlet-name>ActionServletservlet-name>
<servlet-class>web.ActionServletservlet-class>
servlet>
<servlet-mapping>
<servlet-name>ActionServletservlet-name>
<url-pattern>*.dourl-pattern>
servlet-mapping>
<welcome-file-list>
<welcome-file>login.jspwelcome-file>
welcome-file-list>
web-app>