UserManager
刚刚学习servlet,打算学做一个小项目把前边学到的知识做一个总结.
由于只是实现了一些简单的功能,所以美工就凑合着看吧(美工其实也不太会).
首先项目整体架构如图
项目准备工作:
要用到mysql数据库,所以要导入
直接复制在webroot/web-inf/lib下
然后创建Users库,user表
CREATE DATABASE Users; USE Users; CREATE TABLE USER( id INT PRIMARY KEY AUTO_INCREMENT,//主键 username VARCHAR(32) NOT NULL,//用户名 email VARCHAR(64) NOT NULL,//邮箱 grade INT DEFAULT 1,//级别 PASSWORD VARCHAR(32) NOT NULL//密码 );
事先插入一些用户
INSERT INTO USER(username,email,PASSWORD) VALUES ("mahui","1130804967@sohu.com","123"), ("aaaa","1130804967@sina.com","123"), ("bbbb","1130804967@baidu.com","123"), ("cccc","1130804967@google.com","123"), ("dddd","1130804967@163.com","123");
1.LoginServlet.java
package com.mh.view; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class LoginServlet extends HttpServlet { private static final long serialVersionUID = 1L; public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset =UTF-8"); request.setCharacterEncoding("UTF-8"); PrintWriter out = response.getWriter(); out.println("<h1>登录界面<h1>"); out.println("<form action = '/UsersManager/LoginClServlet' method = 'post'>");//form表单提交到LoginClServlet.java out.println("I D:<input type = 'text' name = 'id'/><br/>"); out.println("密 码:<input type = 'password' name = 'password'/><br/>"); out.println("<input type = 'submit' value = 'Submit'/>"); out.println("</form>"); String errInfo =(String)request.getAttribute("err");//第一次该属性为null,什么都不显示 if(errInfo != null){ out.println("<font color = 'red'>"+errInfo+"<font>");//如果errinfo不为空,则输出错误信息 } } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } }
2.LoginClServlet.java(该servlet用于简易的处理用户登录信息)
package com.mh.controller; import java.io.IOException; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class LoginClServlet extends HttpServlet { private static final long serialVersionUID = 1L; public final static String URL = "jdbc:mysql://localhost:3306/Users";//建立连接 public final static String USER = "root";//用户 public final static String PASSWORD = "334400";//密码 public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); String id = request.getParameter("id");//获取id String pass = request.getParameter("password");//获取密码 Connection conn = null; PreparedStatement prep = null; ResultSet set = null; try{ Class.forName("com.mysql.jdbc.Driver");//加载驱动 conn = DriverManager.getConnection(URL,USER,PASSWORD);//获得与数据库的连接对象conn prep = conn.prepareStatement("select * from User where id = ? and password = ?");//预处理语句 prep.setString(1,id);//第一个?赋值 prep.setString(2,pass);//第二个?赋值 set = prep.executeQuery();//执行查询 if(set.next()){//如果结果集合存在用户 request.getRequestDispatcher("/MainFrame").forward(request,response);//转发到/MainFrame主页面 }else{ request.setAttribute("err", "用户ID或密码有误!");//如果不存在该用户,则设置err属性的信息 request.getRequestDispatcher("/LoginServlet").forward(request, response);//转发到登录界面 } }catch(Exception e){ e.printStackTrace(); }finally{ //以下为关闭资源 if(set != null){ try { set.close(); } catch (SQLException e) { e.printStackTrace(); } } if(prep != null){ try { prep.close(); } catch (SQLException e) { e.printStackTrace(); } } if(conn != null){ try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request,response); } }
3.MainFrame.java
package com.mh.view; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class MainFrame extends HttpServlet { private static final long serialVersionUID = 1L; public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); request.setCharacterEncoding("utf-8"); PrintWriter out = response.getWriter(); //这里没什么好讲的,都是一些链接 out.println("<h1>登陆成功<h1>"); out.println("<h3>请选择一下操作<h3>"); out.println("<a href = '/UsersManager/ManageUsers'>管理用户</a>");//跳转到管理界面 out.println("<a href = '/UsersManager/AddUserMain'>添加用户</a>");//添加用户 out.println("<a href = '/UsersManager/SelectUsers'>查询用户</a>");//查询 out.println("<a href = '/UsersManager/LoginServlet'>安全退出</a>");//退出 } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request,response); } }
4.跳转到管理用户页面,这里边是逻辑比较复杂的一个页面,因为页面和逻辑没有实现分离,还有里边使用了分页,mysql的分页是依靠limit来实现
package com.mh.view; import java.io.IOException; import java.io.PrintWriter; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class ManageUsers extends HttpServlet { private static final long serialVersionUID = 1L; public final static String URL = "jdbc:mysql://localhost:3306/Users"; public final static String USER = "root"; public final static String PASSWORD = "334400"; public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=utf-8"); PrintWriter out = response.getWriter(); //以下四行代码实现了跳转功能,document.getElementById('pageNow')首先获得你要跳转的页面,然后在本页面(_self参数控制)打开一个新的页面,并把page当成参数传给本页面 out.print("<script type = 'text/javascript' language = 'javascript'>"); out.print("function go(){var page = document.getElementById('pageNow');" + "window.open('/UsersManager/ManageUsers?page='+page.value,'_self');}"); out.print("</script>"); out.println("<h1>用户管理</h1><a href = '/UsersManager/MainFrame'>主页面</a><hr/>"); out.println("<table border = 1 width = 500px>"); out.println("<tr><th>ID</th><th>用户名</th><th>Email</th><th>级别</th></tr>"); Connection conn = null; PreparedStatement prep = null; ResultSet set = null; try{ Class.forName("com.mysql.jdbc.Driver"); conn = DriverManager.getConnection(URL,USER,PASSWORD); prep = conn.prepareStatement("select count(id) from User ");//获得总共有多少条记录,为分页做准备 set = prep.executeQuery(); set.next();//这里要注意,因为光标是指向集合第一条记录的前面,所以要执行next()方法 int rowCount = set.getInt(1);//把总数赋值给rowcount int pageSize = 3;//每页显示几条记录 int pageCount = (rowCount-1)/pageSize + 1;//总共有几页(这里用到了一个小算法) int pageCurr = 1;//当前页 String curr_Page = (String) request.getParameter("page");//这里是为了获取用户点击下边的第i页跳转到本页面提交的page参数 if(curr_Page != null){ pageCurr = Integer.parseInt(curr_Page);//第一次该参数为null,以后根据用户点击的页数而定 } prep.close();//先关闭 set.close(); String sql = "select * from User limit "+(pageCurr-1)*pageSize+ ","+pageSize;//这里分页用到了limit,使用limit (第几页-1)*每页显示的记录,每页显示记录数 prep = conn.prepareStatement(sql);//再次预处理新的sql set = prep.executeQuery();//执行 while(set.next()){//这里得到的set结果集是一个集合,所以使用while循环 out.println("<tr><td>"+set.getInt(1)+"</td><td>" +set.getString(2)+"</td><td>"+set.getString(3) +"</td><td>"+set.getString(4)+"</td></tr>"); } out.println("</table><br/>"); if(pageCurr != 1){ out.print("<a href = '/UsersManager/ManageUsers?page="+(pageCurr-1)+"'>上一页 </a>"); } //这里是表格的下边把总页数以for循环的方式创建超链接 for(int i = 1; i <= pageCount; i++){////如果不等于第一页,则显示,否则隐藏 out.print("<a href = '/UsersManager/ManageUsers?page="+i+"'><"+i+"></a>"); } if(pageCurr != pageCount){//如果不等于最后一页,则显示,否则隐藏 out.print("<a href = '/UsersManager/ManageUsers?page="+(pageCurr+1)+"'>下一页 </a>"); } out.print("当前页"+pageCurr+"/总页数"+pageCount); //下边是一个跳转功能,要用到javascript,给按钮增加一个点击事件,一点击该按钮,则调用go()方法,该方法在代码的头部 out.print("<br/>跳转到"); out.print("<input type = 'text' size = '20px' id = 'pageNow'/>"); out.print(" <input type = 'button' value = 'GO' onclick = 'go()'/>"); }catch(Exception e){ e.printStackTrace(); }finally{ //关闭资源 if(set != null){ try { set.close(); } catch (SQLException e) { e.printStackTrace(); } } if(prep != null){ try { prep.close(); } catch (SQLException e) { e.printStackTrace(); } } if(conn != null){ try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request,response); } }
5.AddUserMain.java 没什么好说的
package com.mh.view; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class AddUserMain extends HttpServlet { private static final long serialVersionUID = 1L; public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=utf-8"); PrintWriter out = response.getWriter(); out.print("<h1>添加用户</h1><br/><hr/>"); out.print("<form action = '/UsersManager/AddUserHandle' method = 'post'>Name:<input type = 'text' name = 'name'/><br/>"); out.print("Email:<input type = 'text' name = 'email'/><br/>"); out.print("PassWord:<input type = 'password' name = 'password'/><br/>"); out.print("<input type = 'submit' value = 'Submit'/>"); out.print("</form>"); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request,response); } }
6.AddUserHandle.java
package com.mh.controller; import java.io.IOException; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class AddUserHandle extends HttpServlet { private static final long serialVersionUID = 1L; public final static String URL = "jdbc:mysql://localhost:3306/Users"; public final static String USER = "root"; public final static String PASSWORD = "334400"; public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=utf-8"); String username = new String(request.getParameter("name").getBytes("ISO-8859-1"),"UTF-8") ;//获取用户名,这样写是为了用户输入的中文乱码 String email = request.getParameter("email");//获取邮箱 String password = request.getParameter("password");//获取密码 int row = 0; Connection conn = null; PreparedStatement prep = null; ResultSet set = null; try{ Class.forName("com.mysql.jdbc.Driver"); conn = DriverManager.getConnection(URL,USER,PASSWORD); prep = conn.prepareStatement("insert into User (username,email,password)values(?,?,?)");//预处理 prep.setString(1,username);//赋值 prep.setString(2,email); prep.setString(3, password); row = prep.executeUpdate();//执行更新,返回一个整数 if(row != 0){//插入成功返回到ManageUsers.java request.getRequestDispatcher("/ManageUsers").forward(request,response); }else{ //录入失败返回本界面 request.getRequestDispatcher("/AddUserMain").forward(request, response); } }catch(Exception e){ e.printStackTrace(); }finally{ //关闭资源 if(set != null){ try { set.close(); } catch (SQLException e) { e.printStackTrace(); } } if(prep != null){ try { prep.close(); } catch (SQLException e) { e.printStackTrace(); } } if(conn != null){ try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request,response); } }
7.SelectUsers.java
package com.mh.view; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class SelectUsers extends HttpServlet { private static final long serialVersionUID = 1L; public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=utf-8"); PrintWriter out = response.getWriter(); out.print("<h1>查找用户</h1><br/><hr/>"); out.print(" <a href = '/UsersManager/MainFrame'>主页面</a>"); out.print("<form action = '/UsersManager/SelectHandle' method = 'post'>");//跳转到SelectHandle.java out.print("请输入关键字 <input type = 'text' size = '10px' name = 'key'/>"); out.print(" <input type = 'submit' value = '查找'/>"); out.print("</form>"); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request,response); } }
8.SelectHandle.java
package com.mh.controller; import java.io.IOException; import java.io.PrintWriter; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class SelectHandle extends HttpServlet { private static final long serialVersionUID = 1L; public final static String URL = "jdbc:mysql://localhost:3306/Users"; public final static String USER = "root"; public final static String PASSWORD = "334400"; public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=utf-8"); PrintWriter out = response.getWriter(); String key = new String(request.getParameter("key").getBytes("ISO-8859-1"),"UTF-8") ; Connection conn = null; PreparedStatement prep = null; ResultSet set = null; try{ Class.forName("com.mysql.jdbc.Driver"); conn = DriverManager.getConnection(URL,USER,PASSWORD); prep = conn.prepareStatement("select * from User where username like ?");//模糊查询username prep.setString(1,"%"+key+"%");//模糊查询格式 set = prep.executeQuery(); out.print("<h1>查询结果</h1><br/><hr/>"); out.print(" <a href = '/UsersManager/SelectUsers'>返回</a>"); out.println("<table border = 1 width = 500px>"); out.println("<tr><th>ID</th><th>用户名</th><th>Email</th><th>级别</th></tr>"); while(set.next()){//返回集合,遍历 out.println("<tr><td>"+set.getInt(1)+"</td><td>" +set.getString(2)+"</td><td>"+set.getString(3) +"</td><td>"+set.getString(4)+"</td></tr>"); } out.println("</table><br/>"); }catch(Exception e){ e.printStackTrace(); }finally{ if(set != null){ try { set.close(); } catch (SQLException e) { e.printStackTrace(); } } if(prep != null){ try { prep.close(); } catch (SQLException e) { e.printStackTrace(); } } if(conn != null){ try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request,response); } }