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);
- }
- }
UserManager的更多相关文章
- CoreCRM 开发实录 —— 单元测试之 Mock UserManager 和 SignInManager
单元测试的核心就是:只测试眼前的逻辑.这就要求所有的依赖项都要使用仿类来代替,也就是所谓的 Mock Object.在测试 ProfileRepository 和 AccountController ...
- 解决EJB本地调用“java.lang.ClassCastException: $Proxy96 cannot be cast to com.tgb.ejb.UserManager”异常
EJB本地调用方式:把Webclient和EJB服务端部署到同一个JBoss,client和server通过一个JVM进行通信. Web客户端本地调用时.需引用EJB服务端打包的jar,不需引用JBo ...
- InvalidOperationException: Unable to resolve service for type 'Microsoft.AspNetCore.Identity.UserManager`1[Microsoft.AspNetCore.Identity.IdentityUser]'
在新建asp.net core 应用后, 添加了自定义的ApplicationDbContext 和ApplicationUser ,并添加了Identity认证后, 会出现 InvalidOpera ...
- win10系统中UserManager 总是被禁用怎么解决?
RT,也就是提示win10开始菜单和cortana无法工作.升级win10后一直被这个问题困扰,论坛也见有人发帖求助这类问题,百度了方法打开任务管理器进入服务更改User Manager启动类型为自动 ...
- .NET Core中的认证管理解析
.NET Core中的认证管理解析 0x00 问题来源 在新建.NET Core的Web项目时选择“使用个人用户账户”就可以创建一个带有用户和权限管理的项目,已经准备好了用户注册.登录等很多页面,也可 ...
- ASP.NET Core 之 Identity 入门(三)
前言 在上一篇文章中,我们学习了 CookieAuthentication 中间件,本篇的话主要看一下 Identity 本身. 最早2005年 ASP.NET 2.0 的时候开始, Web 应用程序 ...
- 从Membership 到 .NET4.5 之 ASP.NET Identity
我们前面已经讨论过了如何在一个网站中集成最基本的Membership功能,然后深入学习了Membership的架构设计.正所谓从实践从来,到实践从去,在我们把Membership的结构吃透之后,我们要 ...
- 年度巨献-WPF项目开发过程中WPF小知识点汇总(原创+摘抄)
WPF中Style的使用 Styel在英文中解释为”样式“,在Web开发中,css为层叠样式表,自从.net3.0推出WPF以来,WPF也有样式一说,通过设置样式,使其WPF控件外观更加美化同时减少了 ...
- [Android]使用Dagger 2来构建UserScope(翻译)
以下内容为原创,欢迎转载,转载请注明 来自天天博客:http://www.cnblogs.com/tiantianbyconan/p/6237731.html 使用Dagger 2来构建UserSco ...
随机推荐
- 梳理下Cordova的热更新
公司的大部分都是Hybrid 产品,也就是混合开发,所以比较重要的一个核心功能就是热更新了. 做这个功能的时候中间碰到不少坑,记录一下,比较简单,大致思想就是从服务器拉取JS文件替换掉本地对应文件 之 ...
- shiro权限控制
1.1 简介 Apache Shiro是Java的一个安全框架.目前,使用Apache Shiro的人越来越多,因为它相当简单,对比Spring Security,可能没有Spring Securi ...
- Docker(开课吧笔记)
1.Docker基本概念 Docker运行在Linux,需要git技能 docker官网解析 来源于容器又不仅仅是容器,第一个版本基于LXC,远远超过容器概念 交付时拿到的是镜像,直接run运 ...
- 使用Python对Access读写操作
学习Python的过程中,我们会遇到Access的读写问题,这时我们可以利用win32.client模块的COM组件访问功能,通过ADODB操作Access的文件. 1.导入模块 import win ...
- 6.Java集合总结系列:常见集合类的使用(List/Set/Map)
MARK 总结: Set.List 和 Map 可以看做集合的三大类. List集合是有序集合,集合中的元素可以重复,访问集合中的元素可以根据元素的索引来访问. Set集合是无序集合,集合中的元素不可 ...
- word-wrap: break-word;与word-break: break-all;文本自动换行
word-break:break-all和word-wrap:break-word都是能使其容器如DIV的内容自动换行它们的区别就在于:1,word-break:break-all 例如div宽200 ...
- sublimeText3插件安装
1,官方下载sublimeText 3(百度搜索) 2,安装成功后按Ctrl+`调出console 3,然后输入 import urllib.request,os; pf = 'Package Con ...
- Yum -userguide
Introduction Yum(Yellow dog Updater, Modified) is an automatic updater and package installer/remover ...
- Nest客户端的基本使用方法
通过Nuget安装好Nest的相关Dll,之后我们就可以开始了, 1.初始化Nest客户端 string indexName = "customer"; Uri uri = new ...
- 关于sql、mysql语句的模糊查询分类与详解,包括基本用法和mapper.xml文件里插入写法
欢迎猿类加qq:2318645572,共同学习进步 实际例子: ssm框架:service业务层->dao层->mappers.xml->junit/test测试 1:service ...