当前位置:网站首页>Development of a horse tourism website (optimization of servlet)
Development of a horse tourism website (optimization of servlet)
2022-07-08 00:10:00 【Haohao likes pork】
Optimization purpose
- Reduce web Layer file
- distinct
- Easy to maintain
After optimization web Layer directory structure
Catalog
1.0 Content of analysis method
1.0.2 Arrangement web Layer file
1.1.0server layer UserServiceImpl.java file
0. Compilation of base class
be-all servlet Classes will inherit BaseServlet, instead of HttpServlet,BaseServlet rewrite HttpServlet Of Servlet Method
0.0
0.0.0 The base class code
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 {
// Request path
String requestURI = req.getRequestURI();
// Request method to get
String methodName = requestURI.substring(requestURI.lastindexOf("/")+1);
// Distribute tasks
try{
Method method = this.getClass().getMethod(methodName,HttpServletRequest.class,HttpServletResponse.class);
// Violent reflex
method.setAccessible(true);
method.invoke(this,req,resp);
} catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
e.printStackTrace();
}
}
/**
*
* Common method , towards resp We'll meet again obj Of json data
* @param obj
* @param resp
* @throws IOException
*/
public void writeValue(Object obj, HttpServletResponse resp) throws IOException {
ObjectMapper mapper = new ObjectMapper();
// Set the response header to json Format
resp.setContentType("application/json;charset=utf-8");
mapper.writeValue(resp.getOutputStream(),obj);
}
}1.userServlet Class writing
1.0 Content of analysis method
- User registration
- User activation
- Get username
- The user login
- User exits
1.0.0 Write the framework

1.0.1 Code implementation
Most of the code is the same as before web The layer code is consistent , Use public methods to optimize locally
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{
// Create the corresponding service layer object
private UserService service = new UserServiceImpl();
// User registration
public void regist(HttpServletRequest req, HttpServletResponse resp) throws IOException {
// Image verification code validation
String check = req.getParameter("check");
HttpSession session = req.getSession();
String checkcode_server = (String) session.getAttribute("CHECKCODE_SERVER");
// The image verification code is invalid once used
session.removeAttribute("CHECKCODE_SERVER");
if (checkcode_server==null||!checkcode_server.equals(check)){
// Picture verification code verification failed
// Result information object , Store the data that needs to be returned to the front end
ResultInfo info = new ResultInfo(false," Verification code error ");
// Convert the information result object to json Format
ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(info);
// Set the response header to json Format
resp.setContentType("application/json;charset=utf-8");
resp.getWriter().write(json);
return;
}
// The graphic verification code is verified successfully , Get... In the request user Information , Encapsulated in the user object
Map<String,String[]> map = req.getParameterMap();
User user = new User();
try{
BeanUtils.populate(user,map);
} catch (InvocationTargetException | IllegalAccessException e) {
e.printStackTrace();
}
// call UserService Register in
UserService userService = new UserServiceImpl();
boolean flag = userService.regist(user);
ResultInfo info = null;
if (flag){
// Registered successfully
info = new ResultInfo(true);
}else {
info = new ResultInfo(false," Registration failed ");
}
writeValue(info,resp);
}
// User activation
public void active(HttpServletRequest req, HttpServletResponse resp) throws IOException {
String msg =" Activation failed , Please check whether the activation code is valid ";
String code = req.getParameter("code");
if (code!=null){
UserService userService = new UserServiceImpl();
boolean flag = userService.active(code);
if (flag){
// Activation successful
msg = " Activation successful , please <a href='login.html'> Sign in </a>!";
}
}
resp.setContentType("text/html;charset=utf-8");
resp.getWriter().write(msg);
}
// Get username
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){
// Logged in
info.setFlag(true);
info.setData(user.getUsername());
}else {
info.setFlag(false);
}
writeValue(info,resp);
}
// The user login
public void login(HttpServletRequest req, HttpServletResponse resp) throws IOException {
// Image verification code validation
String check = req.getParameter("check");
HttpSession session = req.getSession();
String checkcode_server = (String) session.getAttribute("CHECKCODE_SERVER");
// The image verification code is invalid once used
session.removeAttribute("CHECKCODE_SERVER");
if (checkcode_server==null||!checkcode_server.equals(check)){
// Picture verification code verification failed
// Result information object , Store the data that needs to be returned to the front end
ResultInfo info = new ResultInfo(false," Verification code error ");
// Convert the information result object to json Format
ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(info);
// Set the response header to json Format
resp.setContentType("application/json;charset=utf-8");
resp.getWriter().write(json);
return;
}
// The graphic verification code is verified successfully , Get... In the request user Information , Encapsulated in the user object
Map<String,String[]> map = req.getParameterMap();
User user = new User();
try{
BeanUtils.populate(user,map);
} catch (InvocationTargetException | IllegalAccessException e) {
e.printStackTrace();
}
// call UserService Login in
UserService userService = new UserServiceImpl();
// After landing, user object , by null Login fails
user = userService.login(user);
ResultInfo info = new ResultInfo();
if (user==null){
// Login failed
info.setFlag(false);
info.setErrorMsg(" Username or password incorrect ");
}else if(user.getStatus().equals("N")){
// User not activated
info.setFlag(false);
info.setErrorMsg(" Please go to the registration mailbox to activate ");
}else {
// Successfully logged in , State to keep
req.getSession().setAttribute("user",user);
info.setFlag(true);
}
writeValue(info,resp);
}
// User exits
public void exit(HttpServletRequest req, HttpServletResponse resp) throws IOException {
// Destroy login data
req.getSession().invalidate();
// Jump to the login interface
resp.sendRedirect(req.getContextPath()+"/login.html");
}
}
1.0.2 Arrangement web Layer file
Here I deleted the file directly , You can also use git Repository tools for version control

