代码改变世界

JSP 登录与注册的小案例

2016-12-24 17:31  甘雨路  阅读(1361)  评论(0编辑  收藏  举报
<?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" id="WebApp_ID" version="3.0">
  <servlet>
       <servlet-name>Register</servlet-name>
    <servlet-class>com.zr.homework.servlet.Register</servlet-class>
  </servlet>
  
  <servlet>
    <servlet-name>LoginServlet</servlet-name>
    <servlet-class>com.zr.homework.servlet.LoginServlet</servlet-class>
  </servlet>


  <servlet-mapping>
    <servlet-name>Register</servlet-name>
    <url-pattern>/Register</url-pattern>
  </servlet-mapping>
  <servlet-mapping>
    <servlet-name>LoginServlet</servlet-name>
    <url-pattern>/LoginServlet</url-pattern>
  </servlet-mapping>
  



</web-app>
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
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 'index.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>
        登陆成功<br>
  </body>
</html>
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>

    
    <title>登录页面</title>
  
      <script type="text/javascript">
          function checkName(){
              // 获取相应标签
              var name = document.getElementsByName("name")[0];
              // 获取下一个兄弟节点
              var userTip = name.nextSibling;
              userTip.style.color="red";
              // 判断用户名是否为空,空提示错误
              if(name.value=="" || name.value==null){
                  userTip.innerHTML = "用户名不能为空";
              }else{
                  var request = new XMLHttpRequest();
                  var method = "GET";
                  var url = "LoginServlet?name="+name.value;
                  request.open(method, url, true, null, null);
                  request.send(null);
                  request.onreadystatechange = function(){
                      if(request.readyState==4){
                          if(request.status==200 || request.status==304){
                              userTip.innerHTML = request.responseText;
                          }
                      }
                  };
              };

          }
          
          function checkPwd(){
              // 获取相应标签
              var name = document.getElementsByName("password")[0];
              // 获取下一个兄弟节点
              var userTip = name.nextSibling;
              userTip.style.color="red";
              // 判断用户名是否为空,空提示错误
              if(name.value=="" || name.value==null){
                  userTip.innerHTML = "密码不能为空";
              }else{
                  userTip.innerHTML = "";
              }
          }
          
          
      </script>

  </head>
  
  <body>

       <h1>登录</h1>
       <form action="LoginServlet" method="post">
           用户名:<input type="text" name="name" onblur="checkName()" value="${param.name }"><span></span><br><br>
           密码:<input type="password"  name="password" onblur="checkPwd()" value="${param.password }"><span></span><br><br>
           <input type="submit" value="登录" >
       </form>


  </body>
</html>
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    
    <title>注册页面</title>
    
    
    <script type="text/javascript" src="js/jqeury/jquery-3.1.0.min.js"></script>
    <script type="text/javascript" src="js/register.js"></script>
    
  </head>
  
  <body>
    

    <form action="Register" method="post">
        用户名:<input type="text" id="name" name="name"><span></span><br><br>
           密码:<input type="password" att="one" name="password"  placeholder="3到15位字母和数字"><span></span><br><br>
           确认密码:<input type="password" att="two" ><span></span><br><br>
           邮箱:<input type="text" class="email" name="email"><span></span><br><br>
           身份证号:<input type="text" class="IDCard" name="IDCard"><span></span><br><br>
           出生年月日:<input type="text"  readonly="readonly" name="birthday"><span></span><br><br>
           <input type="submit" value="提交" onclick="return checkRegister()">
    </form>

  </body>
</html>
$(function(){
    $("span").css("color","red");
            
    $("#name").blur(function(){
        
        var value = $("#name").val();
        //如果为空,提示不能为空,否则清除提示信息
        if(value==null || value==""){
            $("#name+span").html("用户名不能为空");
        }else{
            $.post("Register",{"name":value,"action":"requery"},function(data){
                    var isRegistered = eval("("+data+")");
                    if(isRegistered==true){
                        $("#name+span").html("该用户已被注册");

                    }else{
                        $("#name+span").html("");
                    }
                },"text");
            
        }
        
        $("input[att=one]").blur(function(){
            var value = $("input[att=one]").val();
            //如果为空,提示不能为空,否则清除提示信息
            if(value==null || value==""){
                $("input[att=one]+span").html("密码不能为空");
            }else{
                $("input[att=one]+span").html("");
            }
            
        });
        $("input[att=two]").blur(function(){
            var value = $("input[att=two]").val();
            //如果为空,提示不能为空,否则清除提示信息
            if(value==null || value==""){
                $("input[att=two]+span").html("确认密码不能为空");
            }else{
                $("input[att=two]+span").html("");
            }
            
        });
        $(".email").blur(function(){
            var value = $(".email").val();
            //如果为空,提示不能为空,否则清除提示信息
            if(value==null || value==""){
                $(".email+span").html("邮箱不能为空");
            }else{
                $(".email+span").html("");
            }
            
        });
        
        $(".IDCard").blur(function(){
            var value = $(".IDCard").val();
            //如果为空,提示不能为空,否则清除提示信息
            if(value==null || value==""){
                $(".IDCard+span").html("身份证号不能为空");
            }else{
                $(".IDCard+span").html("");
            }
            // 从身份证号中截取生日
            var str = value.substring(6,14);
            var year = str.substring(0,4);
            var month = str.substring(4,6);
            var day = str.substring(6,8);
            var birthday = year+"-"+month+"-"+day;
            $("input[readonly=readonly]").val(birthday);
            
        });
    });
    
    
});



function checkRegister(){
    //检查参数是否为空
    var value1 = $("#name").val();
    if(value1==null || value1==""){
        $("#name+span").html("用户名不能为空");
        return false;
    }
    
    
    var value2 = $("input[att=one]").val();
    if(value2==null || value2==""){
        $("input[att=one]+span").html("密码不能为空");
        return false;
    }
    var value3 = $("input[att=two]").val();
    if(value3==null || value3==""){
        $("input[att=two]+span").html("确认密码不能为空");
        return false;
    }
    var value4 = $(".email").val();
    if(value4==null || value4==""){
        $(".email+span").html("邮箱不能为空");
        return false;
    }
    var value5 = $(".IDCard").val();
    if(value5==null || value5==""){
        $(".IDCard+span").html("身份证号不能为空");
        return false;
    }
    //检查密码是否正确(暂时不处理,密码的正则表达式)
    var pwdIsRight = false;
    // 3到15位字母和数字
    var reg1 = /^[a-zA-Z0-9]{3,15}$/;
    // 包含字母
    var reg2 = /[a-zA-Z]/;
    // 包含数字
    var reg3 = /[0-9]/;
    if(reg1.test(value2)&&reg2.test(value2)&&reg3.test(value2)){
        $("input[att=one]+span").html("");
        pwdIsRight = true;
    }else{
        $("input[att=one]+span").html("密码不正确");
        return false;
    }

    
    //检查密码与确认密码是否相同
    var isEqual = false;
    if(value2==value3){
        isEqual = true;
        $("input[att=one]+span").html("");
    }else{
        $("input[att=one]+span").html("密码不匹配");
        return false;
    }
    // 检查邮箱是否正确
    var emailIsRight = false;
    var regEmail =     /^([a-z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})$/;
    if(regEmail.test(value4)){
        $(".email+span").html("");
        emailIsRight = true;
    }else{
        $(".email+span").html("邮箱不正确");
        return false;
    }
    var IDIsRight = false;
    // 18位数字
    var regID = /^[0-9]{18}$/;
    if(regID.test(value5)){
        IDIsRight = true;
        $(".IDCard+span").html("");
    }else{
        $(".IDCard+span").html("身份证号不正确");
        return false;
    }
    //如果全都正确就返回true,否则返回false
    if(pwdIsRight==true && isEqual==true && emailIsRight==true && IDIsRight==true){
        
        return true;
    }
    return false;
}
<?xml version="1.0" encoding="UTF-8"?>

<!-- c3p0-config.xml文件配置 -->

<c3p0-config>
    <named-config name="getconnection">
        <!-- 基本配置 -->
        <property name="user">LF</property>
        <property name="password">LF</property>
        <property name="jdbcUrl">jdbc:oracle:thin:@192.168.10.105:1521:orcl</property>
        <property name="driverClass">oracle.jdbc.driver.OracleDriver</property>
        <!-- 配置初始值 -->
        <property name="initialPoolSize">16</property>
        <property name="maxPoolSize">25</property>
        <property name="minPoolSize">10</property>
    </named-config>
</c3p0-config>
package com.zr.homework.utils;

import java.sql.Connection;
import java.sql.SQLException;

import javax.sql.DataSource;

import com.mchange.v2.c3p0.ComboPooledDataSource;

public class JdbcUtils {

    
    /**
     * 获取数据库连接
     * @return
     */
    public static Connection getConnection() {
        DataSource ds = new ComboPooledDataSource("getconnection");
        Connection connection = null;
        try {
            connection = ds.getConnection();
            return connection;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

}
package com.zr.homework.pojo;

public class Person {
    private String name;//用户名
    private String password;//密码
    private String email;//邮箱
    private String ID;//身份证
    private String birthday;//出生年月日
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
    public String getID() {
        return ID;
    }
    public void setID(String iD) {
        ID = iD;
    }
    public String getBirthday() {
        return birthday;
    }
    public void setBirthday(String birthday) {
        this.birthday = birthday;
    }
    public Person() {
        super();
    }
    public Person(String name, String password, String email, String iD,
            String birthday) {
        super();
        this.name = name;
        this.password = password;
        this.email = email;
        ID = iD;
        this.birthday = birthday;
    }
    @Override
    public String toString() {
        return "Person [name=" + name + ", password=" + password + ", email="
                + email + ", ID=" + ID + ", birthday=" + birthday + "]";
    }
    
    
}
package com.zr.homework.servlet;

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;

import com.zr.homework.UserDao.impl.UserDaoImpl;
import com.zr.homework.UserServiceImpl.UserServiceImpl;
import com.zr.homework.pojo.Person;
/**
 * 
 * @author lf
 *
 */
public class LoginServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        /*System.out.println("LoginServlet...doGet...");*/
        resp.setCharacterEncoding("utf-8");
        String name = req.getParameter("name");
        UserServiceImpl impl = new UserServiceImpl();
        Person p = new Person(name, null, null, null, null);
        boolean had = impl.requeryUserService(p);
        System.out.println(had);
        if(had){
            resp.getWriter().print("");
        }else{
            resp.getWriter().print("该用户不存在");
        }
        
    }
    
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
        System.out.println("LoginServlet...doPost...");
        String name = request.getParameter("name");
        String password = request.getParameter("password");
        System.out.println(name+","+password);
        Person p = new Person(name, password, null, null, null);
        UserServiceImpl impl = new UserServiceImpl();
        boolean success = impl.loginService(p);
        if (success) {
            response.sendRedirect(request.getContextPath()+"/index.jsp");
        }else {
            request.getRequestDispatcher("/login.jsp").forward(request, response);
        }
        
    }

}
package com.zr.homework.servlet;

