概述
(一)目的
(二)分析
(三)简单试用
(四)注意事项
(五)改造项目
(一)目的
现在是一个功能一个Servlet,Servlet的数量非常多
我们为了减少Servlet的数量可以将其优化为一个模块一个Servlet
相当于在数据库中一张表对应一个Servlet,在Servlet中提供不同的方法,完成用户的请求
(二)分析
Idea控制台中文乱码解决:-Dfile.encoding=gb2312
(三)简单试用
原理:
每当浏览器发起请求,HttpServlet的service()
方法都会被执行(详情看Servlet文集之生命周期)
而BaseServlet继承了HttpServlet,并且重写了service()
方法
再加上UserServlet和CategoryServlet都继承了BaseServlet
因此,每当UserServlet和CategoryServlet被浏览器访问,BaseServlet的service()
方法都会被执行
BaseServlet:
public class BaseServlet extends HttpServlet {
@Override
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//完成方法的分发
//1.获取请求路径
String uri = request.getRequestURI();
//2.获取方法名称
String methodName = uri.substring(uri.lastIndexOf('/') + 1);
//3.获取方法对象Method
//谁调用我?我就代表谁
// System.out.println(this);//UserServlet的对象
try {
//因为Servlet的方法被protected修饰,所以我们要暴力反射,忽略权限修饰符
Method method = this.getClass().getDeclaredMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
//4.执行方法
try {
//暴力反射
method.setAccessible(true);
method.invoke(this, request, response);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
}
}
UserServlet:
@WebServlet("/user/*")
public class UserServlet extends BaseServlet {
protected void add(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("UserServlet的add方法");
}
protected void find(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("UserServlet的find方法");
}
}
CategoryServlet:
@WebServlet("/category/*")
public class CategoryServlet extends BaseServlet {
protected void add(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("CategoryServlet的add方法");
}
protected void find(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("CategoryServlet的find方法");
}
}
效果:
访问:http://localhost/travel/user/find
访问:http://localhost/travel/category/find
(四)注意事项
我们上面使用了暴力反射,其实并不推荐
我们更倾向于把UserServlet和CategoryServlet的方法改成public
我们还原回去
改成public
效果是一样的
(五)改造项目
@WebServlet("/user/*")
public class UserServlet extends BaseServlet {
//声明UserService业务对象
private UserService service = new UserServiceImpl();
/**
* 注册功能
*
* @param request
* @param response
* @throws ServletException
* @throws IOException
*/
public void regist(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 info = new ResultInfo();
info.setFlag(false);
info.setErrorMsg("验证码错误!");
//讲info对象序列化为json
ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(info);
response.setContentType("application/json;charset=utf-8");
response.getWriter().write(json);
return;
}
//1.获取数据
Map<String, String[]> 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完成注册
boolean flag = service.regist(user);
//4.响应结果
ResultInfo info = new ResultInfo();
if (flag) {
//注册成功
info.setFlag(true);
} else {
//注册失败
info.setFlag(false);
info.setErrorMsg("注册失败!");
}
//讲info对象序列化为json
ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(info);
//讲json数据写回客户端
//设置content-type
response.setContentType("application/json;charset=utf-8");
response.getWriter().write(json);
}
/**
* 登录功能
*
* @param request
* @param response
* @throws ServletException
* @throws IOException
*/
public void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1.获取用户名和密码的数据
Map<String, String[]> map = request.getParameterMap();
//2.封装User对象
User user = new User();
try {
BeanUtils.populate(user, map);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
//3.调用service查询
User u = service.login(user);
ResultInfo info = new ResultInfo();
//4.判断用户对象是否为null
if (u == null) {
//用户名或密码错误
info.setFlag(false);
info.setErrorMsg("用户名或密码错误!");
}
//5.判断用户是否激活
if (u != null && !"Y".equals(u.getStatus())) {
//用户尚未激活
info.setFlag(false);
info.setErrorMsg("您尚未激活,请激活!");
}
//6.登录成功
if (u != null && "Y".equals(u.getStatus())) {
request.getSession().setAttribute("user", u);//登录成功标记
info.setFlag(true);
}
//响应数据
ObjectMapper mapper = new ObjectMapper();
response.setContentType("application/json;charset=utf-8");
mapper.writeValue(response.getOutputStream(), info);
}
/**
* 查询单个对象
*
* @param request
* @param response
* @throws ServletException
* @throws IOException
*/
public void findOne(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//从session中获取登录用户
Object user = request.getSession().getAttribute("user");
//将user写回客户端
ObjectMapper mapper = new ObjectMapper();
response.setContentType("application/json;charset=utf-8");
mapper.writeValue(response.getOutputStream(), user);
}
/**
* 退出功能
*
* @param request
* @param response
* @throws ServletException
* @throws IOException
*/
public void exit(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1.销毁session
request.getSession().invalidate();
//2.跳转到登录页面
response.sendRedirect(request.getContextPath() + "/login.html");
}
/**
* 激活功能
*
* @param request
* @param response
* @throws ServletException
* @throws IOException
*/
public void active(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1.获取激活码
String code = request.getParameter("code");
if (code != null) {
//2.调用service完成激活
boolean flag = service.active(code);
//3.判断
String msg = null;
if (flag) {
//激活成功
msg = "激活成功,请<a href='login.html'>登录</a>";
} else {
//激活失败
msg = "激活失败,请联系管理员!";
}
response.setContentType("text/html;charset=utf-8");
response.getWriter().write(msg);
}
}
}
最后再把前端的请求路径修改过来就可以了
转载:https://blog.csdn.net/qq_42528769/article/details/104998459
查看评论