1.1 Analyze routing
The access route of the back end has been changed , So the front-end access url The route also needs to be changed
1.1.0server layer UserServiceImpl.java file
// Send activation email
String text = "<a href='http://localhost/travel/user/active?code="+user.getCode()+"'> Click this link to activate your account </a>";
1.1.1 front end header.html
// Get login user name
$(function () {
$.get("user/FindOne",{},function (data) {
//{uid:1,name:' Li Si '}
if(data.flag){
// Has landed
var msg = " welcome back ,"+data.data;
$("#span_username").html(msg);
$(".login_out").hide()
$(".login").show()
}else {
// Not logged in
$(".login").hide()
$(".login_out").show()
}
});
});
1.1.2 front end login.html
$(function () {
$("#btn_sub").bind("click",function () {
$.post("user/login",$("#loginForm").serialize(),function (data) {
if (data.flag){
// Landing successful , Jump to home page
location.href="index.html"
}else {
// Login failed
$("#errorMsg").html(data.errorMsg);
}
});
});
});1.1.3regist.html
$(function () {
$("#registerForm").submit(function () {
if(checkAll()){
// All the form items have passed the verification
$.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);
}
});
}
// Form item validation failed , Intercept submission requests
return false;
})
})
边栏推荐
- One click free translation of more than 300 pages of PDF documents
- Rectification characteristics of fast recovery diode
- [programming questions] [scratch Level 2] March 2019 garbage classification
- [programming problem] [scratch Level 2] December 2019 flying birds
- webflux - webclient Connect reset by peer Error
- Use filters to count URL request time
- 关于组织2021-2022全国青少年电子信息智能创新大赛西南赛区(四川)复赛的通知
- How to put recyclerview in nestedscrollview- How to put RecyclerView inside NestedScrollView?
- [leetcode] 20. Valid brackets
- Solutions to problems in sqlserver deleting data in tables
猜你喜欢

One click installation with fishros in blue bridge ROS

An example analysis of MP4 file format parsing

一鍵免費翻譯300多頁的pdf文檔
![[leetcode] 20. Valid brackets](/img/42/5a2c5ec6c1a7dbcdfb2226cdea6a42.png)
[leetcode] 20. Valid brackets

FFA与ICGA造影

About the difference between ch32 library function and STM32 library function
![[the most detailed in history] statistical description of overdue days in credit](/img/f7/5c3cbfec5b010171376ac122c704b2.png)
[the most detailed in history] statistical description of overdue days in credit

【编程题】【Scratch二级】2019.03 垃圾分类

一个测试工程师的7年感悟 ---- 致在一路独行的你(别放弃)

某马旅游网站开发(登录注册退出功能的实现)
随机推荐
Pigsty: out of the box database distribution
【编程题】【Scratch二级】2019.09 绘制雪花图案
Chisel tutorial - 04 Control flow in chisel
用語雀寫文章了,功能真心强大!
Redis caching tool class, worth owning~
如果在构造函数中抛出异常,最好的做法是防止内存泄漏?
Robomaster visual tutorial (10) target prediction
Kubectl's handy command line tool: Oh my Zsh tips and tricks
蓝桥ROS中使用fishros一键安装
[programming problem] [scratch Level 2] draw ten squares in December 2019
从Starfish OS持续对SFO的通缩消耗,长远看SFO的价值
Codeworks 5 questions per day (average 1500) - day 8
【編程題】【Scratch二級】2019.12 飛翔的小鳥
QT and OpenGL: loading 3D models using the open asset import library (assimp) - Part 2
快速上手使用本地测试工具postman
单机高并发模型设计
串联二极管,提高耐压
Is 35 really a career crisis? No, my skills are accumulating, and the more I eat, the better
Uic564-2 Appendix 4 - flame retardant fire test: flame diffusion
Relevant methods of sorting arrays in JS (if you want to understand arrays, it's enough to read this article)
