赞
踩
后台系统的所有界面图以及之前的准备工作欢迎看我之前的博文>3<
有任何问题欢迎下方评论=W=
①项目目录图1与图2
②登录模块图
③注册模块图
①Java Resources的src-->建立package,命名为filter-->创建一个DoFilter的java文件,具体代码如下
(PS.这个过滤器我也是仿照csdn一个老哥的做的,在此感谢这位老哥>3<)
- package filter;
-
- import java.io.IOException;
-
- import javax.servlet.Filter;
- import javax.servlet.FilterChain;
- import javax.servlet.FilterConfig;
- import javax.servlet.ServletException;
- import javax.servlet.ServletRequest;
- import javax.servlet.ServletResponse;
-
- public class DoFilter implements Filter {
-
- public DoFilter(){
- System.out.println("过滤器构造");
- }
- public void destroy() {
- System.out.println("过滤器销毁");
- }
- public void doFilter(ServletRequest request, ServletResponse response,FilterChain chain) throws IOException, ServletException {
- request.setCharacterEncoding("utf-8"); //将编码改为utf-8
- response.setContentType("text/html;charset=utf-8");
- chain.doFilter(request, response);
- }
-
- public void init(FilterConfig arg0) throws ServletException {
- System.out.println("过滤器初始化");
- }
-
- }
-
②在WebContent-->WEB-INF-->web.xml中,设置如下内容
- <?xml version="1.0" encoding="UTF-8"?>
- <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
- <display-name>MyBlog</display-name>
- <filter>
- <filter-name>Dofilter</filter-name>
- <filter-class>filter.DoFilter</filter-class>
- </filter>
- <filter-mapping>
- <filter-name>Dofilter</filter-name>
- <url-pattern>/*</url-pattern>
- </filter-mapping>
- <!-- 欢迎页,即进入项目的第一个界面 -->
- <welcome-file-list>
- <welcome-file>login.jsp</welcome-file>
- </welcome-file-list>
- </web-app>
①先载入JSTL的Jar包,在项目右键BuildPath-->Configure Build Path的Libraries里-->Add Jars-->选择目标Jar包
②为确保载入Jar包成功,应该在WebContent-->WEB-INF-->lib的文件夹中查看是否有如下内容,这次用的便是有jstl前缀的jar包
③在WebContent-->新建一个jsp文件,取名为base.jsp-->写入如下内容
(关于layui、bootstrap等框架资源百度即可,按照目录结构放入其中)
- <%@ page language="java" contentType="text/html; charset=UTF-8"
- pageEncoding="UTF-8"%>
- <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
- <c:set var="ctx" value="${pageContext.request.contextPath}"></c:set>
- <link rel="stylesheet" href="${ctx }/js/layui/css/layui.css">
- <script src="${ctx }/js/jquery-3.2.1.min.js"></script>
- <script src="${ctx }/js/layui/layui.js"></script>
- <script src="${ctx}/js/bootstrap/js/bootstrap.min.js"></script>
①逻辑分析(以下为我画的管理员登录业务流程图)
②详细的数据库之前的博文已经写了,为了更好阅读这里再写一次
建数据库,命名为blog-->建表,命名为dai_adm,设计表的字段如下
属性名 | 类型 | 长度 | 允许空 | 是否主键 | 说明 |
adm_id | tinyint | 4 | NOT NULL | 主键 | 管理员id、自增 |
adm_name | varchar | 20 | NOT NULL |
| 管理员名称 |
adm_password | varchar | 20 | NOT NULL |
| 管理员密码 |
③既然是登录,自然要与数据库进行对接,这里我使用的是mysql数据库,要求要加载好mysql的jar包,步骤同之前JSTL的Jar包设置步骤
3.1 在Java Resources的src下-->新建package,命名为util-->新建一个config.properties文件,内容如下
(由于我mysql是接入3306端口,数据库连接时使用的用户名是root,没有设置密码,所以这么设置,如果你有密码,pwd=你的密码)
- driverClass=com.mysql.jdbc.Driver
- url=jdbc:mysql://localhost:3306/blog?useUnicode=true&characterEncoding=utf-8&useSSL=false
- #mysql username
- user=root
- #mysql password
- pwd=
3.2 在Java Resources的src下-->util包中-->新建一个class文件,命名为DBUtil,代码如下
- package util;
-
-
- import java.io.InputStream;
- import java.sql.Connection;
- import java.sql.DriverManager;
- import java.sql.SQLException;
- import java.util.Properties;
-
- public class DBUtil {
- private static String driverClass;
- private static String url;
- private static String user;
- private static String pwd;
-
- //static block静态块
- static{
- //产生properties类的实例
- Properties prop = new Properties();
- //转换成文件流
- InputStream is = DBUtil.class.getClassLoader().getResourceAsStream("util/config.properties");
-
- try {
- prop.load(is);
- driverClass = prop.getProperty("driverClass").trim();
- url = prop.getProperty("url").trim();
- user = prop.getProperty("user").trim();
- pwd = prop.getProperty("pwd").trim();
- Class.forName(driverClass);
-
- //当前类的位置
- System.out.println(DBUtil.class.getResource(""));
- //当前类的根目录的位置
- System.out.println(DBUtil.class.getClassLoader().getResource(""));
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
-
- public static Connection getConnection(){
- // 数据库的连接
- Connection conn = null;
- try {
- conn = DriverManager.getConnection(url, user,pwd);
- } catch (SQLException e) {
- e.printStackTrace();
- }
- return conn;
- }
- public static void closeConnection(Connection conn) throws SQLException {
- conn.close();
- }
-
- }
④这个项目使用了MVC结构,登录模块也就是对管理员进行操作,这里先写pojo层,再写dao层
4.1 在src中-->新建一个package,命名为pojo-->新建一个class文件,命名为Adm,内容如下
- package pojo;
-
- public class Adm{
- private Integer adm_id;
- private String adm_name;
- private String adm_password;
-
- public Integer getAdm_id() {
- return adm_id;
- }
- public void setAdm_id(Integer adm_id) {
- this.adm_id = adm_id;
- }
- public String getAdm_name() {
- return adm_name;
- }
- public void setAdm_name(String adm_name) {
- this.adm_name = adm_name;
- }
- public String getAdm_passward() {
- return adm_password;
- }
- public void setAdm_passward(String adm_password) {
- this.adm_password = adm_password;
- }
- }
4.2 由于后来要做分页功能,所以还要封装一个类-->pojo包中-->新建一个class,命名为ChangePage,内容如下
- package pojo;
-
- public class ChangePage {
- private int page; //默认第一页
- private int limit; //默认一页10条数据
- private int startRow = (page-1)*limit;//mysql里语句随之发生改变
- private String sort;//排序字段
- private String order;//排序关键字
- public int getPage() {
- return page;
- }
- public void setPage(int page) {
- this.page = page;
- }
- public int getLimit() {
- return limit;
- }
- public void setLimit(int limit) {
- this.limit = limit;
- }
- public int getStartRow() {
- return (page-1)*limit;
- }
- public void setStartRow(int startRow) {
- this.startRow = startRow;
- }
- public String getSort() {
- return sort;
- }
- public void setSort(String sort) {
- this.sort = sort;
- }
- public String getOrder() {
- return order;
- }
- public void setOrder(String order) {
- this.order = order;
- }
- }
4.3 在src中-->新建一个package,命名为dao-->新建一个interface文件,命名为AdmDao,内容如下
- package dao;
-
- import java.util.ArrayList;
-
- import pojo.Adm;
-
- public interface AdmDao {
- //1.查询管理员,返回一个管理员类型 这是login里头的方法
- public Adm getAdm(String username,String password);
- //2查询所有的管理员
- public ArrayList<Adm> getAllAdm();
- //3.添加管理员
- public boolean insertAdm(String username,String pwd);
- //4.根据id删除管理员
- public boolean deleteAdm(int id);
- //5.修改管理员信息
- public boolean updateAdm(Adm a);
- //6.根据adm_name查询是否存在该用户,即id唯一,用户名唯一
- public boolean queryIsExist(String username);
- //7.根据id,查询一个管理员
- public Adm getOneAdm(int adm_id);
- //8 分页查询所有的管理员
- public ArrayList<Adm> getPageAdm(int page,int limit);
-
- }
4.4 写AdmDao的实现类,本应该放在不同的包里,我当时为了简便,依然放在了dao包
dao包-->新建class文件,命名为AdmDaoImpl-->实现AdmDao接口,代码如下
- package dao;
-
- import java.sql.Connection;
- import java.sql.PreparedStatement;
- import java.sql.ResultSet;
- import java.sql.SQLException;
- import java.util.ArrayList;
- import pojo.Adm;
- import pojo.ChangePage;
- import util.DBUtil;
-
- public class AdmDaoImpl implements AdmDao {
-
- // 分页方法
- @Override
- public ArrayList<Adm> getPageAdm(int page, int limit) {
- ArrayList<Adm> adm = new ArrayList<Adm>();
- Connection conn = DBUtil.getConnection();
- ChangePage cp = new ChangePage();
- cp.setLimit(limit);
- cp.setPage(page);
- int startRow = cp.getStartRow();
- String sql = "select * from dai_adm limit " + startRow + "," + limit + "";
- // 预编译
- try {
- PreparedStatement prep = conn.prepareStatement(sql);
- ResultSet rst = prep.executeQuery();
- while (rst.next()) {
- Adm ad = new Adm();
- ad.setAdm_id(rst.getInt(1));
- ad.setAdm_name(rst.getString("adm_name"));
- ad.setAdm_passward(rst.getString("adm_password"));
- adm.add(ad);
- }
- } catch (SQLException e) {
- e.printStackTrace();
- } finally {
- try {
- DBUtil.closeConnection(conn);
- } catch (SQLException e) {
- e.printStackTrace();
- }
- }
- return adm;
- }
-
- // 查询所有的管理员
- @Override
- public ArrayList<Adm> getAllAdm() {
- ArrayList<Adm> adm = new ArrayList<Adm>();
- Connection conn = DBUtil.getConnection();
- // 在数据库中添加记录
- String sql = "select * from dai_adm";
- // 预编译
- try {
- PreparedStatement prep = conn.prepareStatement(sql);
- ResultSet rst = prep.executeQuery();
- while (rst.next()) {
- Adm ad = new Adm();
- ad.setAdm_id(rst.getInt(1));
- ad.setAdm_name(rst.getString("adm_name"));
- ad.setAdm_passward(rst.getString("adm_password"));
- adm.add(ad);
- }
- } catch (SQLException e) {
- e.printStackTrace();
- } finally {
- try {
- DBUtil.closeConnection(conn);
- } catch (SQLException e) {
- e.printStackTrace();
- }
- }
- return adm;
- }
-
- @Override
- public Adm getAdm(String username, String password) {
- Adm a = null;
- Connection conn = DBUtil.getConnection();
- String sql = "select * from dai_adm where adm_name = ? and adm_password = ?";
- // 预编译
- PreparedStatement prep;
- try {
- prep = conn.prepareStatement(sql);
- prep.setString(1, username);
- prep.setString(2, password);
- ResultSet rst = prep.executeQuery();
- if (rst.next()) {
- System.out.println("啊啊啊,我是servlet,我已经查到信息了!!!");
- a = new Adm();
- a.setAdm_id(rst.getInt("adm_id"));
- a.setAdm_name(rst.getString("adm_name"));
- a.setAdm_passward(rst.getString("adm_password"));
- return a;
- } else {
- // System.out.println(username+","+password);
- }
- } catch (Exception e) {
- e.printStackTrace();
- } finally {
- try {
- DBUtil.closeConnection(conn);
- } catch (SQLException e) {
- e.printStackTrace();
- }
- }
- return a;
- }
-
- // 3.添加管理员
- @Override
- public boolean insertAdm(String username, String pwd) {
- Connection conn = DBUtil.getConnection();
- // 在数据库中添加记录
- String sql = "insert into dai_adm(adm_name,adm_password) values(?,?)";
- // 预编译
- PreparedStatement prep;
- try {
- prep = conn.prepareStatement(sql);
- prep.setString(1, username);
- prep.setString(2, pwd);
- prep.executeUpdate();
- return true;
- } catch (SQLException e) {
- e.printStackTrace();
- return false;
- } finally {
- try {
- DBUtil.closeConnection(conn);
- } catch (SQLException e) {
- e.printStackTrace();
- }
- }
- }
-
- @Override
- public boolean deleteAdm(int adm_id) {
- Connection conn = DBUtil.getConnection();
- // 在数据库中删除记录
- String sql = "delete from dai_adm where adm_id = ?";
- // 预编译
- PreparedStatement prep;
- try {
- prep = conn.prepareStatement(sql);
- prep.setInt(1, adm_id);
- prep.executeUpdate();
- return true;
- } catch (SQLException e) {
- e.printStackTrace();
- return false;
- } finally {
- try {
- DBUtil.closeConnection(conn);
- } catch (SQLException e) {
- e.printStackTrace();
- }
- }
- }
-
- @Override
- public boolean updateAdm(Adm a) {
- Connection conn = DBUtil.getConnection();
- // 在数据库中修改记录
- String sql = "update dai_adm set adm_name = ?,adm_password = ? where adm_id=?";
- // 预编译
- PreparedStatement prep;
- try {
- prep = conn.prepareStatement(sql);
- prep.setString(1, a.getAdm_name());
- prep.setString(2, a.getAdm_passward());
- prep.setInt(3, a.getAdm_id());
- prep.executeUpdate();
- return true;
- } catch (SQLException e) {
- e.printStackTrace();
- return false;
- } finally {
- try {
- DBUtil.closeConnection(conn);
- } catch (SQLException e) {
- e.printStackTrace();
- }
- }
- }
-
- @Override
- public boolean queryIsExist(String username) {
- Connection conn = DBUtil.getConnection();
- // 在数据库中查询记录
- String sql = "select * from dai_adm where adm_name = ?";
- // 预编译
- PreparedStatement prep;
- try {
- prep = conn.prepareStatement(sql);
- prep.setString(1, username);
- ResultSet rst = prep.executeQuery();
- if (rst.next()) {
- return true;
- } else {
- return false;
- }
-
- } catch (SQLException e) {
- e.printStackTrace();
-
- } finally {
- try {
- DBUtil.closeConnection(conn);
- } catch (SQLException e) {
- e.printStackTrace();
- }
- }
- return false;
- }
-
- @Override
- public Adm getOneAdm(int adm_id) {
- Adm a = null;
- Connection conn = DBUtil.getConnection();
- // 在数据库中修改记录
- String sql = "select * from dai_adm where adm_id = ?";
- // 预编译
- PreparedStatement prep;
- try {
- prep = conn.prepareStatement(sql);
- prep.setInt(1, adm_id);
- ResultSet rst = prep.executeQuery();
- a = new Adm();
- if (rst.next()) {
- a.setAdm_id(rst.getInt(1));
- a.setAdm_name(rst.getString("adm_name"));
- a.setAdm_passward(rst.getString("adm_password"));
- return a;
- }
-
- } catch (Exception e) {
- e.printStackTrace();
- } finally {
- try {
- DBUtil.closeConnection(conn);
- } catch (SQLException e) {
- e.printStackTrace();
- }
- }
- return a;
- }
-
- }
PS:这里有一个方法叫做getAllAdm(),还有一个方法叫做getPageAdm()。
前者我是用来获得总共有多少条管理员信息,后者我是用来获得分页信息与分页数据的,前者本来不需要在数据库上走那么多步骤。
因为ResultSet创建的对象可以使用last()方法跳到最后一条数据,然后再使用getRow()方法获得总数,这里建议大家按照这种方法。
⑤Service层:src-->新建package包,命名为servlet-->新建一个Servlet文件,命名为LoginServlet-->在URL mappings中改名为/login-->键入代码,如下
- package servlet;
-
- import java.io.IOException;
- import java.io.PrintWriter;
-
- import javax.servlet.ServletException;
- import javax.servlet.annotation.WebServlet;
- import javax.servlet.http.HttpServlet;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
-
- import dao.AdmDao;
- import dao.AdmDaoImpl;
- import pojo.Adm;
-
- /**
- * Servlet implementation class LoginServlet
- WebServlet里的/login就是刚刚改的URL Mappings的内容
- */
- @WebServlet("/login")
- public class LoginServlet extends HttpServlet {
- private static final long serialVersionUID = 1L;
-
- /**
- * @see HttpServlet#HttpServlet()
- */
- public LoginServlet() {
- super();
- // TODO Auto-generated constructor stub
- }
-
- /**
- * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
- * void getSession()方法相当于得到一个session对象,而void setAttribute()和String Attribute分别是对属性赋值和得到属性值的方法。
- */
- protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
- //response.getWriter().append("Served at: ").append(request.getContextPath());
- request.setCharacterEncoding("utf-8");
- response.setContentType("text/html;charset=utf-8");
-
- PrintWriter out = response.getWriter();
- String name = request.getParameter("username");
- String pwd = request.getParameter("pwd");
-
- AdmDao a = new AdmDaoImpl();
- Adm adm = a.getAdm(name , pwd);
- System.out.println(a.toString());
- if(adm!=null) {
- request.getSession().setAttribute("admin",adm);
- //重定向到成功页面
- response.sendRedirect("index.jsp");
- }else {
- //out.println("啊啊啊,我应该转发到失败的界面了");
- request.setAttribute("errMsg", "账号或密码错误,请重新输入信息!");
- //转发到login界面
- request.getRequestDispatcher("login.jsp").forward(request, response);
- return;
- }
-
- }
-
- /**
- * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
- */
- protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
- // TODO Auto-generated method stub
- doGet(request, response);
- }
-
- }
⑥WebContent-->新建jsp文件,命名为login.jsp-->键入代码,如下(使用了bootstrap和layui框架)
- <%@ page language="java" contentType="text/html; charset=UTF-8"
- pageEncoding="UTF-8"%>
- <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
- <html>
- <head>
- <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
- <link rel="stylesheet" href="./js/bootstrap/css/bootstrap.min.css">
- <link rel="stylesheet" href="./css/b_register.css">
- <%@include file="base.jsp"%>
- <title>登录</title>
- </head>
- <body>
- <%
- String errorMsg = (String) request.getAttribute("errMsg");
- if (errorMsg == null) {
- errorMsg = "";
- }
- %>
- <div id="box">
- <!-- action="${ctx}/login" -->
- <form id="myform" method="post" action="${ctx}/login">
- <div class="form-group">
- <label for="username">用户名</label> <input type="text"
- class="form-control" id="username" name="username"
- placeholder="请输入用户名:"> <span id="tip"
- style="color: red; margin-top: 20px;"><%=errorMsg%></span>
-
- </div>
-
- <div class="form-group">
- <label for="pwd">密码</label> <input type="password"
- class="form-control" id="pwd" name="pwd" placeholder="请输入密码:">
- </div>
-
- <button type="submit" class="btn btn-default btn_" id="btn">确定</button>
- <span style="margin-left: 250px;"></span> <a href="register.jsp"><button
- type="button" class="btn btn-default btn_">注册</button></a>
- </form>
- </div>
- <script type="text/javascript">
- layui.use([ 'layer' ], function() {
- layui.use([ 'form' ], function() {
- var form = layui.form;
- });
- // 点击提交执行的内容
- $('#username').blur(function() {
- //或者取长度
- if ($("#username").val() == "") {
- layer.msg("用户名不能输入为空哦!", {
- icon : 2
- });
- return;
- }
- });
- //点击提交,表单验证
- $('#btn').click(function() {
- if ($("#pwd").val() === "") {
- layer.msg("密码不能输入为空哦!", {
- icon : 2
- });
- return;
- }
- });
- });
- </script>
- </body>
- </html>
5.1 这里CSS目录如下(CSS并不重要,可以自己调整)
5.2 b_register的css样式如下
- @CHARSET "UTF-8";
- *{
- margin:0;
- padding:0;
- }
- body{
- background:url("./image/19.jpg") no-repeat;
- }
- #box{
- width:520px;
- height:400px;
- margin:200px auto;
- border-radius:20px;
- background-color: rgba(0, 0, 0, 0.3);
- box-shadow:1px 2px 5px black;
- padding: 1px;
- position:relative;
- background-image: url(./image/18.gif);
- opacity: 0.8;
- }
- #myform{
- margin:30px;
- }
- span{
- margin-left:100px;
- }
- .btn_{
- color:tomato;
- margin-top:30px;
- }
5.3 base的css样式如下
- @charset "UTF-8";
- body {
- width: 100%;
- height: 100%;
- background: url('../css/image/18.gif');
- overflow: hidden;
- }
-
- #box {
- height:550px;
- display:flex;
- align-items:center;
- justify-content:center;
- align-content:center;
-
- }
⑤当输入用户名或密码错误时,应该有的提示
⑥当输入密码正确时,应进入后台主界面,这里大家在WebContent里新建一个jsp文件,取名为index即可,这里放一张后台图,具体的下篇博文再更
①逻辑分析(以下为我画的管理员注册业务流程图,注册成功即自动跳转登录页面)
②Service层:这里主要就是首先判断你是否输入用户名,用户名输入过后判断是否这个用户名已经存在(用户名和id都是唯一的),然后再验证你两次密码是否相同,最后再进入注册。
所以说前台可以判断1是是否输入2是密码两次是否一致;
后台连接数据库后应该是进行了两个操作1是判断用户名是否存在2是进行往数据库里增加数据
2.1 src-->在servlet包里-->新建一个Servlet文件,命名为RegisterServlet-->在URL mappings中改名为/register-->键入代码,如下
- package servlet;
-
- import java.io.IOException;
- import java.io.PrintWriter;
-
- import javax.servlet.ServletException;
- import javax.servlet.annotation.WebServlet;
- import javax.servlet.http.HttpServlet;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
-
- import dao.AdmDao;
- import dao.AdmDaoImpl;
-
- /**
- * Servlet implementation class RegisterServlet
- WebServlet里的/register就是刚刚改的URL Mappings的内容
- */
- @WebServlet("/register")
- public class RegisterServlet extends HttpServlet {
- private static final long serialVersionUID = 1L;
-
- /**
- * @see HttpServlet#HttpServlet()
- */
- public RegisterServlet() {
- super();
- // TODO Auto-generated constructor stub
- }
-
- /**
- * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
- */
- protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
- String result = "false";
- PrintWriter writer = null;
- try {
- PrintWriter out = response.getWriter();
- //1.接收参数
- String username = request.getParameter("username");
- String pwd = request.getParameter("pwd");
- AdmDao a = new AdmDaoImpl();
- boolean flag= a.insertAdm(username,pwd);
- if(flag){
- result = "true";
- }
- writer = response.getWriter();
- writer.write(result);
- }catch(Exception e) {
- e.printStackTrace();
- }finally {
- writer.flush();
- writer.close();
- }
-
-
- }
-
- /**
- * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
- */
- protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
- // TODO Auto-generated method stub
- doGet(request, response);
- }
-
- }
2.2 src-->在servlet包里-->新建一个Servlet文件,命名为QueryAdmIsExist-->在URL mappings中改名为/isExist-->键入代码,如下
- package servlet;
-
- import java.io.IOException;
- import java.io.PrintWriter;
-
- import javax.servlet.ServletException;
- import javax.servlet.annotation.WebServlet;
- import javax.servlet.http.HttpServlet;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
-
- import dao.AdmDao;
- import dao.AdmDaoImpl;
-
- /**
- * Servlet implementation class QueryAdmIsExist
- */
- @WebServlet("/isExist")
- public class QueryAdmIsExist extends HttpServlet {
- private static final long serialVersionUID = 1L;
-
- /**
- * @see HttpServlet#HttpServlet()
- */
- public QueryAdmIsExist() {
- super();
- // TODO Auto-generated constructor stub
- }
-
- /**
- * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
- */
- protected void doGet(HttpServletRequest request, HttpServletResponse resp) throws ServletException, IOException {
- request.setCharacterEncoding("utf-8");
- resp.setCharacterEncoding("utf-8");
- resp.setContentType("text/html;charset=utf-8");
- //根据姓名查询用户是否存在 改的更完善了一点
- String result = "false";
- PrintWriter writer = null;
- try {
- String username = request.getParameter("username");
- AdmDao a = new AdmDaoImpl();
- boolean flag = a.queryIsExist(username);
- if(flag==true) {
- result = "true";
- }
- writer = resp.getWriter();
- writer.write(result);
- } catch (Exception e) {
- e.printStackTrace();
- }finally {
- writer.flush();
- writer.close();
- }
-
- }
-
- /**
- * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
- */
- protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
- // TODO Auto-generated method stub
- doGet(request, response);
- }
-
- }
③在WebContent下-->新建jsp文件,命名为register.jsp-->键入代码,如下(这里使用的是ajax,和上面登录模块不一样,注意区别)
- <%@ page language="java" contentType="text/html; charset=UTF-8"
- pageEncoding="UTF-8"%>
- <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
- <html>
- <head>
- <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
- <link rel="stylesheet" href="./js/bootstrap/css/bootstrap.min.css">
- <link rel="stylesheet" href="./css/b_register.css">
- <%@include file="base.jsp"%>
- <title>注册</title>
- </head>
- <body>
- <div id="box">
- <form id="myform" method="post">
- <div class="form-group">
- <label for="username">用户名</label>
- <input type="text" class="form-control" id="username" name="username" placeholder="请输入用户名:">
- <span id="tip" style="color:red;margin-top:20px;"></span>
- </div>
-
- <div class="form-group">
- <label for="pwd">密码</label>
- <input type="password" class="form-control" id="pwd" name="pwd" placeholder="请输入密码:">
- </div>
- <div class="form-group">
- <label for="conFirmPwd">确认密码</label>
- <input type="password" class="form-control" id="conFirmPwd" name="conFirmPwd" placeholder="请再次输入密码:">
- </div>
- <button type="button" class="btn btn-default btn_" id = "btn">提交</button>
- <span style="margin-left:250px;"></span>
- <a href="login.jsp"><button type="button" class="btn btn-default btn_">返回</button></a>
- </form>
- </div>
- </body>
- <script>
- layui.use([ 'layer' ], function() {
- /* alert(0); */
- layui.use([ 'form' ], function() {
- var form = layui.form;
- });
- var isOk = false;
- // 点击提交执行的内容
- $('#username').blur(function() {
- //或者取长度
- if ($("#username").val() == "") {
- layer.msg("不能输入为空哦!", {
- icon : 2
- });
- return;
- }else {
- $.post('isExist',
- {
- username : $('#username').val()
- },
- function(result) {
- //alert(typeof result);
- if(result=="true"){
- //alert(1);
- isOk = false;
- //利用jquery对元素设置样式
- $('#username').css("border", "1px solid red");
- //html() 设置标签之间的 内容
- $('#tip').html('该用户已存在');
- $('#tip').css("color", "red");
- return;
- }else{
- //alert(2);
- isOk = true;
- //利用jquery对元素设置样式
- $('#username').css("border", "1px solid gray");
- //html() 设置标签之间的 内容
- $('#tip').html('该用户名可用');
- $('#tip').css("color", "green");
- }
-
- }, "text");
- }
- });
- //点击提交,表单验证
- $('#btn').click(function() {
- if (!isOk) {
- return;
- }
- if($("#pwd").val() !== $("#conFirmPwd").val()){
- layer.msg("两次密码输入不同!",{
- icon : 2
- });
- return;
- }
- //提交表单
- $.post("register",//后台地址
- {
- username: $("#username").val(),
- pwd:$("#pwd").val(),
- },//需要提交到后台的数据
- function(result){
- //alert(typeof result);
- //alert(result);
- if (result) {
- //添加成功
- layer.msg("注册成功", {
- icon : 1
- });
- window.location.href = "login.jsp";
- }else{
- layer.msg("注册失败",{
- icon : 2
- });
- // 这里使用JQuery实现会有问题
- document.getElementById("myform").reset();
- $('#tip').html("");
- }
- },
- "json");
- //清空表单
- });
- });
- </script>
- </html>
④注册时用户名存在或可用的区别图片如下
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。