工程结构如下,其中,图上少了main.jsp界面。该界面为主界面,提供跳转到增,删,查,改,界面的超链接 部分功能未实现
开发环境如下:ubuntu 14.04 +myeclipse 2014 +tomcat 7+mysql+jdbc5.1.7
参考传智博客 韩顺平java ee教程。
数据库如下:
-- MySQL dump 10.13 Distrib 5.5.41, for debian-linux-gnu (x86_64)
--
-- Host: localhost Database: spdb1
-- ------------------------------------------------------
-- Server version 5.5.41-0ubuntu0.14.04.1
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;
/*!40103 SET TIME_ZONE='+00:00' */;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
--
-- Table structure for table `users`
--
DROP TABLE IF EXISTS `users`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `users` (
`userId` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(20) DEFAULT NULL,
`passwd` varchar(20) DEFAULT NULL,
`email` varchar(30) DEFAULT NULL,
`grade` int(11) DEFAULT NULL,
PRIMARY KEY (`userId`)
) ENGINE=InnoDB AUTO_INCREMENT=28 DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `users`
--
LOCK TABLES `users` WRITE;
/*!40000 ALTER TABLE `users` DISABLE KEYS */;
INSERT INTO `users` VALUES (1,'admin','admin','[email protected]',1),(2,'frank','frank','[email protected]',1),(6,'tester4','tester4','[email protected]',5),(7,'tester5','tester5','[email protected]',5),(9,'tester7','tester7','[email protected]',5),(10,'tester8','tester8','[email protected]',5),(11,'tester9','tester9','[email protected]',5),(12,'tester10','tester10','[email protected]',5),(13,'tester11','tester11','[email protected]',5),(14,'tester12','tester12','[email protected]',5),(15,'tester13','tester13','[email protected]',5),(16,'tester14','tester14','[email protected]',5),(19,'texter','texter','[email protected]',5),(20,'texter1','texter1','[email protected]',5),(21,'x','x','null',5),(22,'xiaoming','xiaoming','null',5),(23,'1','1','null',1),(24,'mm','mm','null',1),(25,'43','34','null',4),(26,'er','er','er',5),(27,'yvy','yvy','[email protected]',1);
/*!40000 ALTER TABLE `users` ENABLE KEYS */;
UNLOCK TABLES;
/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;
/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
-- Dump completed on 2015-02-13 21:51:49
LoginClServlet.java 负责用户登录的验证
package com.sp.controller;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.sp.model.*;
public class LoginClServlet extends HttpServlet {
/**
* The doGet method of the servlet.
*
* This method is called when a form has its tag value method equals to get.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
//得到用户名和密码
String u=request.getParameter("username");
String p=request.getParameter("passname");
UserBeanCl ubc=new UserBeanCl();
//System.out.println("使用servlet");
if(ubc.checkUser(u, p))
{
ArrayList al=ubc.getUsersByPage(1);
int pageCount=ubc.getPageCount();
request.setAttribute("result", al);
request.setAttribute("pageCount", pageCount);
request.setAttribute("pageNow", 1);
//将用户名放入session,以备后用
request.getSession().setAttribute("myName", u);
request.getRequestDispatcher("main.jsp").forward(request, response);
}
else
{
request.getRequestDispatcher("login.jsp").forward(request, response);
}
}
/**
* The doPost method of the servlet.
*
* This method is called when a form has its tag value method equals to post.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
this.doGet(request, response);
}
}
package com.sp.controller;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.sp.model.*;
public class UsersClServlet extends HttpServlet {
/**
* The doGet method of the servlet.
*
* This method is called when a form has its tag value method equals to get.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
//获得标识位
String flag=request.getParameter("flag");
if(flag.equals("cutpage"))
{
try{
int pageNow=Integer.parseInt(request.getParameter("pageNow"));
UserBeanCl ubc=new UserBeanCl();
ArrayList al=ubc.getUsersByPage(pageNow);
int pageCount=ubc.getPageCount();
request.setAttribute("result", al);
request.setAttribute("pageCount", pageCount);
request.setAttribute("pageNow", pageNow);
request.getRequestDispatcher("wel.jsp").forward(request, response);
}catch (Exception e){
e.printStackTrace();
}
}
else if(flag.equals("delUser"))
{
//删除用户
String userId=request.getParameter("userId");
UserBeanCl ubc=new UserBeanCl();
if(ubc.delUserById(userId))
{
//删除成功
request.getRequestDispatcher("suc.jsp").forward(request, response);
}
else
{
//删除失败
request.getRequestDispatcher("err.jsp").forward(request, response);
}
}
else if(flag.equals("addUser"))
{
//添加用户
//得到用户输入的信息
String name=request.getParameter("userName");
String passwd=request.getParameter("passwd");
String email=request.getParameter("email");
String grade=request.getParameter("grade");
UserBeanCl ubc=new UserBeanCl();
if( ubc.addUser(name, passwd, email, grade) )
{
//添加成功
request.getRequestDispatcher("suc.jsp").forward(request, response);
}
else
{
//添加失败
request.getRequestDispatcher("err.jsp").forward(request, response);
}
}
else if(flag.equals("updateUser"))
{
//修改用户
//得到用户输入的信息
String userId=request.getParameter("userId");
String name=request.getParameter("userName");
String passwd=request.getParameter("passwd");
String email=request.getParameter("email");
String grade=request.getParameter("grade");
UserBeanCl ubc=new UserBeanCl();
if( ubc.ubdateUser(userId,name, passwd, email, grade) )
{
//修改成功
request.getRequestDispatcher("suc.jsp").forward(request, response);
}
else
{
//修改失败
request.getRequestDispatcher("err.jsp").forward(request, response);
}
}
}
/**
* The doPost method of the servlet.
*
* This method is called when a form has its tag value method equals to post.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
this.doGet(request, response);
}
}
model
ConnDB.java 负责加载数据库驱动,获得连接
package com.sp.model;
import java.sql.*;
public class ConnDB {
private Connection ct=null;
public Connection getConn()
{
try{
Class.forName("com.mysql.jdbc.Driver");
ct=DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/spdb1?user=root&password=frank1994");
}catch(Exception e){
e.printStackTrace();
}
return ct;
}
}
package com.sp.model;
public class UserBean {
private int userId;
private String username;
private String passwd;
private String email;
private int grade;
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPasswd() {
return passwd;
}
public void setPasswd(String passwd) {
this.passwd = passwd;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public int getGrade() {
return grade;
}
public void setGrade(int grade) {
this.grade = grade;
}
}
//连接数据库
package com.sp.model;
import java.sql.*;
import java.util.*;
public class UserBeanCl {
//验证用户是否合法
private Statement sm=null;
private ResultSet rs=null;
private Connection ct=null;
private int pageSize=3;
private int rowCount=0;
private int pageCount=0;
//修改用户
public boolean ubdateUser(String userId,String name,String passwd,String email,String grade)
{
boolean b=false;
try{
ct=new ConnDB().getConn();
sm=ct.createStatement();
int a=sm.executeUpdate("update users set username='"+name+"',passwd='"+passwd+"',email='"+email+"', grade='"+grade+"' where userId='"+userId+"'");
if(a==1)
b=true;
}catch(Exception e){
e.printStackTrace();
}finally{
this.close();
}
return b;
}
//添加用户
/**
*
* @param name :用户名
* @param passwd:密码
* @param email:邮箱
* @param grade:级别
* @return boolean: if true 添加成功 else 失败
*/
public boolean addUser(String name,String passwd,String email,String grade)
{
boolean b=false;
try{
ct=new ConnDB().getConn();
sm=ct.createStatement();
int a=sm.executeUpdate("insert into users(username,passwd,email,grade) values('"+name+"','"+passwd+"','"+email+"','"+grade+"') ");
if(a==1)
b=true;
}catch(Exception e){
e.printStackTrace();
}finally{
this.close();
}
return b;
}
//删除用户
public boolean delUserById(String id)
{
boolean b=false;
try{
ct=new ConnDB().getConn();
sm=ct.createStatement();
int a=sm.executeUpdate("delete from users where userId='"+id+"'");
if(a==1)
b=true;
}catch(Exception e){
e.printStackTrace();
}finally{
this.close();
}
return b;
}
//返回总页数
public int getPageCount()
{
try{
ct=new ConnDB().getConn();
sm=ct.createStatement();
rs=sm.executeQuery("select count(*) from users");
if(rs.next())
{
rowCount=rs.getInt(1);
}
pageCount=rowCount%pageSize==0?rowCount/pageSize:rowCount/pageSize+1;
}catch(Exception e){
e.printStackTrace();
}finally{
this.close();
}
return pageCount;
}
//得到需要显示的用户信息
public ArrayList getUsersByPage(int pageNow)
{
ArrayList al=new ArrayList();
try{
ct=new ConnDB().getConn();
sm=ct.createStatement();
//查询出需要显示的记录
rs=sm.executeQuery("select * from users limit "+(pageNow-1)*pageSize+","+pageSize+"");
while(rs.next())
{
UserBean ub=new UserBean();
ub.setUserId(rs.getInt(1));
ub.setUsername(rs.getString(2));
ub.setPasswd(rs.getString(3));
ub.setEmail(rs.getString(4));
ub.setGrade(rs.getInt(5));
al.add(ub);
}
}catch(Exception e){
e.printStackTrace();
}finally{
this.close();
}
return al;
}
//关闭资源
public void close()
{
//关闭资源
try{
if(rs!=null)
{
rs.close();
rs=null;
}
if(sm!=null)
{
sm.close();
sm=null;
}
if(ct!=null)
{
ct.close();
ct=null;
}
}catch(Exception e){
e.printStackTrace();
}
}
public boolean checkUser(String u,String p)
{
boolean b=false;
try{
ct=new ConnDB().getConn();
sm=ct.createStatement();
rs=sm.executeQuery("select passwd from users where username='"+u+"'");
if(rs.next())
{
if(rs.getString(1).equals(p))
{
//合法
b=true;
}
}
}catch(Exception e){
e.printStackTrace();
}finally{
this.close();
}
return b;
}
}
main.jsp 提供跳转到个个功能界面的链接
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
My JSP 'main.jsp' starting page
请选择操作
管理用户
添加用户
查找用户
注销用户
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
My JSP 'addUser.jsp' starting page
请输入用户信息
err.jsp 操作失败界面
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
My JSP 'err.jsp' starting page
操作失败!
返回主界面
login.jsp 登录界面
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
My JSP 'login.jsp' starting page
<%
String err=request.getParameter("err");
if(err!=null)
{
if(err.equals("1"))
{
out.println("用户没有正常登录,请登录!
");
}
}
%>
用户登录
suc.jsp 操作成功界面
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
My JSP 'suc.jsp' starting page
恭喜你,操作成功!
返回主界面
<%@ page language="java" import="java.util.*,com.sp.model.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
My JSP 'updateUser.jsp' starting page
请输入用户信息
<%@ page language="java" import="java.util.*,java.sql.*,com.sp.model.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://"
+ request.getServerName() + ":" + request.getServerPort()
+ path + "/";
%>
My JSP 'wel.jsp' starting page
<%
//防止用户非法登录
String u=(String)session.getAttribute("myName") ;
if(u==null)
{
response.sendRedirect("login.jsp?err=1");
return ;
}
%>
登录成功!哈哈<%=u%>
返回重新登录 返回主界面
用户信息列表
<%
//UserBeanCl ubc=new UserBeanCl();
//ArrayList al=ubc.getUsersByPage(pageNow);
ArrayList al=(ArrayList)request.getAttribute("result");
%>
用户ID 用户名
密码 电子邮件 级别
修改用户 删除用户
<%
String []color={"silver","pink"};
for(int i=0;i
><%=ub.getUserId() %> <%=ub.getUsername() %>
<%=ub.getPasswd() %> <%=ub.getEmail() %> <%=ub.getGrade() %>
修改用户
删除用户
<%
}
%>
<%
int pageNow=((Integer)request.getAttribute("pageNow")).intValue();
if(pageNow!=1)
{
//显示上一页
out.println("上一页");
}
int pageCount=((Integer)request.getAttribute("pageCount")).intValue();
//显示超链接
for(int i=1;i<=pageCount;i++)
{
out.println(" ["+i+"]");
}
if(pageNow!=pageCount)
{
//显示下一页
out.println("下一页");
}
%>
<%
%>
web.xml如下:
This is the description of my J2EE component
This is the display name of my J2EE component
LoginClServlet
com.sp.controller.LoginClServlet
This is the description of my J2EE component
This is the display name of my J2EE component
UsersClServlet
com.sp.controller.UsersClServlet
LoginClServlet
/LoginClServlet
UsersClServlet
/UsersClServlet