当前位置:网站首页>某马旅游网站开发(对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;
})
})
边栏推荐
- PostGIS learning
- How did a fake offer steal $540million from "axie infinity"?
- limit 与offset的用法(转载)
- 2022.7.7-----leetcode. six hundred and forty-eight
- Use filters to count URL request time
- Teach you to make a custom form label by hand
- 蓝桥ROS中使用fishros一键安装
- Fully automated processing of monthly card shortage data and output of card shortage personnel information
- Aitm3.0005 smoke toxicity test
- UIC564-2 附录4 –阻燃防火测试:火焰的扩散
猜你喜欢

光流传感器初步测试:GL9306

BSS 7230 flame retardant performance test of aviation interior materials

HB 5469民用飞机机舱内部非金属材料燃烧试验方法
![[programming problem] [scratch Level 2] December 2019 flying birds](/img/5e/a105f8615f3991635c9ffd3a8e5836.png)
[programming problem] [scratch Level 2] December 2019 flying birds

Wechat applet development beginner 1

ROS从入门到精通(九) 可视化仿真初体验之TurtleBot3

The function is really powerful!

每日刷题记录 (十六)

How to measure whether the product is "just needed, high frequency, pain points"

QT and OpenGL: loading 3D models using the open asset import library (assimp) - Part 2
随机推荐
蓝桥ROS中使用fishros一键安装
解析token的网址
【推荐系统基础】正负样本采样和构造
How to put recyclerview in nestedscrollview- How to put RecyclerView inside NestedScrollView?
gorm 关联关系小结
Is it safe for tongdaxin to buy funds?
QT creator add JSON based Wizard
【史上最详细】信贷中逾期天数统计说明
10 schemes to ensure interface data security
第四期SFO销毁,Starfish OS如何对SFO价值赋能?
Gorm Association summary
[the most detailed in history] statistical description of overdue days in credit
SQL uses the in keyword to query multiple fields
aws-aws help报错
手写一个模拟的ReentrantLock
MP4文件格式解析之结合实例分析
80% of the people answered incorrectly. Does the leaf on the apple logo face left or right?
codeforces每日5题(均1500)-第八天
Basic learning of SQL Server -- creating databases and tables with the mouse
Data Lake (XV): spark and iceberg integrate write operations
