用户注册登录过程主要分为几个步骤:(1)前端页面设计;(2)数据访问模型包;(3)Servlet容器数据接收处理;(4)跳转至页面。下面分步骤小记一下,供以后参考:
整个实现环境:EclipseVersion: -09 (4.9.0)--Eclipse Java EE IDE for Web Developers.;JDK 1.8.0_73;mysql:5.6.44-win32(远程数据库);Tomcat9.0
项目结构如下:
(1)前端页面设计
由于仅仅是用户注册登录,因此设计就较为简单。在Eclipse中新建Dynamic web project,并命名为new。WebContent用于存放页面设计文档,如结构图中的front目录为前端页面文档,包括css、img和jsp文件。其上一级目录中的index.jsp仅为跳转使用,前端页面首页为front目录下的index.jsp。如下首页代码,资源文件如css和img可以不管,重点是实现的过程。
首页代码参考:
<%@ page language="java" contentType="text/html; charset=UTF-8"pageEncoding="UTF-8"%><!DOCTYPE html><html><head> <meta http-equiv="content-type" content="text/html" charset="GB2312"><title>myweb</title><link rel="stylesheet" type="text/css" href="css/front.css"></head><body><div class="box1"><div class="header"><li><a href="user.jsp">公司简介</a></li><li><a href="news.html">公司新闻</a></li><!-- 如果session中username的值存在,则显示欢迎用户 和用户退出--><% if(request.getSession().getAttribute("username")!=null){ %><li>welcome,<%=request.getSession().getAttribute("username")%></li><li><a href="logout.jsp">用户退出</a></li><% } else{ %><!-- 如果session中username的值不存在,则显示用户注册 和用户登录--><li><a href="register.jsp">用户注册</a></li><li><a href="login.jsp">用户登录</a></li><% } %></div><div class="main"><img src="img/car.jpg"></div></div>
用户注册register.jsp代码:
<%@ page language="java" contentType="text/html; charset=UTF-8"pageEncoding="UTF-8"%><!DOCTYPE html><html><head><meta charset="UTF-8"><title>Insert title here</title><link rel="stylesheet" type="text/css" href="css/front.css"></head><body><div class="box"><form action="UserRegister" method="post"><div class="section"><label>username</label><input type="text" name="username"> </div><div class="section"><label>username</label><input type="password" name="userpwd"> </div><div class="section"><label>gender</label><input type="radio" name="sex"> male <input type="radio" name="sex"> female</div><div class="section"><input type="submit" name="submit" value="提交"><input type="reset" name="reset" value="Reset"> </div></form></div></body></html>
用户登录login.jsp代码:
<%@ page language="java" contentType="text/html; charset=UTF-8"pageEncoding="UTF-8"%><!DOCTYPE html><html><head><meta charset="UTF-8"><title>Insert title here</title><link rel="stylesheet" type="text/css" href="css/front.css"></head><body><div class="box"><form action="UserServlet" method="post"><div class="section"><label>username</label><input type="text" name="username"> </div><div class="section"><label>username</label><input type="password" name="userpwd"> </div><div class="section"><input type="submit" name="submit" value="提交"><input type="reset" name="reset" value="Reset"> </div></form></div></body></html>
用户退出logout.jsp代码:
<%@ page language="java" contentType="text/html; charset=UTF-8"pageEncoding="UTF-8"%><!DOCTYPE html><html><head><meta charset="UTF-8"><title>Insert title here</title></head><body><% request.getSession().setAttribute("username", null); %><script>window.location.href="index.jsp";</script></body></html>
用户登录和用户注册在前端页面处都是表单样式,这里form表单里的action指向了servlet容器,servlet容器用于处理http请求如表单提交request以及响应response反馈给页面。
(2)DAO数据访问模型对象
这里的DAO是数据访问对象包简写,本次还未涉及使用任何框架。在java Resources里新建一个dao包,(新建package),然后在该包里新建两个java类,一个是负责连接数据库和关闭数据库的封装类DButils.java,一个是负责与数据库交互处理如新增、删除、更新、查询等操作的类,这里名为为LoginDaolmp.java,即用于处理用户登录和注册的数据模型类。
DButils.java类代码如下:
package dao;import java.sql.*;public class DButils { static final String JDBC_DRIVER = "com.mysql.jdbc.Driver"; static final String DB_URL = "jdbc:mysql://106.13.111.246:3306/new";static final String USER = "cao";static final String PASS = "root123";static Connection conn = null;public static Connection getConnection(){ try {//加载oracle驱动Class.forName(JDBC_DRIVER);//通过驱动获取数据库的连接conn = DriverManager.getConnection(DB_URL,USER,PASS);System.out.println("连接成功");} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}return conn;}public static void Close(){try { if(conn!=null) { conn.close();}} catch (SQLException e) {// TODO: handle exceptione.printStackTrace();}}}
LoginDaolmp.java代码如下:
package dao;import java.sql.*;public class LoginDaolmp {//登录时查询用户名和密码是否匹配,如果匹配则返回真public boolean searchName(String loginName, String loginpwd) {Connection conn=(Connection)DButils.getConnection();String sql="select * from user where username=? and userpwd=?";try {PreparedStatement ps=(PreparedStatement)conn.prepareStatement(sql);ps.setString(1, loginName);ps.setString(2,loginpwd);ResultSet rs=ps.executeQuery();while(rs.next()) {return true;}} catch (SQLException e) {// TODO: handle exceptione.printStackTrace();}return false;}//注册时将新用户名和信息插入数据库,操作成功则返回真public boolean RegisterName(String loginName, String loginpwd,String sex) {Connection conn=(Connection)DButils.getConnection();PreparedStatement ps=null;String sql="insert into user values(null,?,?,?)";try { ps=conn.prepareStatement(sql);ps.setString(1, loginName);ps.setString(2,loginpwd);ps.setString(3, sex);int result=ps.executeUpdate(); if(result==1) {return true;}} catch (SQLException e) {// TODO: handle exceptione.printStackTrace();}return false;}}
(3)Servlet容器接收响应处理
当进入首页点击用户登录或用户注册时,表单响应会提交至servlet容器。操作时新建servlet容器,然后新建两个类,一个为处理用户登录,一个为处理用户注册。这里分别命名为UserRegister和UserServlet,如下为处理用户登录的UserServlet类代码:
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.LoginDaolmp;/*** Servlet implementation class UserServlet*/@WebServlet("/front/UserServlet")public class UserServlet extends HttpServlet {private static final long serialVersionUID = 1L;/*** @see HttpServlet#HttpServlet()*/public UserServlet() {super();// TODO Auto-generated constructor stub}/*** @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)*/protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {// TODO Auto-generated method stubresponse.getWriter().append("Served at: ").append(request.getContextPath());}/*** @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)*/protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {// TODO Auto-generated method stubdoGet(request, response);String username=request.getParameter("username"); //获取表单里用户名文本框信息String userpwd=request.getParameter("userpwd");//获取表单里用户密码文本框信息LoginDaolmp dl=new LoginDaolmp(); PrintWriter out=response.getWriter();boolean isHave=dl.searchName(username, userpwd);//调用查询用户名和密码是否匹配方法if(isHave) {response.setCharacterEncoding("UTF-8");response.setContentType("text/html;charset=utf-8");request.setAttribute("username", username); request.getSession().setAttribute("username", username); //将登录用户名保存在session里out.println("<script>alert('登录成功!');window.location.href='index.jsp'</script>");}else {request.getSession().setAttribute("info", "account does not right"); response.sendRedirect("index.jsp");}}}
如下为处理用户注册的UserRegister类代码:
package Servlet;import java.io.IOException;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.LoginDaolmp;/*** Servlet implementation class UserRegister*/@WebServlet("/front/UserRegister")public class UserRegister extends HttpServlet {private static final long serialVersionUID = 1L;/*** @see HttpServlet#HttpServlet()*/public UserRegister() {super();// TODO Auto-generated constructor stub}/*** @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)*/protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {// TODO Auto-generated method stubresponse.getWriter().append("Served at: ").append(request.getContextPath());}/*** @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)*/protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {// TODO Auto-generated method stubString username=request.getParameter("username");String userpwd=request.getParameter("userpwd");String sex=request.getParameter("sex");LoginDaolmp dl=new LoginDaolmp();boolean isHave=dl.RegisterName(username, userpwd, sex);if(isHave) {request.setAttribute("username", username);System.out.println("注册成功!");request.getRequestDispatcher("index.jsp").forward(request, response);}else {request.getSession().setAttribute("info", "account does not right");response.sendRedirect("front/register.jsp");}}}
可以看到在servlet容器里两个类主要编写的是doPost方法,在doPost方法里处理用户注册和登录。
(4)测试效果
当点击首页的用户登录后,进入登录表单页面,填写用户名和密码,点击提交后就会进入UserServlet类进行用户信息匹配操作处理,如果返回为真,则将用户名信息保存到session里,首页页面显示的就是欢迎用户信息了。如下:
整个用户登录和注册的处理过程就实现完毕,里面还有一些小的细节未处理好,如request.getRequestDispatcher(url).forward(request,response),其中的url路径还有待完善。