当前位置:网站首页>某马旅游网站开发(对servlet的优化)
某马旅游网站开发(对servlet的优化)
2022-07-07 21:58:00 【豪豪喜欢吃猪肉】
优化目的
- 减少web层文件
- 层次分明
- 便于维护
优化后web层目录结构
目录
1.1.0server层UserServiceImpl.java文件
0.基类的编写
所有的servlet类都将继承BaseServlet,而不是HttpServlet,BaseServlet重写HttpServlet的Servlet方法
0.0
0.0.0基类代码
package com.haohao.travel.web.servlet;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.haohao.travel.domain.User;
import javax.servlet.ServletException;
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.lang.reflect.Method;
public class BaseServlet extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 请求路径
String requestURI = req.getRequestURI();
// 请求方法获取
String methodName = requestURI.substring(requestURI.lastindexOf("/")+1);
// 分发任务
try{
Method method = this.getClass().getMethod(methodName,HttpServletRequest.class,HttpServletResponse.class);
// 暴力反射
method.setAccessible(true);
method.invoke(this,req,resp);
} catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
e.printStackTrace();
}
}
/**
*
* 公用方法,向resp返会对象obj的json数据
* @param obj
* @param resp
* @throws IOException
*/
public void writeValue(Object obj, HttpServletResponse resp) throws IOException {
ObjectMapper mapper = new ObjectMapper();
// 设置响应头为json格式
resp.setContentType("application/json;charset=utf-8");
mapper.writeValue(resp.getOutputStream(),obj);
}
}
1.userServlet类编写
1.0分析方法内容
- 用户注册
- 用户激活
- 获取用户名
- 用户登录
- 用户退出
1.0.0编写框架
1.0.1代码实现
大部分的代码与之前的web层代码一致,使用公共方法局部进行优化
package com.haohao.travel.web.servlet;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.haohao.travel.domain.ResultInfo;
import com.haohao.travel.domain.User;
import com.haohao.travel.service.UserService;
import com.haohao.travel.service.impl.UserServiceImpl;
import org.apache.commons.beanutils.BeanUtils;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;
@WebServlet("/user/*") //
public class UserServlet extends BaseServlet{
// 创建对应的服务层对象
private UserService service = new UserServiceImpl();
//用户注册
public void regist(HttpServletRequest req, HttpServletResponse resp) throws IOException {
// 图片验证码效验
String check = req.getParameter("check");
HttpSession session = req.getSession();
String checkcode_server = (String) session.getAttribute("CHECKCODE_SERVER");
// 图片验证码用过一次即失效
session.removeAttribute("CHECKCODE_SERVER");
if (checkcode_server==null||!checkcode_server.equals(check)){
// 图片验证码校验失败
// 结果信息对象,存储需要返回给前端的数据
ResultInfo info = new ResultInfo(false,"验证码错误");
// 将信息结果对象转换为json格式
ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(info);
// 设置响应头为json格式
resp.setContentType("application/json;charset=utf-8");
resp.getWriter().write(json);
return;
}
// 图形验证码校验成功,获取请求中的user信息,封装为user对象
Map<String,String[]> map = req.getParameterMap();
User user = new User();
try{
BeanUtils.populate(user,map);
} catch (InvocationTargetException | IllegalAccessException e) {
e.printStackTrace();
}
// 调用UserService中的注册进行注册
UserService userService = new UserServiceImpl();
boolean flag = userService.regist(user);
ResultInfo info = null;
if (flag){
// 注册成功
info = new ResultInfo(true);
}else {
info = new ResultInfo(false,"注册失败");
}
writeValue(info,resp);
}
//用户激活
public void active(HttpServletRequest req, HttpServletResponse resp) throws IOException {
String msg ="激活失败,请检查激活码是否有效";
String code = req.getParameter("code");
if (code!=null){
UserService userService = new UserServiceImpl();
boolean flag = userService.active(code);
if (flag){
// 激活成功
msg = "激活成功,请<a href='login.html'>登录</a>!";
}
}
resp.setContentType("text/html;charset=utf-8");
resp.getWriter().write(msg);
}
//获取用户名
public void FindOne(HttpServletRequest req, HttpServletResponse resp) throws IOException {
User user = null;
try{
user= (User) req.getSession().getAttribute("user");
}catch (Exception e){
}
ResultInfo info=new ResultInfo();
if(user!=null){
// 登陆过的
info.setFlag(true);
info.setData(user.getUsername());
}else {
info.setFlag(false);
}
writeValue(info,resp);
}
//用户登录
public void login(HttpServletRequest req, HttpServletResponse resp) throws IOException {
// 图片验证码效验
String check = req.getParameter("check");
HttpSession session = req.getSession();
String checkcode_server = (String) session.getAttribute("CHECKCODE_SERVER");
// 图片验证码用过一次即失效
session.removeAttribute("CHECKCODE_SERVER");
if (checkcode_server==null||!checkcode_server.equals(check)){
// 图片验证码校验失败
// 结果信息对象,存储需要返回给前端的数据
ResultInfo info = new ResultInfo(false,"验证码错误");
// 将信息结果对象转换为json格式
ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(info);
// 设置响应头为json格式
resp.setContentType("application/json;charset=utf-8");
resp.getWriter().write(json);
return;
}
// 图形验证码校验成功,获取请求中的user信息,封装为user对象
Map<String,String[]> map = req.getParameterMap();
User user = new User();
try{
BeanUtils.populate(user,map);
} catch (InvocationTargetException | IllegalAccessException e) {
e.printStackTrace();
}
// 调用UserService中的登录进行登录
UserService userService = new UserServiceImpl();
// 登陆后的user对象,为null则登陆失败
user = userService.login(user);
ResultInfo info = new ResultInfo();
if (user==null){
// 登陆失败
info.setFlag(false);
info.setErrorMsg("用户名或密码不正确");
}else if(user.getStatus().equals("N")){
// 用户未激活
info.setFlag(false);
info.setErrorMsg("请前往注册邮箱进行激活");
}else {
// 成功登录,状态保持
req.getSession().setAttribute("user",user);
info.setFlag(true);
}
writeValue(info,resp);
}
//用户退出
public void exit(HttpServletRequest req, HttpServletResponse resp) throws IOException {
// 销毁登陆数据
req.getSession().invalidate();
// 跳转登陆界面
resp.sendRedirect(req.getContextPath()+"/login.html");
}
}
1.0.2整理web层文件
这里我直接把文件删掉了,大家还可以使用git存储库工具进行版本控制
1.1分析路由
后端的访问路由已经更改,那么前端访问的url路由也是需要更改一下的的
1.1.0server层UserServiceImpl.java文件
// 发送激活邮件
String text = "<a href='http://localhost/travel/user/active?code="+user.getCode()+"'>点击此链接激活账号</a>";
1.1.1前端header.html
// 获取登陆用户名
$(function () {
$.get("user/FindOne",{},function (data) {
//{uid:1,name:'李四'}
if(data.flag){
// 已登陆
var msg = "欢迎回来,"+data.data;
$("#span_username").html(msg);
$(".login_out").hide()
$(".login").show()
}else {
// 未登录
$(".login").hide()
$(".login_out").show()
}
});
});
1.1.2前端login.html
$(function () {
$("#btn_sub").bind("click",function () {
$.post("user/login",$("#loginForm").serialize(),function (data) {
if (data.flag){
// 登陆成功,跳转到首页
location.href="index.html"
}else {
// 登陆失败
$("#errorMsg").html(data.errorMsg);
}
});
});
});
1.1.3regist.html
$(function () {
$("#registerForm").submit(function () {
if(checkAll()){
// 表单项全部验证通过
$.post("user/regist",$(this).serialize(),function (data) {
if(data.flag){
location.href="register_ok.html";
}else {
$("#checkCode").src="checkCode?"+new Date().getTime();
$("#errorMsg").html(data.errorMsg);
}
});
}
// 表单项验证失败,拦截提交请求
return false;
})
})
边栏推荐
- One click installation with fishros in blue bridge ROS
- BSS 7230 航空内饰材料阻燃性能测试
- How does starfish OS enable the value of SFO in the fourth phase of SFO destruction?
- [the most detailed in history] statistical description of overdue days in credit
- Rock-paper-scissors
- @Configuration注解的详细介绍
- Problems faced when connecting to sqlserver after downloading (I)
- Introduction knowledge system of Web front-end engineers
- At the age of 35, I made a decision to face unemployment
- go time包常用函数
猜你喜欢
【編程題】【Scratch二級】2019.12 飛翔的小鳥
【编程题】【Scratch二级】2019.12 绘制十个正方形
How does starfish OS enable the value of SFO in the fourth phase of SFO destruction?
Robomaster visual tutorial (1) camera
【推荐系统基础】正负样本采样和构造
【编程题】【Scratch二级】2019.03 绘制方形螺旋
Basic learning of SQL Server -- creating databases and tables with code
Laser slam learning (2d/3d, partial practice)
UIC564-2 附录4 –阻燃防火测试:火焰的扩散
Traduction gratuite en un clic de plus de 300 pages de documents PDF
随机推荐
SQL 使用in关键字查询多个字段
Enterprise application demand-oriented development of human resources department, employee attendance records and paid wages business process cases
80%的人答错,苹果logo上的叶子到底朝左还是朝右?
Install sqlserver2019
串联二极管,提高耐压
【推荐系统基础】正负样本采样和构造
CoinDesk评波场去中心化进程:让人们看到互联网的未来
手写一个模拟的ReentrantLock
FFA and ICGA angiography
QT creator add custom new file / Project Template Wizard
Is it safe to buy funds online?
10 schemes to ensure interface data security
Data Lake (XV): spark and iceberg integrate write operations
Pigsty:开箱即用的数据库发行版
Two small problems in creating user registration interface
95. (cesium chapter) cesium dynamic monomer-3d building (building)
507 field D - extraterrestrial relics
aws-aws help报错
Rock-paper-scissors
STM32F1与STM32CubeIDE编程实例-旋转编码器驱动