import java.io.IOException;






import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.zr.homework.UserDao.impl.UserDaoImpl;
import com.zr.homework.UserService.UserService;
import com.zr.homework.UserServiceImpl.UserServiceImpl;
import com.zr.homework.pojo.Person;

public class Register extends HttpServlet {

    private static final long serialVersionUID = 1L;
    
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        System.out.println("doGet...");
    }
    

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        System.out.println("Register...doPost...");
        UserServiceImpl impl = new UserServiceImpl();
        
        String name = request.getParameter("name");
        String action = request.getParameter("action");
        // 检查是查询还是注册
        if("requery".equals(action)){
            
            Person p = new Person(name, null, null, null, null);
            boolean isExited = impl.requeryUserService(p);
            response.getWriter().print(isExited);
        }else{
            System.out.println("注册用户");
            //获取相应的值
            String username = request.getParameter("name");
            String password = request.getParameter("password");
            String email = request.getParameter("email");
            String IDCard = request.getParameter("IDCard");
            String birthday = request.getParameter("birthday");
            System.out.println("birthday:"+birthday);
            Person person = new Person(username, password, email, IDCard, birthday);
            System.out.println(person);
            // 注册服务
            boolean isSuccess = impl.addUserService(person);
            // 如果注册成功,重定向到登录页面,否则重定向到错误页面
            if(isSuccess){
                response.sendRedirect(request.getContextPath()+"/login.jsp");
            }else {
                response.sendRedirect(request.getContextPath()+"/error.jsp");
            }
        }
    }

}
package com.zr.homework.UserDao;

