当前位置:网站首页>某马旅游网站开发(对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;
})
})
边栏推荐
- Apng2gif solutions to various problems
- Restricted linear table
- Problems faced when connecting to sqlserver after downloading (I)
- HB 5469 combustion test method for non-metallic materials in civil aircraft cabin
- P1308 [noip2011 popularity group] count the number of words
- Robomaster visual tutorial (1) camera
- SQL uses the in keyword to query multiple fields
- Data Lake (XV): spark and iceberg integrate write operations
- Tools for debugging makefiles - tool for debugging makefiles
- Seven years' experience of a test engineer -- to you who walk alone all the way (don't give up)
猜你喜欢

STM32F1与STM32CubeIDE编程实例-旋转编码器驱动

80%的人答错,苹果logo上的叶子到底朝左还是朝右?

HB 5469 combustion test method for non-metallic materials in civil aircraft cabin

35岁那年,我做了一个面临失业的决定

BSS 7230 flame retardant performance test of aviation interior materials

FFA与ICGA造影

【编程题】【Scratch二级】2019.09 制作蝙蝠冲关游戏

An example analysis of MP4 file format parsing

Chisel tutorial - 03 Combinatorial logic in chisel (chisel3 cheat sheet is attached at the end)

Pycharm basic settings latest version 2022
随机推荐
Magic fast power
Opengl3.3 mouse picking up objects
35岁真就成了职业危机?不,我的技术在积累,我还越吃越香了
Set up personal network disk with nextcloud
如何衡量产品是否“刚需、高频、痛点”
Chisel tutorial - 04 Control flow in chisel
一个测试工程师的7年感悟 ---- 致在一路独行的你(别放弃)
Go learning notes (2) basic types and statements (1)
Kubectl's handy command line tool: Oh my Zsh tips and tricks
Jisuan Ke - t3104
Flash download setup
HDU - 1260 tickets (linear DP)
Is it safe to buy funds online?
Ping error: unknown name or service
用语雀写文章了,功能真心强大!
2022.7.7-----leetcode.648
Introduction knowledge system of Web front-end engineers
每日刷题记录 (十六)
面试题详解:用Redis实现分布式锁的血泪史
BSS 7230 航空内饰材料阻燃性能测试
