Java基础13
Jsp+javaBean(java文件)模式开发用户管理系统 4
1. jsp+java_class模式下的用户管理系统模型图 5
2.登录界面_UserManagerSys/src/webRoot/login.jsp 5
3.登录处理界面_UserManagerSys/src/webRoot/loginCl.jsp 6
4.欢迎界面_UserManagerSys/src/webRoot/wel.jsp 7
5.model层_UserManagerSys/src/user.model/UserBeanCl.java 10
6.model层_UserManagerSys/src/user.model/UserBean.java 14
5.model层_UserManagerSys/src/user.model/ConnDB.java 15
登录界面_UserManageSys2/WebRoot/WEB-INF/login.jsp 20
登录处理界面_UserManageSys2/WebRoot/WEB-INF/loginCl.jsp 22
主界面_UserManageSys2/WebRoot/WEB-INF/Main.jsp 24
欢迎界面_UserManageSys2/WebRoot/WEB-INF/wel.jsp 26
修改界面_UserManageSys2/WebRoot/WEB-INF/updateUser.jsp 30
添加用户界面_UserManageSys2/WebRoot/WEB-INF/addUser.jsp 32
操作成功界面_UserManageSys2/WebRoot/WEB-INF/suc.jsp 34
操作失败界面_UserManageSys2/WebRoot/WEB-INF/err.jsp 36
登录处理_UserManageSys2/ src/user.controller/LoginClServer.java 37
处理用户的服务_UserManageSys2/ src/user.controller/UserClServer.java 40
Users表_UserManageSys2/src/user.model/UserBean.java 43
表处理_UserManageSys2/ src/user.model/UserBeanCl.java 45
工具类_UserManageSys2/ src/user.model/Tools.java 51
连接数据库_UserManageSys2/ src/user.model/ConnDB.java 52
文件结构
Jsp内置对象
1.out //向客户端输出数据,字节流
out.println("");
2.request //接收客户端的http请求 <----->servlet中的HttpServletRequest
getParameter(String name); //name表表单的参数名
getParameterValues(String name); //得到参数值集,使用String []
setAttribute(String name,Object obj); //设置名字为name的obj,值为obj
getAttribute(String name); //返回由name指定的属性值,如果不存在就返回null;
getCookie();
3.response //封装jsp的产生的回应
addCookie(Cookie cookie);
sendRedirect("./welcome.jsp");
4.session //用于保存用户的信息,跟踪用户的行为
setAttribute(String name,Object obj);
getAttribute(String name);
5.applicattion //多个用户共享该对象,可以做计数器
6.pageContext //代表jsp页面的上下文
7.exception //代表运行的一个异常
getMessage();
8.page //代表jsp这个实例本身(使用比较少)
9.config //代表jsp对应的servlet的配置,可以得到web.xml中的参数
//===========================================================================
//------------session技术--------------
1.得到session
servlet中:HttpSession hs=request.getSession(true);
jsp中:session是一个内置对象,可以直接使用
2.向session添加属性
servlet中:hs.setAttribute(String name,Object val);
jsp中:session.setAttribute(String name,Object o);
3.从session得到某个属性//(getAttribute得到的属性是Object类型,要注意转换类型)
servlet中:hs.getAttribute(String name);
jsp中:session.getAttribute(String name);
4.从session删除掉某个属性
servlet中:hs.removeAttribute(String name);
jsp中:session.removeAttribute(String name);
5.指定session发吊时的存活时间//(这设置成20秒,默认是30分钟)
servlet中:hs.setMaxInactive(20);
jsp中:session.setMaxInactive(20);
6.session的特点:
//1.session是被某个浏览器独占的空间,
//2.当某个浏览器访问网站时,服务器会给浏览器分配一个唯一的session id,以此区分不同客户端
//3.由于session的各个属性要占用服务器内存,因此要迫不得以,才使用,如下情况用:
//1.保存用户信息
//2.保存购物车 等
Jsp测试案例(MyHello.jsp)
<%@ page language="java" import="java.util.*" pageEncoding="gb2312"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'MyHello.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
Hello,维唯为为 <br>
</body>
</html>
Jsp+javaBean(java文件)模式开发用户管理系统
1. jsp+java_class模式下的用户管理系统模型图
2.登录界面_UserManagerSys/src/webRoot/login.jsp
<%@ page language="java" import="java.util.*" pageEncoding="gb2312"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'login.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body bgcolor="pink">
<center>
用户登录 <br>
<hr>
<form action="loginCl.jsp" method="post">
用户名:<input type="text" name="username"/><br>
密 码:<input type="password" name="passwd"/><br>
<input type="submit" value="登录"/>
<input type="reset" value="重置"/>
</form>
</center>
</body>
</html>
3.登录处理界面_UserManagerSys/src/webRoot/loginCl.jsp
<%@ page language="java" import="java.util.*,java.sql.*,user.model.*" pageEncoding="gb2312"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'loginCl.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
<%
//接收用户名和密码,完成对用户的验证
String u=request.getParameter("username");
String p=request.getParameter("passwd");
//到数据库中去验证用户
//调用UserBeanCl的方法,完成对用户的验证
UserBeanCl ubc=new UserBeanCl();
if(ubc.checkUser(u,p))
{
response.sendRedirect("wel.jsp?username="+u);
}else
{
response.sendRedirect("login.jsp?errNo=1");
}
%>
</body>
</html>
4.欢迎界面_UserManagerSys/src/webRoot/wel.jsp
<%@ page language="java" import="java.util.*,java.sql.*,user.model.*" pageEncoding="gb2312"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'wel.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body bgcolor="pink">
<%
String u=request.getParameter("username");
%>
登录成功!维唯为为恭喜你!<%=u %><br>
<a href="login.jsp">返回重新登录</a>
<hr>
<center>
<h1>用户信息列表</h1>
<%
//定义分页用到的变量
int pageNow=1;
//接收用户希望显示的页数(pageNow)
String s_pageNow=request.getParameter("pageNow");
if(s_pageNow!=null)
{
//接收到pageNow
pageNow=Integer.parseInt(s_pageNow);
}
//调用UserBeanCl的方法(创建一个UserBeanCl的实例,然后调用它的某个方法),完成分布显示
UserBeanCl ubc=new UserBeanCl();
ArrayList al=ubc.getUserByPage(pageNow);
//显示
%>
<table border="1">
<tr><td>用户id</td><td>用户名</td><td>密码</td><td>邮箱</td><td>级别</td></tr>
<%
for(int i=0;i<al.size();i++)
{ //从al中取出UserBean
UserBean ub=(UserBean)al.get(i);
%>
<tr><td><%=ub.getUserId() %></td><td><%=ub.getUsername() %></td>
<td><%=ub.getPasswd() %></td><td><%=ub.getEmail() %></td>
<td><%=ub.getGrade() %></td></tr>
<%
}
%>
</table>
<%
int pageCount=ubc.getPageCount();
int pageSize=ubc.getPageSize();
//首页
out.println("<a href=wel.jsp?pageNow=1&username="+u+">首页</a>");
//上一页
if(pageNow!=1)
{
out.println("<a href=wel.jsp?pageNow="+(pageNow-1)+"&username="+u+">上一页</a>");
}
//显示页面链接
for(int i=pageNow;i<pageNow+pageSize&&i<=pageCount;i++)
{
out.println("<a href=wel.jsp?pageNow="+i+"&username="+u+">["+i+"]</a>");
}
//下一页
if(pageNow!=pageCount)
{
out.println("<a href=wel.jsp?pageNow="+(pageNow+1)+"&username="+u+">下一页</a>");
}
//尾页
out.println("<a href=wel.jsp?pageNow="+pageCount+"&username="+u+">尾页</a>");
%>
</center>
</body>
</html>
5.model层_UserManagerSys/src/user.model/UserBeanCl.java
/**
* 这是一个处理类,有些人把它叫做BO,主要是封装对user表的各种操作,(主要
* 是增,删,修,查...)
*/
package user.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=5;
public int getPageSize() {
return pageSize;
}
private int rowCount=0; //行数
private int pageCount=0;//页数
//验证用户是否存在
public boolean checkUser(String u,String p)
{
boolean b=false;
try {
//到数据库去验证
ct=new ConnDB().getConn();
//3.创建Statement
Statement sm=ct.createStatement();
//4.查询
ResultSet rs=sm.executeQuery("select passwd from users where username='"+u+"'");
//验证
if(rs.next())
{
//到此说明输入的用户名存在
if(rs.getString(1).equals(p))
{
b=true;
//合法,跳转wel.jsp
//如何将loginCl.jsp得到的数据传到下一个页面
//1.cookie 2.session 3.response.sendRedirect
//response.sendRedirect("wel.jsp?user="+u);//将用户发送过去
}else
{
//密码错误
}
}else
{
//用户名错误
//不合法,跳转到login.jsp
//response.sendRedirect("login.jsp?errNo=1");
}
} catch (SQLException e) {
e.printStackTrace();
}finally{
//关闭打开的各种资源
this.close();
}
return b;
}
/**
* @author luowei
* @return 返回分页的总页数
*/
public int getPageCount()
{
try {
//得到连接
ct=new ConnDB().getConn();
//3.创建Statement
Statement sm=ct.createStatement();
//4.查询
ResultSet rs=sm.executeQuery("select count(*) from users");
if(rs.next())//将游标从第0条记录移到第1条记录,并判断是否为空
{
rowCount=rs.getInt(1);
}
//计算
if(rowCount%pageSize==0)
{
pageCount=rowCount/pageSize;
}else
{
pageCount=rowCount/pageSize+1;
}
} catch (Exception e) {
e.printStackTrace();
}finally
{
this.close();
}
return pageCount;
}
/**@得到用户需要显示的用户信息(分页)
* @author luowei
* @param pageNow:当前页
* @return
*/
public ArrayList getUserByPage(int pageNow)
{
ArrayList al=new ArrayList();
try {
//得到连接
ct=new ConnDB().getConn();
//3.创建Statement
Statement sm=ct.createStatement();
//查询出需要显示的记录
rs=sm.executeQuery("select * from users limit "+(pageSize*(pageNow-1))+","+pageSize);
//开始将rs封装到ArrayList
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;
}
/**@author luowei
* @see关闭资源
* @return null
*
*/
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();
}
}
}
6.model层_UserManagerSys/src/user.model/UserBean.java
/**
* 这是一个javabean,对应user表,代表数据
* 他的一个实例(对象),对应users的一条
*/
package user.model;
public class UserBean {
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;
}
private int userId;
private String username;
private String passwd;
private String email;
private int grade;
}
5.model层_UserManagerSys/src/user.model/ConnDB.java
/**
* 得到数据库的连接
*/
package user.model;
import java.sql.*;
public class ConnDB {
private Connection ct=null;
public Connection getConn()
{
try {
//1.加载驱动
Class.forName("org.gjt.mm.mysql.Driver").newInstance();
//Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver").newInstance();
//2.得到连接
ct=DriverManager.getConnection("jdbc:mysql://localhost:3306/test_user","root","root");
//ct=DriverManager.getConnection("jdbc:microsoft:sqlserver://localhost:1433;databaseName=testusr","sa","luowei");
} catch (Exception e) {
e.printStackTrace();
}
return ct;
}
}
MVC模式开发用户管理系统
1. MVC模介绍
MVC模型图
mvc用户管理系统模型图
2.向数据库添加用户表
create database test_user;
use test_user;
create table users(
useId int primary key AUTO_INCREMENT,#用户id号
username varchar(20),
passwd varchar(20),
email varchar(30),
grade int #用户的级别
);
insert into users values(null,"admin","admin","admin@sohu.com","1");
insert into users values(null,"luowei","luowei505050","luowei@163.com","1");
insert into users values(null,"test1","test1","test1@sina.com","5");
insert into users values(null,"test2","test2","test2@sina.com","2");
insert into users values(null,"test3","test3","test3@sina.com","5");
insert into users values(null,"test4","test4","test4@sina.com","6");
insert into users values(null,"test5","test5","test5@sina.com","6");
insert into users values(null,"test6","test6","test6@sina.com","7");
insert into users values(null,"test7","test7","test7@sina.com","7");
insert into users values(null,"test8","test8","test8@sina.com","8");
insert into users values(null,"test9","test9","test9@sina.com","8");
insert into users values(null,"test10","test10","test10@sina.com","9");
insert into users values(null,"test11","test11","test11@sina.com","3");
insert into users values(null,"test12","test12","test12@sina.com","4");
select * from users;
insert into users(username,passwd,email,grade) select username,passwd,email,grade from users;
select * from users where username=admin and passwd=admin;
#添加新列
alter table users add myPic varchar(30);
#修改数据
update users set myPic='luowei.gif' where userName='luowei';
update users set myPic='admin.gif' where userName='admin';
update users set myPic='test1.gif' where userName='test1';
#drop table users;
#--------------------------------------------------------------------
CREATE TABLE person (
id SMALLINT UNSIGNED NOT NULL AUTO_INCREMENT,
name CHAR(60) NOT NULL,
PRIMARY KEY (id)
);
CREATE TABLE shirt (
id SMALLINT UNSIGNED NOT NULL AUTO_INCREMENT,
style ENUM('t-shirt', 'polo', 'dress') NOT NULL,
color ENUM('red', 'blue', 'orange', 'white', 'black') NOT NULL,
owner SMALLINT UNSIGNED NOT NULL REFERENCES person(id),
PRIMARY KEY (id)
);
INSERT INTO person VALUES (NULL, 'Antonio Paz');
SELECT @last := LAST_INSERT_ID();
INSERT INTO shirt VALUES
(NULL, 'polo', 'blue', @last),
(NULL, 'dress', 'white', @last),
(NULL, 't-shirt', 'blue', @last);
INSERT INTO person VALUES (NULL, 'Lilliana Angelovska');
SELECT @last := LAST_INSERT_ID();
INSERT INTO shirt VALUES
(NULL, 'dress', 'orange', @last),
(NULL, 'polo', 'red', @last),
(NULL, 'dress', 'blue', @last),
(NULL, 't-shirt', 'white', @last);
SELECT * FROM person;
SELECT * FROM shirt;
SELECT s.* FROM person p, shirt s
WHERE p.name LIKE 'Lilliana%'
AND s.owner = p.id
AND s.color <> 'white';
#----------------------------------------------------------
select * from users order by useId limit 5;
界面层(View层)
登录界面_UserManageSys2/WebRoot/WEB-INF/login.jsp
<!-- 登录界面 -->
<%@ page language="java" import="java.util.*" pageEncoding="gb2312"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'login.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body bgcolor="ff9900">
<center>
<%
String errNo=request.getParameter("errNo");
if(errNo!=null)
{
if(errNo.equals("1"))
{
out.println("<font color=red size=7>登录错误,请输入正确的用户名和密码!</font><br>");
}
}
%>
<!-- 引入一张图片 -->
<img src="imgs/1.gif"/>
<hr>
用户登录 <br>
<form action="LoginClServlet" method="post">
用户名:<input type="text" name="username"/><br>
密 码:<input type="password" name="passwd"/><br>
<input type="submit" value="登录"/>
<input type="reset" value="重置"/>
</form>
<hr>
<!-- 引入一张图片 -->
<img src="imgs/logo.gif"/>
</center>
</body>
</html>
登录处理界面_UserManageSys2/WebRoot/WEB-INF/loginCl.jsp
<%@ page language="java" import="java.util.*,java.sql.*,user.model.*" pageEncoding="gb2312"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'loginCl.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
<%
//接收用户名和密码,完成对用户的验证
String u=request.getParameter("username");
String p=request.getParameter("passwd");
//到数据库中去验证用户
//调用UserBeanCl的方法,完成对用户的验证
UserBeanCl ubc=new UserBeanCl();
if(ubc.checkUser(u,p))
{
response.sendRedirect("wel.jsp?username="+u);
}else
{
response.sendRedirect("login.jsp?errNo=1");
}
%>
</body>
</html>
主界面_UserManageSys2/WebRoot/WEB-INF/Main.jsp
<!--主界面 -->
<%@ page language="java" import="java.util.*" pageEncoding="gb2312"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'Main.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body bgcolor="ff9900">
<%
String u=request.getParameter("username");
//System.out.println("Main.jsp得到的username="+u);
%>
<center>
<!-- 引入一张图片 -->
<img src="imgs/1.gif"/>
<hr>
<h1>请选择操作</h1>
<a href="UserClServlet?pageNow=1&flag=fenye&username=<%=u %>" >管理用户</a><br/>
<!-- flag标志告诉控制器,进行分页 -->
<!-- 注意这里变量<%=u %>要放在双引号里边,直接赋给username -->
<a href="addUser.jsp?username=<%=u %>">添加用户</a><br/>
<a href="#">查找用户</a><br/>
<a href="#">注销用户</a><br/>
<hr>
<!-- 引入一张图片 -->
<img src="imgs/logo.gif"/>
</center>
</body>
</html>
欢迎界面_UserManageSys2/WebRoot/WEB-INF/wel.jsp
<!--欢迎界面 -->
<%@ page language="java" import="java.util.*,java.sql.*,user.model.*" pageEncoding="gb2312"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'wel.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
<script type="text/javascript">
<!--
function msg()
{
return window.confirm("你确认要删除吗?");
}
-->
</script>
</head>
<body bgcolor="ff9900">
<%
String u=request.getParameter("username");
//System.out.println("UserClServlet得到的username="+u);
//u=new String(u.getBytes("gb2312"),"iso-8859-1"); //转码
//防止用户非法登录
String userName=(String)session.getAttribute("myName");
//如果用户没有登录
if(userName==null)
{
//返回登录界面
response.sendRedirect("login.jsp?errNo=1");
return ;
}
%>
登录成功!维唯为为恭喜你!<%=u %><br/>
session得到的用户名为:<%=userName %><br/>
<a href="login.jsp">返回重新登录</a>
<a href="Main.jsp?username=<%=u %>">返回主界面</a>
<hr>
<center>
<h1>用户信息列表</h1>
<%
//调用UserBeanCl的方法(创建一个UserBeanCl的实例,然后调用它的某个方法),完成分布显示
//UserBeanCl ubc=new UserBeanCl();
//ArrayList al=ubc.getUserByPage(pageNow);
//要显示的用户信息从request中取
ArrayList al=(ArrayList)request.getAttribute("result");
//显示
%>
<%
//得到pageCount
String s_pageCount=(String)request.getAttribute("pageCount");
int pageCount=Integer.parseInt(s_pageCount);
String s_pageSize=(String)request.getAttribute("pageSize");
int pageSize=Integer.parseInt(s_pageSize);
String s_pageNow=(String)request.getAttribute("pageNow");
int pageNow=Integer.parseInt(s_pageNow);
%>
<table border="1">
<tr bgcolor="pink"><td>用户id</td><td>用户名</td><td>密码</td>
<td>邮箱</td><td>级别</td><td>修改用户</td><td>删除用户</td></tr>
<%
//定义一个颜色数组
String []color={"silver","pink"};
for(int i=0;i<al.size();i++)
{ //从al中取出UserBean
UserBean ub=(UserBean)al.get(i);
%>
<tr bgcolor="<%=color[i%2] %>"><td><%=ub.getUserId() %></td><td><%=ub.getUsername() %></td>
<td><%=ub.getPasswd() %></td><td><%=ub.getEmail() %></td>
<td><%=ub.getGrade() %></td>
<td><a href="updateUser.jsp?username=<%=u%>&pageNow=<%=pageNow %>&userId=<%=ub.getUserId()
%>&userName=<%=ub.getUsername() %>&passWd=<%=ub.getPasswd() %>&email=<%=ub.getEmail()
%>&grade=<%=ub.getGrade() %>">修改用户</a></td>
<td><a onclick="return msg()" href="UserClServlet?username=<%=u%>&pageNow=<%=pageNow
%>&flag=delUser&userid=<%=ub.getUserId() %>">删除用户</a></td></tr>
<%
}
%>
</table>
<%
//首页
out.println("<a href=UserClServlet?flag=fenye&pageNow=1&username="+u+">首页</a>"); //转到分页控制器处理
//上一页
if(pageNow!=1)
{
out.println("<a href=UserClServlet?flag=fenye&pageNow="+(pageNow-1)+"&username="+u+">上一页</a>");
}
//显示页面链接
for(int i=pageNow;i<pageNow+pageSize&&i<=pageCount;i++)
{
out.println("<a href=UserClServlet?flag=fenye&pageNow="+i+"&username="+u+">["+i+"]</a>");
}
//下一页
if(pageNow!=pageCount)
{
out.println("<a href=UserClServlet?flag=fenye&pageNow="+(pageNow+1)+"&username="+u+">下一页</a>");
}
//尾页
out.println("<a href=UserClServlet?flag=fenye&pageNow="+pageCount+"&username="+u+">尾页</a>");
%>
<hr>
<!-- 引入一张图片 -->
<img src="imgs/logo.gif"/>
</center>
</body>
</html>
修改界面_UserManageSys2/WebRoot/WEB-INF/updateUser.jsp
<%@ page language="java" import="java.util.*" pageEncoding="gb2312"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'updateUser.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body bgcolor="ff9900">
<%
String u=request.getParameter("username");
String pageNow=request.getParameter("pageNow");
//String flag=request.getParameter("flag");
//System.out.println("Main.jsp得到的username="+u);
%>
欢迎您:<%=u %><br>
<a href="Main.jsp?username=<%=u %>">返回主界面</a>
<a href="UserClServlet?username=<%=u %>&UserClServlet=<%=u %>&pageNow=<%=pageNow %>&flag=fenye">返回上一页</a>
<center>
<!-- 引入一张图片 -->
<img src="imgs/1.gif"/>
<hr>
<h1>修改用户信息</h1>
<form action="UserClServlet?pageNow=1&flag=updateUser&username=<%=u %>" method="post">
<table border="1">
<tr bgcolor="pink"><td>用户Id</td><td><input readonly type="text" name="userId" value="<%=request.getParameter("userId") %>"/></td></tr>
<tr bgcolor="pink"><td>用户名</td><td><input type="text" name="userName" value="<%=request.getParameter("userName") %>"/></td></tr>
<tr bgcolor="silver"><td>密码</td><td><input type="text" name="passWd" value="<%=request.getParameter("passWd") %>"/></td></tr>
<tr bgcolor="pink"><td>电子邮件</td><td><input type="text" name="email" value="<%=request.getParameter("email") %>"/></td></tr>
<tr bgcolor="silver"><td>级别</td><td><input type="text" name="grade" value="<%=request.getParameter("grade") %>"/></td></tr>
</table>
<input type="submit" value="修改信息"/>
</form>
<hr>
<!-- 引入一张图片 -->
<img src="imgs/logo.gif"/>
</center>
</body>
</html>
添加用户界面_UserManageSys2/WebRoot/WEB-INF/addUser.jsp
<%@ page language="java" import="java.util.*" pageEncoding="gb2312"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'addUser.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body bgcolor="ff9900">
<%
String u=request.getParameter("username");
//System.out.println("Main.jsp得到的username="+u);
%>
欢迎您:<%=u %><br>
<a href="Main.jsp?username=<%=u %>">返回主界面</a>
<center>
<!-- 引入一张图片 -->
<img src="imgs/1.gif"/>
<hr>
<h1>请输入用户信息</h1>
<form action="UserClServlet?pageNow=1&flag=addUser&username=<%=u %>" method="post">
<table border="1">
<tr bgcolor="pink"><td>用户名</td><td><input type="text" name="userName"/></td></tr>
<tr bgcolor="silver"><td>密码</td><td><input type="text" name="password"/></td></tr>
<tr bgcolor="pink"><td>电子邮件</td><td><input type="text" name="email"/></td></tr>
<tr bgcolor="silver"><td>级别</td><td><input type="text" name="grade"/></td></tr>
</table>
<input type="submit" value="添加用户"/>
<input type="reset" value=" 重 置 "/>
</form>
<hr>
<!-- 引入一张图片 -->
<img src="imgs/logo.gif"/>
</center>
</body>
</html>
操作成功界面_UserManageSys2/WebRoot/WEB-INF/suc.jsp
<!-- 登录界面 -->
<%@ page language="java" import="java.util.*" pageEncoding="gb2312"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'login.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body bgcolor="ff9900">
<center>
<!-- 引入一张图片 -->
<img src="imgs/1.gif"/>
<hr>
<%
String u=request.getParameter("username");
//String pageNow=request.getParameter("pageNow");
//String flag=request.getParameter("flag");
%>
<h1>恭喜你 <%=u %>,操作成功!</h1><br>
<a href="Main.jsp?username=<%=u %>">返回主界面</a>
<!--
<a href="addUser.jsp?username=<%=u %>">返回上一页</a>
-->
<hr>
<!-- 引入一张图片 -->
<img src="imgs/logo.gif"/>
</center>
</body>
</html>
操作失败界面_UserManageSys2/WebRoot/WEB-INF/err.jsp
<!-- 登录界面 -->
<%@ page language="java" import="java.util.*" pageEncoding="gb2312"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'login.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body bgcolor="ff9900">
<center>
<!-- 引入一张图片 -->
<img src="imgs/1.gif"/>
<hr>
<%
String u=request.getParameter("username");
//String pageNow=request.getParameter("pageNow");
//String flag=request.getParameter("flag");
%>
<h1>操作不成功!</h1><br>
<a href="Main.jsp?username=<%=u %>">返回主界面</a>
<!--
<a href="addUser.jsp?username=<%=u %>">返回上一页</a>
-->
<hr>
<!-- 引入一张图片 -->
<img src="imgs/logo.gif"/>
</center>
</body>
</html>
控制器层(controller层)
登录处理_UserManageSys2/ src/user.controller/LoginClServer.java
/**
* 这是一个控制器,主要完成对用户身份的验证
* 控制器本身是不会去完成业务逻辑,它主要是去调用模型完成对数据的处理
*/
package user.controller;
import user.model.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class LoginClServlet extends HttpServlet {
/**
* The doGet method of the servlet. <br>
*
* 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");
//u=new String(u.getBytes("iso-8859-1"),"gb2312");//将用户名转码,解决中文乱码而导致的验证错误
String p=request.getParameter("passwd");
System.out.println("username="+u+" password="+p);
//使用模型(UserBeanCl),完成对用户的验证
//1.创建一个UserBeanCl对象
UserBeanCl ubc=new UserBeanCl();
//调用方法
if(ubc.checkUser(u, p))
{
//System.out.println("使用了servlet控制器完成验证!");
//在跳转到wel.jsp页面时,就把要显示的数据给wel.jsp准备好
ArrayList al=ubc.getUserByPage(1);
int pageCount=ubc.getPageCount();
int pageSize=ubc.getPageSize();
//将al,pageCount,pageNow,pageSize放入request当中
request.setAttribute("result", al);
request.setAttribute("pageCount", pageCount+"");
//因为第二个参数是对象,用int直接传递,后边使用时不好处理,所以把它转成String
request.setAttribute("pageSize", pageSize+"");
request.setAttribute("pageNow", "1");
//合法
//response.sendRedirect("wel.jsp?username="+u);
//因为sendRedirect方法效率不高,所以一般多是用转发的方法
//将用户名放入session,以备后用
request.getSession().setAttribute("myName", u);
//这种方法的效率高,同时保证了request中的原有对象还可以在下一面页使用
//所以就不需要加(?username="+u)了
request.getRequestDispatcher("Main.jsp").forward(request, response);
}else
{
//不合法
request.getRequestDispatcher("login.jsp").forward(request, response);
System.out.println("LoginClServlet验证不合法");
}
}
/**
* The doPost method of the servlet. <br>
*
* 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);
}
}
处理用户的服务_UserManageSys2/ src/user.controller/UserClServer.java
/**
* 这个控制器,将处理用户的分页显示,用户的删除,修改,添加
*/
package user.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 user.model.*;
public class UserClServlet extends HttpServlet {
/**
* The doGet method of the servlet. <br>
*
* 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("fenye")) //如果是分页
{
try {
//得到用户希望显示的信息
int pageNow=Integer.parseInt(request.getParameter("pageNow"));
String u=request.getParameter("username");
System.out.println("UserClServlet得到的username="+u);
//调用UserBeanCl
UserBeanCl ubc=new UserBeanCl();
//在跳转到wel.jsp页面时,就把要显示的数据给wel.jsp准备好
ArrayList al=ubc.getUserByPage(pageNow); //经UserBeanCl处理后,获得当前页的数据
int pageCount=ubc.getPageCount();
int pageSize=ubc.getPageSize();
//将al,pageCount,pageNow,pageSize放入request当中
request.setAttribute("result", al);
request.setAttribute("pageCount", pageCount+"");
//因为第二个参数是对象,用int直接传递,后边使用时不好处理,所以把它转成String
request.setAttribute("pageSize", pageSize+"");
request.setAttribute("username", u);
request.setAttribute("pageNow", pageNow+"");
//重新跳转回wel.jsp
request.getRequestDispatcher("wel.jsp").forward(request, response);
} catch (Exception e) {
e.printStackTrace();
}
}else if(flag.equals("delUser")) //如果是删除
{
//完成删除
//1.得到要删除的用户的id
String userId=request.getParameter("userid");
//创建UserBeanCl
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")) //如果是添加
{
//完成添加用户
//1.得到用户输入的信息
String name=request.getParameter("userName");
String passwd=request.getParameter("password");
String email=request.getParameter("email");
String grade=request.getParameter("grade");
//创建UserBeanCl
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")) //如果是修改
{
//完成添加用户
//1.得到用户输入的信息
String id=request.getParameter("userId");
String name=request.getParameter("userName");
String passwd=request.getParameter("passWd");
String email=request.getParameter("email");
String grade=request.getParameter("grade");
//创建UserBeanCl
UserBeanCl ubc=new UserBeanCl();
if(ubc.updateUser(id,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. <br>
*
* 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层)
Users表_UserManageSys2/src/user.model/UserBean.java
/**
* 这是一个javabean,对应user表,代表数据
* 他的一个实例(对象),对应users的一条
*/
package user.model;
public class UserBean {
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;
}
private int userId;
private String username;
private String passwd;
private String email;
private int grade;
}
表处理_UserManageSys2/ src/user.model/UserBeanCl.java
/**
* 这是一个处理类,有些人把它叫做BO,主要是封装对user表的各种操作,(主要
* 是增,删,修,查...)
*/
package user.model;
import java.io.UnsupportedEncodingException;
import java.sql.*;
import java.util.*;
public class UserBeanCl {
private Statement sm=null;
private ResultSet rs=null;
private Connection ct=null;
private int pageSize=5;
public int getPageSize() {
return pageSize;
}
private int rowCount=0; //行数
private int pageCount=0;//页数
/**
* 验证用户是否存在
* @param u
* @param p
* @return
*/
public boolean checkUser(String u,String p)
{
boolean b=false;
try {
//到数据库去验证
ct=new ConnDB().getConn();
//3.创建Statement
Statement sm=ct.createStatement();
//4.查询
ResultSet rs=sm.executeQuery("select passwd from users where username='"+u+"'");
//验证
if(rs.next())
{
//到此说明输入的用户名存在
if(rs.getString(1).equals(p))
{
b=true;
//合法,跳转wel.jsp
//如何将loginCl.jsp得到的数据传到下一个页面
//1.cookie 2.session 3.response.sendRedirect
//response.sendRedirect("wel.jsp?user="+u);//将用户发送过去
}else
{
//密码错误
}
}else
{
//用户名错误
//不合法,跳转到login.jsp
//response.sendRedirect("login.jsp?errNo=1");
}
} catch (SQLException e) {
e.printStackTrace();
}finally{
//关闭打开的各种资源
this.close();
}
return b;
}
/**添加用户
* @author luowei
* @param name:用户名
* @param passwd:密码
* @param email:电子邮件
* @param grade:级别
* @return boolean
*/
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) //1表示是否是成功的添加了1条记录
{
//添加成功
b=true;
}
} catch (Exception e) {
e.printStackTrace();
}
return b;
}
/**
* 修改用户
* @author luowei
*
*/
public boolean updateUser(String id,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 useId='"+id+"'");
if(a==1) //1表示是否是成功的修改了1条记录
{
//修改成功
b=true;
}
} catch (Exception e) {
e.printStackTrace();
}
return b;
}
/**删除用户
* @author luowei
*/
public boolean delUserById(String id)
{
boolean b=false;
//int Id=Integer.parseInt(id);
try {
//得到连接
ct=new ConnDB().getConn();
sm=ct.createStatement();
//执行
int a=sm.executeUpdate("delete from users where useId='"+id+"'");
if(a==1)
{
//删除成功
b=true;
}
} catch (Exception e) {
e.printStackTrace();
}finally{
this.close();
}
return b;
}
/**
* @author luowei
* @return 返回分页的总页数
*/
public int getPageCount()
{
try {
//得到连接
ct=new ConnDB().getConn();
//3.创建Statement
Statement sm=ct.createStatement();
//4.查询
ResultSet rs=sm.executeQuery("select count(*) from users");
if(rs.next())//将游标从第0条记录移到第1条记录,并判断是否为空
{
rowCount=rs.getInt(1);
}
//计算
if(rowCount%pageSize==0)
{
pageCount=rowCount/pageSize;
}else
{
pageCount=rowCount/pageSize+1;
}
} catch (Exception e) {
e.printStackTrace();
}finally
{
this.close();
}
return pageCount;
}
/**得到用户需要显示的用户信息(分页)
* @author luowei
* @param 当前页
* @return
*/
public ArrayList getUserByPage(int pageNow)
{
ArrayList al=new ArrayList();
try {
//得到连接
ct=new ConnDB().getConn();
//3.创建Statement
Statement sm=ct.createStatement();
//查询出需要显示的记录
rs=sm.executeQuery("select * from users order by useId limit "+(pageSize*(pageNow-1))+","+pageSize);
//开始将rs封装到ArrayList
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;
}
/**@author luowei
* @see关闭资源
* @return null
*
*/
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();
}
}
}
工具类_UserManageSys2/ src/user.model/Tools.java
/**
* 工具类
*/
package user.model;
public class Tools {
/**提供一个方法,将乱码转成gb2312,gbk,utf-8
*
* @param input
* @return
*/
public static String getNewString(String input)
{
String result="";
try{
result=new String(input.getBytes("gb2312"),"iso-8859-1");
}catch(Exception e)
{
e.printStackTrace();
}
return result;
}
}
连接数据库_UserManageSys2/ src/user.model/ConnDB.java
/**
* 得到数据库的连接
*/
package user.model;
import java.sql.*;
public class ConnDB {
private Connection ct=null;
public Connection getConn()
{
try {
//1.加载驱动
Class.forName("org.gjt.mm.mysql.Driver").newInstance();
//Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver").newInstance();
//2.得到连接
ct=DriverManager.getConnection("jdbc:mysql://localhost:3306/test_user","root","root");
//ct=DriverManager.getConnection("jdbc:microsoft:sqlserver://localhost:1433;databaseName=testusr","sa","luowei");
} catch (Exception e) {
e.printStackTrace();
}
return ct;
}
}