import java.util.List;

import com.zr.homework.pojo.Person;

/**
 * 
 * @author lf
 *
 */
public interface UserDao {
    /**
     * 查询
     * @param p 用户
     * @return
     */
    public boolean requeryUser(Person p);
    /**
     * 添加用户
     * @param p 用户
     * @return
     */
    public boolean addUser(Person p);
    /**
     * 用户登录
     * @param p
     * @return
     */
    public boolean userLogin(Person p);
}
package com.zr.homework.UserDao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.zr.homework.UserDao.UserDao;
import com.zr.homework.pojo.Person;
import com.zr.homework.utils.JdbcUtils;

public class UserDaoImpl implements UserDao{

    @Override
    public boolean requeryUser(Person p) {
        boolean isExited = false;
        // 如果为空,直接返回false
        if (p==null) {
            return isExited;
        }
        //获取连接
        Connection connection =  JdbcUtils.getConnection();
        //SQL语句
        String sql = "SELECT NAME FROM HW WHERE NAME=?";
        //创建预编译
        PreparedStatement pStatement = null;
        ResultSet rSet = null;
        try {
            // 执行SQL语句
            pStatement = connection.prepareStatement(sql);
            // 设置相应的参数
            pStatement.setString(1, p.getName());
            //查询结果集,有就返回ture,否则返回false
            rSet = pStatement.executeQuery();
            if (rSet.next()) {
                isExited = true;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally{
            //关闭相应对象
            try {
                if (rSet!=null) {
                    rSet.close();
                }
                if (pStatement!=null) {
                    pStatement.close();
                }
                if (connection!=null) {
                    connection.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            
        }
        return isExited;
    }

    @Override
    public boolean addUser(Person p) {
        boolean isSuccess=false;
        // 如果为空,直接返回false
        if (p==null) {
            return false;
        }
        //获取连接
        Connection connection =  JdbcUtils.getConnection();
        //SQL语句
        String sql = "INSERT INTO HW VALUES(?,?,?,?,?)";
        //创建预编译
        PreparedStatement pStatement = null;
        int successAmount = -1;
        try {
            // 执行SQL语句
            pStatement = connection.prepareStatement(sql);
            // 设置相应的参数
            pStatement.setString(1, p.getName());
            pStatement.setString(2, p.getPassword());
            pStatement.setString(3, p.getEmail());
            pStatement.setString(4, p.getID());
            pStatement.setString(5, p.getBirthday());
            //操作成功数大于零,就返回ture,否则返回false
            successAmount = pStatement.executeUpdate();
            if (successAmount>0) {
                isSuccess = true;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally{
            //关闭相应对象
            try {
                if (pStatement!=null) {
                    pStatement.close();
                }
                if (connection!=null) {
                    connection.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            
        }
        return isSuccess;
    }

    @Override
    public boolean userLogin(Person p) {
        boolean isExited = false;
        // 如果为空,直接返回false
        if (p==null) {
            return isExited;
        }
        //获取连接
        Connection connection =  JdbcUtils.getConnection();
        //SQL语句
        String sql = "SELECT NAME FROM HW WHERE NAME=? AND PASSWORD=?";
        //创建预编译
        PreparedStatement pStatement = null;
        ResultSet rSet = null;
        try {
            // 执行SQL语句
            pStatement = connection.prepareStatement(sql);
            // 设置相应的参数
            pStatement.setString(1, p.getName());
            pStatement.setString(2, p.getPassword());
            //查询结果集,有就返回ture,否则返回false
            rSet = pStatement.executeQuery();
            if (rSet.next()) {
                isExited = true;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally{
            //关闭相应对象
            try {
                if (rSet!=null) {
                    rSet.close();
                }
                if (pStatement!=null) {
                    pStatement.close();
                }
                if (connection!=null) {
                    connection.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            
        }
        return isExited;
    }

}
package com.zr.homework.UserService;

import com.zr.homework.pojo.Person;
/**
 * 
 * @author lf
 *
 */
public interface UserService {
    /**
     * 用户查询服务
     * @param p
     * @return
     */
    public boolean requeryUserService(Person p);
    /**
     * 注册服务
     * @param p
     * @return
     */
    public boolean addUserService(Person p);
    /**
     * 登陆服务
     * @param p
     * @return
     */
    public boolean loginService(Person p);
}
package com.zr.homework.UserServiceImpl;

import com.zr.homework.UserDao.impl.UserDaoImpl;
import com.zr.homework.UserService.UserService;
import com.zr.homework.pojo.Person;

public class UserServiceImpl implements UserService{

    /**
     * 用户查询
     */
    @Override
    public boolean requeryUserService(Person p) {
        UserDaoImpl impl = new UserDaoImpl();
        return impl.requeryUser(p);
    }
    /**
     * 注册服务
     */
    @Override
    public boolean addUserService(Person p) {
        UserDaoImpl impl = new UserDaoImpl();
        return impl.addUser(p);
    }
    @Override
    public boolean loginService(Person p) {
        UserDaoImpl impl = new UserDaoImpl();
        return impl.userLogin(p);
    }

}