增加对用户的增删改查,这样我们这个用户登录系统就改造成了一个用户管理系统(MVC模式)
1,增加(注册)用户
(1)main.jsp
<body bgcolor="#FFFFFF">
<img src="img/logo.png">
<center>
<h2>请选择操作</h2>
<hr>
<a href="UserServlet?flag=fy&pageNow=1">管理用户</a><br>
<a href="addUser.jsp">注册用户</a><br>
<a href="#">注销用户</a><br>
<a href="selectUser.jsp">查找用户</a><br>
<hr>
</center>
</body>
</html>
(2)addUser.jsp
<body bgcolor="#FFFFFF">
<img src="img/logo.png">
<center>
<h2>请输入用户信息</h2>
<hr>
<form action="UserServlet?flag=add" method="post">
用户名:
<input type="text" name="id" />
<br>
密 码:
<input type="password" name="passw" />
<br>
年 龄:
<input type="text" name="age" />
<br>
性 别:
<input type="text" name="sex" />
<br>
<input type="submit" value="注册" />
<input type="reset" value="重置" />
<hr>
</form>
</center>
</body>
</html>
(3)UserServlet.java
package com.dtg.controller;
/*
* 这个控制器,控制分页,增删改查等功能
* */
import java.io.IOException;
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.dtg.model.User;
import com.dtg.model.UserCl;
public class UserServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
/*
* 得到用户希望显示的pageNow
* */
// System.out.println("分页也用的是Servlet控制器");
String s_pageNow = request.getParameter("pageNow"); //从login_success.jsp传过来
String flag = request.getParameter("flag");//获取标记位
if("fy".equals(flag)){
try {
int pageNow = Integer.parseInt(s_pageNow);
UserCl userCl = new UserCl();
ArrayList<User> al = userCl.getUserByPage(pageNow);
int pageCount = userCl.getPageCount();
request.setAttribute("result", al);
request.setAttribute("pageCount", pageCount+"");
request.setAttribute("pageNow", pageNow+"");
request.getRequestDispatcher("login_success.jsp").forward(request,
response);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}else if("del".equals(flag)){
String userId = request.getParameter("userId");
try {
UserCl userCl = new UserCl();
if(userCl.delUser(userId)){
//删除成功
request.getRequestDispatcher("success.jsp").forward(request, response);
System.out.println("进入成功分支");
}else{
//删除失败
request.getRequestDispatcher("failure.jsp").forward(request, response);
System.out.println("进入失败分支");
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else if("update".equals(flag)){
String userId = request.getParameter("userId");
String passw = request.getParameter("passw");
String s_age = request.getParameter("age");
int age = Integer.parseInt(s_age);
String sex = request.getParameter("sex");
try {
UserCl userCl = new UserCl();
User user = new User();
user.setPassword(passw);
user.setAge(age);
user.setSex(sex);
if(userCl.updateUser(user,userId)){
request.getRequestDispatcher("success.jsp").forward(request, response);
}else{
request.getRequestDispatcher("failure.jsp").forward(request, response);
}
} catch (Exception e) {
e.printStackTrace();
// TODO: handle exception
}
}else if("add".equals(flag)){
try {
String id = request.getParameter("id");
String passw = request.getParameter("passw");
String s_age = request.getParameter("age");
int age = Integer.parseInt(s_age);
String sex = request.getParameter("sex");
User user = new User();
user.setId(id);
user.setPassword(passw);
user.setAge(age);
user.setSex(sex);
UserCl userCl = new UserCl();
if(userCl.addUser(user)){
request.getRequestDispatcher("success.jsp").forward(request, response);
}else{
request.getRequestDispatcher("failure.jsp").forward(request, response);
}
} catch (Exception e) {
e.printStackTrace();
// TODO: handle exception
}
}else if("select".equals(flag)){
try {
String id = request.getParameter("id");
String passw = request.getParameter("passw");
UserCl userCl = new UserCl();
User user = userCl.selectUser(id, passw);
if(user!=null){
request.setAttribute("user", user);
request.getRequestDispatcher("display.jsp").forward(request, response);
}else{
request.getRequestDispatcher("failure.jsp").forward(request, response);
}
} catch (Exception e) {
e.printStackTrace();
// TODO: handle exception
}
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doGet(request, response);
}
}
(4)UserCl.java
package com.dtg.model;
import java.sql.*;
import java.util.ArrayList;
public class UserCl {
Connection conn = null;
Statement sm = null; //prepareStatement,预处理
ResultSet rs = null;
boolean flag = false;
int pageSize = 3; // 页面大小
int pageNow = 1;//默认显示第一页
int rowCount = 0;//总记录数,从数据库中查询
int pageCount = 0; //页数,(rowCount/pageSize)+1
//关闭连接
public void closeConn() throws SQLException{
try {
if(rs != null){
rs.close();
rs = null;
}
if(sm!=null){
sm.close();
sm = null;
}
if(conn!=null){
conn.close();
conn = null;
}
} catch (Exception e) {
e.printStackTrace();
// TODO: handle exception
}
}
public boolean checkUser(String id, String passw){
try {
ConnDB conndb =new ConnDB();
conn = conndb.getConn();
sm = conn.createStatement();
rs = sm
.executeQuery("select password from user2 where id ='" + id
+ "'");
if (rs.next()) {
//确保用户名id是存在的
if (rs.getString(1).equals(passw)) {
//密码正确,用户合法
flag = true;
} else {
//密码不正确,用户不合法
flag = false;
}
} else {
//用户不存在
flag = false;
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}finally{
try {
this.closeConn();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return flag;
}
/**
* 得到分页的页数
* @return
*/
public int getPageCount(){
try {
conn = new ConnDB().getConn();
sm = conn.createStatement();
rs = sm.executeQuery("select count(*) from user2");
if (rs.next()) {
rowCount = rs.getInt(1);
}
// 计算pageCount
if (rowCount % pageSize == 0) {
pageCount = rowCount / pageSize;
} else {
pageCount = rowCount / pageSize + 1;
}
} catch (Exception e) {
// TODO: handle exception
}finally{
try {
this.closeConn();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return pageCount;
}
/**
* 取要分页显示的数据
*/
public ArrayList<User> getUserByPage(int pageNow){
ArrayList<User> al = new ArrayList<User>();
try {
conn = new ConnDB().getConn();
sm = conn.createStatement();
rs = sm.executeQuery("select top "+ pageSize+ " * from user2 where userId not in (select top "+ pageSize*(pageNow-1)+" userId from user2 order by userId) order by userId");
while(rs.next()){
User user = new User();
user.setUserId(rs.getInt(1));
user.setId(rs.getString(2));
user.setPassword(rs.getString(3));
user.setAge(rs.getInt(4));
user.setSex(rs.getString(5));
//添加user到动态数组中
al.add(user);
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}finally{
try {
this.closeConn();
} catch (Exception e2) {
e2.printStackTrace();
// TODO: handle exception
}
}
return al;
}
/**
* 删除用户
*/
public boolean delUser(String userId){
boolean b = false;
try {
conn = new ConnDB().getConn();
sm = conn.createStatement();
// 删除或更新几条,返回数字几
int a = sm.executeUpdate("delete from user2 where userId = '"+userId+"'");
if(a==1){
b = true;//删除成功
}
} catch (Exception e) {
e.printStackTrace();
// TODO: handle exception
}finally{
try {
this.closeConn();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return b;
}
/**
* 修改用户信心
*/
public boolean updateUser(User user,String userId){
boolean b = false;
try {
conn = new ConnDB().getConn();
sm = conn.createStatement();
int a = sm.executeUpdate("update user2 set password ='"+user.getPassword()+"',age='"+user.getAge()+"',sex='"+user.getSex()+"' where userId = '"+userId+"'");
if(a==1){
b = true;
}
} catch (Exception e) {
e.printStackTrace();
// TODO: handle exception
}
return b;
}
/**
* 注册新用户
*/
public boolean addUser(User user){
boolean b = false;
try {
conn = new ConnDB().getConn();
sm = conn.createStatement();
// 删除或更新几条,返回数字几
int a = sm.executeUpdate("insert into user2 (id,password,age,sex) values ('"+user.getId()+"','"+user.getPassword()+"','"+user.getAge()+"','"+user.getSex()+"')");
if(a==1){
b = true;
}
} catch (Exception e) {
e.printStackTrace();
// TODO: handle exception
}
return b;
}
/**
* 查找用户
*/
public User selectUser(String id, String passw){
User user = new User();
try {
conn = new ConnDB().getConn();
sm = conn.createStatement();
// 根据用户id和password检索用户
rs = sm.executeQuery("select id,age,sex from user2 where id='"+id+"' and password='"+passw+"'");
while(rs.next()){
user.setId(rs.getString(1));
user.setAge(rs.getInt(2));
user.setSex(rs.getString(3));
}
} catch (Exception e) {
e.printStackTrace();
// TODO: handle exception
}
return user;
}
}
(5)login_success.jsp
<script type="text/javascript">
<!--
function check(){
return window.confirm("您确定要注销吗?");
}
-->
</script>
</head>
<body bgcolor="#FFFFFF">
<%
String id = (String)session.getAttribute("id");
if(id==null){
//返回登陆界面(目前学过的内置对象response,request,out,session)
response.sendRedirect("login.jsp?err=1");
return ;
}
%>
<img src="img/logo.png">
<center>
<h2>
登陆成功 ,欢迎[<font color="red"><%=id %></font>]光临,<a href="/jsp1/index.jsp">返回重新登录</a>
</h2>
<hr>
<%
//接受用户想要显示的页面
String s_pageNow = (String)request.getAttribute("pageNow");
int pageNow = Integer.parseInt(s_pageNow);
//要显示的数据,用request来取
ArrayList<User> al = (ArrayList<User>)request.getAttribute("result");
// object -->String -->int
String s_pageCount = (String)request.getAttribute("pageCount");
int pageCount = Integer.parseInt(s_pageCount);
String []color = {"#b2d235","#f47920"};
//用表格显示
%>
<table border="1">
<tr bgcolor="#f47920"><td>userId</td><td>ID</td><td>PASSWORD</td><td>AGE</td><td>SEX</td>
<td>Delete</td><td>Update</td>
</tr>
<%
for(int i=0;i<al.size();i++){
User user = (User)al.get(i);
%>
<tr bgcolor="<%=color[i%2] %>"><td><%=user.getUserId() %></td><td><%=user.getId() %></td>
<td><%=user.getPassword() %></td>
<td><%=user.getAge() %></td><td><%=user.getSex() %></td>
<td><a οnclick="return check()" href="UserServlet?flag=del&userId=<%=user.getUserId() %>">Delete</a></td>
<td><a href="updateUser.jsp?userId=<%=user.getUserId() %>">Update</a></td>
</tr>
<%
}
%>
</table>
<%
//显示超链接
if(pageNow != 1){
out.print("<a href=UserServlet?flag=fy&pageNow="+(pageNow-1)+" >上一页</a>");
}
if(pageNow > 6 && pageNow <= (pageCount-4)){
for(int i=pageNow-5;i<=pageNow+4;i++){
out.println("<a href=UserServlet?flag=fy&pageNow="+i+">["+i+"]</a>");
}
}else if(pageNow >(pageCount-4) ){
for(int i=pageCount-9;i<=pageCount;i++){
out.println("<a href=UserServlet?flag=fy&pageNow="+i+">["+i+"]</a>");
}
}else{
for(int i=1;i<=10;i++){
//要是pageCount > 10 则不显示全部,只显示前10页的超链接
//for(int i=1;i<=pageCount;i++)
out.println("<a href=UserServlet?flag=fy&pageNow="+i+">["+i+"]</a>");
}
}
if(pageNow != pageCount){
out.print("<a href=UserServlet?flag=fy&pageNow="+(pageNow+1)+">下一页</a>");
}
%>
</center>
</body>
</html>
(6)updateUser.jsp
</head>
<body bgcolor="#FFFFFF">
<img src="img/logo.png">
<center>
<h2>请输入要修改的用户信息</h2>
<hr>
<form action="UserServlet?flag=update&userId=<%=request.getParameter("userId") %>" method="post">
密 码:
<input type="password" name="passw" />
<br>
年 龄:
<input type="text" name="age" />
<br>
性 别:
<input type="text" name="sex" />
<br>
<input type="submit" value="更改" />
<input type="reset" value="重置" />
<hr>
</form>
</center>
</body>
</html>