一.案例要求
建库
要求登陆成功进入欢迎页面,显示用户信息(用自定义标签),完成用户信息输出
登录信息不正确回到登录页,并提示错误信息
注册时,用户名不可以重复,用ajax验证
注册成功,写入数据库,并返回登录页面
用户信息修改页面要求用在jsp页面使用Bean完成
-
各页面注意页面效果,用Bootstrap框架布局
注意:所有jsp页面不可以出现任何java代码
二.使用工具
工具
IDEA、Navicat 15 for MySQL、Tomcat服务器、java开发环境JDK1.8、xmind(思维导图工具)
相关文件的导入
- 在WEB-INF下新建lib文件夹,把jar包(843b)导入后按图示操作
- 按快捷键ctrl+shift+alt+s 打开Project Structure 选到Artifacts选区点击右下角的FIX... 选择Add ''to the artifact如果点完后还有FIX...继续重复操作,直至没有。
三.案例导图
四.案例实现
1.数据库建立
1.1 新建数据库
1.2 建表
1.3 添加记录
2.登录页面实现
Bootstrap部署
到Bootstrap下载文件,这里用的是Bootstrap4.4.1
下载好后把bootstrap-4.4.1下的dist文件夹中的两个文件夹复制粘贴到web目录下即可如下图(Bootstrap快速入门)
login.jsp实现
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %><%--导入标准库标签的包--%>
<html>
<head>
<title>登录界面</title>
<link href="css/bootstrap.min.css" rel="stylesheet"><%--导入bootstrap的css样式--%>
</head>
<body>
<div class="container"><%--bootstrap的栅格布局--%>
<h3 style="text-align: center" class="mt-4">用户登录</h3><%--mt调整margin-top--%>
<form action="${pageContext.request.contextPath}/loginServlet" method="post" class="mt-2 col-lg-5 col-md-3 mr-auto ml-auto"><%--直接从Bootstrap官网复制粘贴过来,修改一下即可--%>
<div class="form-group"><%--mr-auto和ml-auto是为了使内容居中 col-md-8是指该内容在辨率≥768px的设备中占3个格子 col-lg-4是该内容在分辨率≥992px的设备中占5个格子--%>
<label for="userName">用户名</label><%--label的作用就是点击标签体内容 焦点给到id为username的输入框--%>
<input type="text" class="form-control" name="userName" id="userName" placeholder="请输入用户名">
</div>
<div class="form-group">
<label for="userPassword">密码</label>
<input type="password" class="form-control" id="userPassword" name="userPassword" placeholder="请输入密码">
</div>
<hr class="mt-4 mb-4"><%--mt调整margin-top mb是调整margin--bottomde--%>
<div class="form-group" style="text-align: center"><%--style的属性是为了使两个按钮居中--%>
<button type="submit" class="btn btn-primary btn-light">登录</button>
<a href="register.jsp" class="btn btn-primary btn-dark">注册</a>
</div>
</form>
<%--出错显示的信息框--%>
<c:if test="${not empty errorMes}"><%--如果request域中获取的errorMes不为空则显示下列信息--%>
<div class="alert alert-warning alert-dismissible fade show col-md-2 col-lg-4 mr-auto ml-auto " role="alert"> <%--Bootstrap的警告框 直接从官网复制代码修改即可--%>
<strong>出错啦!</strong> <c:out value="${errorMes}"/>
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
</c:if>
</div>
<script src="js/bootstrap.min.js"></script><%--导入bootstrap的js--%>
<script src="js/jquery-3.4.1.min.js"></script><%--导入jquery--%>
</body>
效果
3.JDBC的DAO模式实现
3.1 数据库连接类
需要加载的MySQL驱动已在提供的jar包中(mysql-connector-java-8.0.19)
package cn.lot.DB;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class MySQLConnection {
/*加载的驱动程序名*/
private static final String DRIVER="com.mysql.cj.jdbc.Driver";
/*配置MySQL时的用户名和密码*/
private static final String USERNAME="你自己的用户名";
private static final String PASSWORD="密码";
/*URL指向访问的数据库名*/
private static final String URL="jdbc:mysql://localhost:3306/user?serverTimezone=Asia/Shanghai";/*设置为shanghai的时间*/
/*声明Connection对象*/
private Connection conn;
public Connection getConnction() throws Exception{
Class.forName(DRIVER);/*加载驱动*/
conn = DriverManager.getConnection(URL,USERNAME,PASSWORD);
return conn;
}
/*关闭数据库连接的方法*/
public void close(){
if(conn != null){
try{
this.conn.close();
}catch (SQLException e){
e.printStackTrace();
}
}
}
}
3.2 User实体类-JavaBean
User特征
- 有一个默认的无参构造函数
- 需要被序列化即实现Serializable接口
- 除userid属性只读外(本案例中userid由数据库自动生成)其余属性均可读写
- 所有属性均有getter和setter方法
User代码
package cn.lot.VO;
import java.io.Serializable;
public class User implements Serializable {
private int userid;
private String username;
private String address;
private String password;
private String sex;
private String email;
public User() {}
public User(int userid, String username, String address, String password, String sex, String email) {
this.userid = userid;
this.username = username;
this.password = password;
this.address = address;
this.sex = sex;
this.email = email;
}
public int getUserid() {
return userid;
}
public void setUserid(int userid) {
this.userid = userid;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
@Override
public String toString() {
return "User{" +
"userid=" + userid +
", username='" + username + '\'' +
", address='" + address + '\'' +
", password='" + password + '\'' +
", sex='" + sex + '\'' +
", email='" + email + '\'' +
'}';
}
}
3.3 UserDAO接口类
package cn.lot.DAO;
import cn.lot.VO.User;
public interface UserDAO {
/*通过用户名查找并返回用户信息*/
public User FindByName(String name)throws Exception;
/*更新用户信息*/
public boolean UpDateinfo(User user)throws Exception;
/*添加新用户*/
public boolean AddUser(User user)throws Exception;
}
3.4 UserDAOImpl实现类
package cn.lot.DAO;
import cn.lot.VO.User;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class UserDAOImpl implements UserDAO {
private Connection conn;
private PreparedStatement pstmt;/*预编译 可以动态操作SQL语句*/
public UserDAOImpl(Connection conn){
this.conn = conn;
}
@Override
public User FindByName(String name)throws Exception{
User user = new User();
/*在Navicat for MySQL中新建查询写相关的SQL语句并执行,若成功则把语句赋值给sql并将=后面的条件换成?*/
String sql = "SELECT * FROM userinfo WHERE username = ?";
try {
this.pstmt = this.conn.prepareStatement(sql);/*执行sql语句*/
this.pstmt.setString(1,name);/*为sql语句中的第一个问号赋值*/
ResultSet rs = this.pstmt.executeQuery();/*将执行查询的结果存放在ResultSet的对象中*/
if(rs.next()){
/*将获得的属性传给新建的一个User对象*/
user.setUserid(rs.getInt(1));
user.setUsername(rs.getString(2));
user.setPassword(rs.getString(3));
user.setAddress(rs.getString(4));
user.setSex(rs.getString(5));
user.setEmail(rs.getString(6));
}else {
user = null;
System.out.println("user为空");
}
} catch (SQLException e) {
e.printStackTrace();
}
/*用完就要关闭PreparedStatement,释放内存*/
this.pstmt.close();
return user;
}
@Override
public boolean UpDateinfo(User user) throws Exception{
boolean flag = false;
String sql = "UPDATE userinfo SET username = ? ,password = ?,address = ?,sex = ?,email = ? WHERE userid = ?";
try {
this.pstmt = this.conn.prepareStatement(sql);
this.pstmt.setString(1,user.getUsername());
this.pstmt.setString(2,user.getPassword());
this.pstmt.setString(3,user.getAddress());
this.pstmt.setString(4,user.getSex());
this.pstmt.setString(5,user.getEmail());
this.pstmt.setInt(6,user.getUserid());
if(this.pstmt.executeUpdate() > 0){
/*若执行了更新*/
flag = true;
}else {
System.out.println("更新失败");
}
} catch (SQLException e) {
e.printStackTrace();
}
this.pstmt.close();
return flag;
}
@Override
public boolean AddUser(User user) throws Exception{
boolean flag = false;
String sql = "INSERT INTO userinfo(username,password,address,sex,email)VALUES(?,?,?,?,?)";
try {
this.pstmt = this.conn.prepareStatement(sql);
this.pstmt.setString(1,user.getUsername());
this.pstmt.setString(2,user.getPassword());
this.pstmt.setString(3,user.getAddress());
this.pstmt.setString(4,user.getSex());
this.pstmt.setString(5,user.getEmail());
if(this.pstmt.executeUpdate() > 0 ){
flag = true;
}else {
System.out.println("用户注册失败");
}
} catch (SQLException e) {
e.printStackTrace();
}
this.pstmt.close();
return flag;
}
}
3.5 UserDAOProxy代理类
package cn.lot.DAO;
import cn.lot.DB.MySQLConnection;
import cn.lot.VO.User;
public class UserDAOProxy implements UserDAO {
private MySQLConnection conn = null;
private UserDAO dao;
/*对数据库进行持久化操作*/
public UserDAOProxy()throws Exception{
this.conn = new MySQLConnection();
/*对DAO实现类进行实例化*/
this.dao = new UserDAOImpl(this.conn.getConnction());
}
@Override
public User FindByName(String name) throws Exception{
User user = new User();
try {
/*调用DAO实现类的同名方法*/
user = this.dao.FindByName(name);
} catch (Exception e) {
e.printStackTrace();
} finally {
/*操作完成后关掉连接*/
this.conn.close();
}
return user;
}
@Override
public boolean UpDateinfo(User user)throws Exception {
boolean flag = false;
try {
flag = this.dao.UpDateinfo(user);
} catch (Exception e) {
e.printStackTrace();
} finally {
this.conn.close();
}
return flag;
}
@Override
public boolean AddUser(User user)throws Exception {
boolean flag = false;
try {
flag = this.dao.AddUser(user);
} catch (Exception e) {
e.printStackTrace();
} finally {
this.conn.close();
}
return flag;
}
}
3.6 DAOFactiory工厂类
package cn.lot.FACTORY;
import cn.lot.DAO.UserDAO;
import cn.lot.DAO.UserDAOProxy;
public class DAOFactory {
/*UserDAO时抽象类 通过实现了接口的UserDAOProxy将其实例化*/
public static UserDAO getUserDAOInstance()throws Exception{
return new UserDAOProxy();
}
}
4.登录业务实现
4.1 loginServlet的实现
代码实现
package cn.lot.servlet;
import cn.lot.FACTORY.DAOFactory;
import cn.lot.VO.User;
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 java.io.IOException;
@WebServlet("/loginServlet")
public class loginServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
/*获取用户名和密码*/
String userName = request.getParameter("userName");
String userPassword = request.getParameter("userPassword");
/*错误信息*/
String errorMes;
try {
/* 通过用户名从数据库查找相关数据*/
User user = DAOFactory.getUserDAOInstance().FindByName(userName);
/*先判断user的name是否为空即该名字在数据库中不存在*/
if(user.getUsername() != null){
/* 判断输入的密码是否和数据库中该用户名的密码是一样的*/
if(userName.equals(user.getUsername()) && userPassword.equals(user.getPassword())){
//将用户信息传入session并跳转到success页面
request.getSession().setAttribute("user",user);
request.getRequestDispatcher("/success.jsp").forward(request, response);
}else{
errorMes = "您输入的密码有误!";
request.setAttribute("errorMes",errorMes);
//将密码错误信息带回login.jsp页面
request.getRequestDispatcher("/login.jsp").forward(request, response);
}
}else {
errorMes = "您输入的用户名不存在!";
request.setAttribute("errorMes",errorMes);
//将用户名错误信息带回login.jsp页面
request.getRequestDispatcher("/login.jsp").forward(request, response);
}
} catch (Exception e) {
e.printStackTrace();
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
}
·登陆成功
自定义标签
自定义标签实现步骤如下:
-
编写一个继承SimpleTagSupport的myout类
package cn.lot.myTaglib; import javax.servlet.jsp.JspException; import javax.servlet.jsp.JspWriter; import javax.servlet.jsp.tagext.SimpleTagSupport; import java.io.IOException; public class myout extends SimpleTagSupport { private String value; //一定要有Setter方法 public void setValue(String value) { this.value = value; } @Override public void doTag() throws JspException, IOException { JspWriter writer = getJspContext().getOut(); writer.write(value); } }
-
在WEB-INF下新建tld文件并编辑(对标签处理类进行描述)
· tld新建如图所示:
· 编辑内容:
<?xml version="1.0" encoding="ISO-8859-1"?>
<taglib xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-jsptaglibrary_2_1.xsd"
version="2.1">
<tlib-version>1.0</tlib-version>
<short-name>myshortname</short-name>
<uri>http://mycompany.com</uri><!--要用这个来获取自定义的标签库-->
<!--每一个tag都指定一个标签java类-->
<tag>
<!--调用的方法名-->
<name>out</name>
<!--标签类所在位置-->
<tag-class>cn.lot.myTaglib.myout</tag-class>
<!--该属性是指明需不需要标签体-->
<body-content>empty</body-content>
<attribute>
<name>value</name>
<!--属性必填-->
<required>true</required>
<rtexprvalue>true</rtexprvalue><!--是否能使用jsp表达式-->
</attribute>
</tag>
<!-- Invoke 'Generate' action to add tags or functions -->
</taglib>
- 在jsp页面中用@taglib指令导入tld文件中的uri,即可使用
success.jsp实现
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%--导入自定义标签--%>
<%@taglib prefix="my" uri="http://mycompany.com" %>
<%--导入标准库标签--%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<title>登陆成功</title>
<link href="css/bootstrap.min.css" rel="stylesheet"><%--导入bootstrap的css样式--%>
</head>
<body>
<div class="container">
<h3 style="text-align: center" class="mt-4"><my:out value="${user.username}"/>,欢迎您的访问</h3>
<table class="table table-hover col-lg-5 col-lg-3 ml-auto mr-auto">
<tr>
<th scope="row">用户名</th>
<td><my:out value="${user.username}"/> </td>
</tr>
<tr>
<th scope="row">密码</th>
<td><my:out value="${user.password}"/> </td>
</tr>
<tr>
<th scope="row">地址</th>
<td><my:out value="${user.address}"/> </td>
</tr>
<tr>
<th scope="row">性别</th>
<td><my:out value="${user.sex}"/> </td>
</tr>
<tr>
<th scope="row">邮箱</th>
<td><my:out value="${user.email}"/> </td>
</tr>
</table>
<div class="row" ><%--style的属性是为了使两个按钮居中--%>
<a href="updateinfo.jsp" class="btn btn-outline-success col-lg-4 col-md-2 mr-auto ml-auto" >修改信息</a>
</div>
</div>
</body>
<script src="js/bootstrap.min.js"></script><%--导入bootstrap的js--%>
<script src="js/jquery-3.4.1.min.js"></script><%--导入jquery--%>
</html>
效果图
·登陆失败
用户名错误提示页面
密码错误提示页面
5.修改业务实现
5.1 修改信息页面实现
updateinfo.jsp实现
- 用来修改信息
- 将修改的信息传给confirm.jsp
<%--加入下面两行(以后用Filter实现)不然JSP中用javabean传递会中文乱码--%>
<%@ page contentType="text/html;charset=GB2312" language="java" %>
<% request.setCharacterEncoding( "GB2312");%>
<html>
<head>
<title>修改用户信息</title>
<link href="css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container">
<h3 style="text-align: center" class="mt-4">用户信息修改</h3>
<form action="confirm.jsp" class="mt-2 col-lg-5 col-md-3 mr-auto ml-auto" method="post">
/*这里的所有属性的name均和其在数据库中的字段名一样 为了能够更好地利用javaBean修改信息*/
<div class="form-group">
<label for="userid">用户ID</label>
<input class="form-control" id="userid" type="text" name="userid" readonly="readonly" value="${userinfo.userid}"> <%--只读不能修改--%>
</div>
<div class="form-group">
<label for="username">用户名</label>
<input class="form-control" id="username" type="text" name="username" value="${userinfo.username}">
</div>
<div class="form-group">
<label for="password">密码</label>
<input class="form-control" id="password" type="password" name="password" value="${userinfo.password}">
</div>
<div class="form-group">
<label for="address">地址</label>
<input class="form-control" id="address" type="text" name="address" value="${userinfo.address}">
</div>
<div class="form-group">
<label for="sex">性别</label>
<input class="form-control" id="sex" type="text" name="sex" value="${userinfo.sex}">
</div>
<div class="form-group">
<label for="email">邮箱</label>
<input class="form-control" id="email" type="email" name="email" value="${userinfo.email}">
</div>
<hr class="mt-4 mb-4">
<div class="row">
<input class="btn btn-outline-primary col-lg-2 col-md-1 mr-auto ml-auto mb-2" id="submit" type="submit" value="确认" onclick="return confirm('信息确认好了吗?')">
<a class="btn btn-outline-dark col-lg-2 col-md-1 mr-auto ml-auto mb-2" href="success.jsp" role="button">返回</a>
</div>
</form>
</div>
<script src="js/bootstrap.min.js"></script><%--导入bootstrap的js--%>
<script src="js/jquery-3.4.1.min.js"></script><%--导入jquery--%>
</body>
</html>
效果图
把密码从88888888改为11111111 地址从广东改到吉林
5.2 利用javaBean更新数据库实现
- 将获取到的信息通过jsp的useBean标签来获取名为userinfo的User对象(在loginServlet中将其存到了Session域里)
- 通过jsp的setProperty标签把从updateinfo.jsp获取到的与uerinfo属性名相对应的值重新赋给userinfo,因为该对象在session中,所以直接通过按钮跳转到ReturnServlet实现数据库的更新操作,并把更新好的userinfo重新放到session域里后跳转到succes.jsp
confirm.jsp实现
<%--加入下面两行(以后用Filter实现)不然JSP中用javabean传递会中文乱码--%>
<%@ page contentType="text/html;charset=GB2312" language="java" %>
<% request.setCharacterEncoding( "GB2312");%>
<html>
<head>
<title>确认修改</title>
<link href="css/bootstrap.min.css" rel="stylesheet">
<meta http-equiv="content-type" content="text/html; charset=utf-8">
</head>
<body>
<div class="container">
<jsp:useBean id="userinfo" scope="session" class="cn.lot.VO.User"/>
<jsp:setProperty name="userinfo" property="*"/>
<h3 style="text-align: center" class="mt-4">确认修改</h3>
<table class="table table-hover col-lg-5 col-lg-3 ml-auto mr-auto">
<tr>
<th scope="row">用户名</th>
<td><jsp:getProperty name="userinfo" property="username"/></td>
</tr>
<tr>
<th scope="row">密码</th>
<td><jsp:getProperty name="userinfo" property="password"/></td>
</tr>
<tr>
<th scope="row">地址</th>
<td><jsp:getProperty name="userinfo" property="address"/> </td>
</tr>
<tr>
<th scope="row">性别</th>
<td><jsp:getProperty name="userinfo" property="sex"/> </td>
</tr>
<tr>
<th scope="row">邮箱</th>
<td><jsp:getProperty name="userinfo" property="email"/> </td>
</tr>
</table>
<div class="row" >
<a href="${pageContext.request.contextPath}/ReturnServlet" class="btn btn-outline-info col-lg-4 col-md-2 mr-auto ml-auto" onclick="return confirm('确认更新吗?')">更新</a>
</div>
<div class="row" >
<a href="updateinfo.jsp" class="btn btn-outline-info col-lg-4 col-md-2 mr-auto ml-auto ">返回</a>
</div>
</div>
<script src="js/bootstrap.min.js"></script><%--导入bootstrap的js--%>
<script src="js/jquery-3.4.1.min.js"></script><%--导入jquery--%>
</body>
</html>
ReturnServlet实现
package cn.lot.servlet;
import cn.lot.FACTORY.DAOFactory;
import cn.lot.VO.User;
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 java.io.IOException;
@WebServlet("/ReturnServlet")
public class ReturnServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
User user = (User)request.getSession().getAttribute("userinfo");
try {
Boolean flag = DAOFactory.getUserDAOInstance().UpDateinfo(user);
if(flag){
request.getSession().setAttribute("userinfo",user);
request.getRequestDispatcher("/success.jsp").forward(request, response);
}else {
System.out.println("更新失败了");
}
} catch (Exception e) {
e.printStackTrace();
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
}
效果图
6.注册业务实现
6.1 注册用户页面实现
- 输入用户名时通过ajax(异步JavaScript 和 XML)实现不需要刷新来判断并提示用户名为空和数据库中是否已存在相同的名字
用ajax实现register.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%--导入标准库标签--%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<title>注册页面</title>
</head>
<link href="css/bootstrap.min.css" rel="stylesheet">
<script src="js/jquery-3.4.1.min.js"></script>
<script type="text/javascript">
//ajax的实现
$(function () {
$("#username").blur(function () {
var url = "${pageContext.request.contextPath}/UserNameServlet";
var username = $(this).val();
//不为空时,用Ajax请求向后台发送信息,验证该用户名是否可用
$.post(url,{username:username},function (data) {/*url为请求路径 {bookname:bookname}为请求参数 data为响应的参数*/
//根据传来的信息
if(data == "1"){
//更新页面
$("#namemsg").html("<font color='red'>这个名字太受欢迎啦!</font>");
}
else if(data == "0"){
$("#namemsg").html("<font color='#2e8b57'>名字取得独一无二!</font>");
}
else {
$("#namemsg").html("<font color='red'>名字不能为空!</font>");
}
},"text")//预期服务器响应的类型为text
})
});
</script>
<body>
<div class="container">
<h3 style="text-align: center" class="mt-4">用户注册</h3>
<form action="${pageContext.request.contextPath}/AddUserServlet" class="mt-2 col-lg-5 col-md-3 mr-auto ml-auto" method="post">
<div class="form-group">
<label for="username">用户名</label>
<input class="form-control" id="username" type="text" name="username" placeholder="请输入用户名" value=""><span id="namemsg"></span>
</div>
<div class="form-group">
<label for="password">密码</label>
<input class="form-control" id="password" type="password" name="password" placeholder="请输入密码" value="">
</div>
<div class="form-group">
<label for="address">地址</label>
<input class="form-control" id="address" type="text" name="address" placeholder="请输入地址" value="">
</div>
<div class="form-group">
<label for="sex">性别</label>
<input class="form-control" id="sex" type="text" name="sex" placeholder="请输入性别" value="">
</div>
<div class="form-group">
<label for="email">邮箱</label>
<input class="form-control" id="email" type="email" name="email" placeholder="请输入邮箱" value="">
</div>
<hr class="mt-4 mb-4">
<div class="form-group" style="text-align: center">
<input class="btn btn-outline-primary" id="submit" type="submit" value="提交">
<input class="btn btn-light" type="reset" value="重置" id="resetButton">
<a class="btn btn-light" href="login.jsp" role="button">返回</a>
</div>
</form>
<c:if test="${not empty errorMes}"><%--如果request域中获取的errorMes不为空则显示下列信息--%>
<div class="alert alert-warning alert-dismissible fade show col-md-2 col-lg-5 mr-auto ml-auto " role="alert"> <%--Bootstrap的警告框 直接从官网复制代码修改即可--%>
<strong>出错啦!</strong> <c:out value="${msg}"/>
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
</c:if>
</div>
<script>
/*选中用户名输入框清空提示信息*/
$("#username").focus(function () {
$("#namemsg").html('');
})
</script>
</body>
</html>
效果图
用户名为空:
用户名可用:
用户名已存在:
6.2 AddUserServlet的实现
- 将获取到的信息赋值给一个user对象所对应的属性,存入session并跳转到success.jsp页面
代码实现
package cn.lot.servlet;
import cn.lot.FACTORY.DAOFactory;
import cn.lot.VO.User;
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 java.io.IOException;
import java.util.Map;
@WebServlet("/AddUserServlet")
public class AddUserServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
User user = new User();
//获取信息
String username = request.getParameter("username");
String password = request.getParameter("password");
String address = request.getParameter("address");
String sex = request.getParameter("sex");
String email = request.getParameter("email");
/*将信息存入新建的User对象中 这里可以更完善一下数据库并没有设置其他属性不能为空 所以如果不填信息也能保存进去*/
user.setUsername(username);
user.setPassword(password);
user.setAddress(address);
user.setSex(sex);
user.setEmail(email);
try {
Boolean flag = DAOFactory.getUserDAOInstance().AddUser(user);
if(flag){
request.getSession().setAttribute("userinfo",user);
request.getRequestDispatcher("/success.jsp").forward(request, response);
}else {
String msg = "注册失败啦!";
request.setAttribute("msg",msg);
request.getRequestDispatcher("/register.jsp").forward(request, response);
}
} catch (Exception e) {
e.printStackTrace();
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
}
效果图
注册页面:
注册成功:
本人实力水平有限,很多地方有待改进,本次案例用到的都是课上所学,欢迎指出有误或着可以改进的地方。