主要是为了 测试分析校验 测试表单的提交与否
表单提交的时候进行校验 鼠标离开输入框的时候校验 校验标准如下
在此使用异步提交表单是为了获取服务器响应的数据。因为我们前台使用的是html作为视图层,不能够直接从servlet相关的域对象获取值,只能通过ajax获取响应数据
效果图
编写RegistUserServlet
package cn.itcast.travel.web.servlet;
import cn.itcast.travel.domain.ResultInfo;
import cn.itcast.travel.domain.User;
import cn.itcast.travel.service.UserService;
import cn.itcast.travel.service.impl.UserServiceImpl;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.beanutils.BeanUtils;
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.lang.reflect.InvocationTargetException;
import java.util.Map;
/**
* @Author wang
* @Date 2022/5/23 16:18
* @PackageName:${PACKAGE_NAME}
* @ClassName: ${NAME}
* @Description: TODO
* @Version 1.0
*/
@WebServlet("/registUserServlet")
public class RegistUserServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1.获取数据
Map map = request.getParameterMap();
//2.封装对象
User user = new User();
try {
BeanUtils.populate(user, map);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
//3.调用service完成注册
UserService service = new UserServiceImpl();
boolean flag = service.regist(user);
ResultInfo userInfo = new ResultInfo();
//4.响应结果
if (flag) {
//注册成功
userInfo.setFlag(true);
} else {
//注册失败
userInfo.setFlag(false);
userInfo.setErrorMsg("注册失败");
}
//将info对象序列化为json
ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(userInfo);
//将json数据写回客户端
//设置content-type
response.setContentType("application/json;charset=utf-8");
// response.getOutputStream().write(json.getBytes());
response.getWriter().write(json);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
}
UserService
UserServiceImpl
UserDao
UserDaoImpl
package cn.itcast.travel.dao.impl;
import cn.itcast.travel.dao.UserDao;
import cn.itcast.travel.domain.User;
import cn.itcast.travel.util.JDBCUtils;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
/**
* @Author wang
* @Date 2022/5/23 16:23
* @PackageName:cn.itcast.travel.dao.impl
* @ClassName: UserDaoImpl
* @Description: TODO
* @Version 1.0
*/
public class UserDaoImpl implements UserDao {
private JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());
@Override
public User findByUsername(String username) {
//1.定义sql
String sql = "select * from tab_user where username = ?";
//2.执行sql
User user = template.queryForObject(sql, new BeanPropertyRowMapper(User.class), username);
return user;
}
@Override
public void save(User user) {
//1.定义sql
String sql = "insert into tab_user(username,password,name,birthday,sex,telephone,email) values(?,?,?,?,?,?,?)";
//2.执行sql
template.update(sql,
user.getUsername(),
user.getPassword(),
user.getName(),
user.getBirthday(),
user.getSex(),
user.getTelephone(),
user.getEmail());
}
}
UserServiceImpl
package cn.itcast.travel.service.impl;
import cn.itcast.travel.dao.UserDao;
import cn.itcast.travel.dao.impl.UserDaoImpl;
import cn.itcast.travel.domain.User;
import cn.itcast.travel.service.UserService;
/**
* @Author wang
* @Date 2022/5/23 16:22
* @PackageName:cn.itcast.travel.service.impl
* @ClassName: UserServiceImpl
* @Description: TODO
* @Version 1.0
*/
public class UserServiceImpl implements UserService {
private UserDao userDao = new UserDaoImpl();
@Override
public boolean regist(User user) {
//1.根据用户名查询用户对象
User u = userDao.findByUsername(user.getUsername());
//判断u是否为null
if (u != null) {
//用户名存在 注册失败
return false;
}
//2.保存用户对象
userDao.save(user);
return true;
}
}
代码健壮性校验
在测试的过程中 如果控制台错误日志 原因解决
但是在之前的表单中 是没有校验验证码的 正常是要先校验验证码 才能进行下一步的注册
RegistUserServlet
@WebServlet("/registUserServlet")
public class RegistUserServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//验证码校验
String check = request.getParameter("check");
//从session中获取验证码
HttpSession session = request.getSession();
String checkcode_server = (String) session.getAttribute("CHECKCODE_SERVER");
session.removeAttribute("CHECKCODE_SERVER");//为了保证验证码只能使用一次
//比价
if (checkcode_server == null || !checkcode_server.equalsIgnoreCase(check)){
ResultInfo userInfo = new ResultInfo();
//验证码校验失败
userInfo.setFlag(false);
userInfo.setErrorMsg("验证码错误");
//将info对象序列化为json
ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(userInfo);
//将json数据写回客户端
//设置content-type
response.setContentType("application/json;charset=utf-8");
response.getWriter().write(json);
return;
}
//1.获取数据
Map map = request.getParameterMap();
.......
.......
.......
register.html
$(function () {
//当表单提交时 调用所有的校验方法
$("#registerForm").submit(function () {
//1.发送数据到服务器
if (checkUsername() && checkPassword() && checkEamil() && checkName() && checkTelephone() && checkBirthday() && checkCheck()) {
//校验通过 发送ajax请求 提交表单的数据 usernamezhangsan & password=123
$.post('registUserServlet', $(this).serialize(), function (data) {
//处理服务器响应的数据 data:{flag:true,errorMsg:'注册失败'}
if (data.flag) {
//注册成功 跳转页面
location.href = "register_ok.html";
} else {
//注册失败 给error添加提示信息
$("#errorMsg").html(data.errorMsg)
}
})
}
测试效果图
邮件激活
为什么要进行邮件激活?为了保证用户填写的邮箱是正确的。将来可以推广一些宣传信息,到用户邮箱中
邮件工具类:MailUtils,调用其中sendMail方法可以完成邮件发送
效果图
经过分析,发现,用户激活其实就是修改用户表中的status为‘Y’
UserServiceImpl
public class UserServiceImpl implements UserService {
private UserDao userDao = new UserDaoImpl();
@Override
public boolean regist(User user) {
//1.根据用户名查询用户对象
User u = userDao.findByUsername(user.getUsername());
//判断u是否为null
if (u != null) {
//用户名存在 注册失败
return false;
}
//2.保存用户对象
//2.1设置激活码
user.setCode(UuidUtil.getUuid());
//2.2设置激活状态
user.setStatus("N");
userDao.save(user);
//激活邮件发送 邮件正文
String content = "点击激活[黑马旅游网]";
MailUtils.sendMail(user.getEmail(), content, "激活邮件");
return true;
}
}
测试效果图
ActiveUserServlet
package cn.itcast.travel.web.servlet;
import cn.itcast.travel.service.UserService;
import cn.itcast.travel.service.impl.UserServiceImpl;
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;
/**
* @Author wang
* @Date 2022/5/24 10:20
* @PackageName:${PACKAGE_NAME}
* @ClassName: ${NAME}
* @Description: TODO
* @Version 1.0
*/
@WebServlet("/activeUserServlet")
public class ActiveUserServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1.获取激活码
String code = request.getParameter("code");//获取通过http协议提交过来的数据. 不仅仅代表表单提交 而且有自定义参数
if (code != null) {
//2.调用service完成激活
UserService service = new UserServiceImpl();
boolean flag = service.active(code);
//3。判断标记
String msg = "";
if (flag) {//激活成功
msg = "激活成功 请登录";
} else {
//激活失败
msg = "激活失败,请联系管理员!";
}
response.setContentType("text/html;charset=utf-8");
response.getWriter().write(msg);
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
}
UserService
UserServiceImpl
@Override
public boolean active(String code) {
//1.根据激活码查询用户对象
User user = userDao.findByCode(code);
if (user != null) {
userDao.updateStatus(user);
return true;
} else {
return false;
}
}
UserDao
UserDaoImpl
/**
* 保存用户对象
*
* @param user
*/
@Override
public void save(User user) {
//1.定义sql
String sql = "insert into tab_user(username,password,name,birthday,sex,telephone,email,status,code) values(?,?,?,?,?,?,?,?,?)";
//2.执行sql
template.update(sql,
user.getUsername(),
user.getPassword(),
user.getName(),
user.getBirthday(),
user.getSex(),
user.getTelephone(),
user.getEmail(),
user.getStatus(),
user.getCode()
);
}
/**
* 根据激活码查询用户对象
*
* @param code
* @return
*/
@Override
public User findByCode(String code) {
String sql = "select * from tab_user where code = ?";
//当sql的返回对象 要么只有一个要么没有的时候 使用方法 queryForObject() 这个方法如果没有查出来时 会出异常 不会返回null
User user = null;
try {
user = template.queryForObject(sql, new BeanPropertyRowMapper(User.class), code);
} catch (DataAccessException e) {
e.printStackTrace();
}
return user;
}
/**
* 修改用户的激活状态
*
* @param user
*/
@Override
public void updateStatus(User user) {
String sql = "update tab_user set status = 'Y' where uid = ?";
template.update(sql, user.getUid());
}
效果图