当前位置:网站首页>Ruiji takeout project - development of business development function Day2
Ruiji takeout project - development of business development function Day2
2022-07-28 22:19:00 【ajjjjjjjjjtty】
Operate employees
Catalog
- Perfect login function
- New employees
- Paging query of employee information
- Enable / Disable employee account
- Edit employee information
One 、 Perfect login function
Summary of improving login information :
- Problem analysis
- Previously, we have completed the development of employee login function of background system , But there is a problem : If the user does not log in , Directly access the system homepage , You can still access .
- This design is unreasonable , What we want to see is , Only after successful login can you access the page in the system , If you don't log in, jump to the login page .
- that , How should it be realized ? The answer is to use filters or interceptors , In filters or interceptors Judge whether the user has completed login , If you don't log in, jump to the login page .
- Code implementation
Implementation steps :
- Create custom filters LoginCheckFilter
- Annotate the startup class @ServletComponentScan
- Improve the processing logic of the filter
1.1 Create custom filters LoginCheckFilter
You need to add comments on the class of this filter WebFilter(filterName = "loginCheckFilter", urlPatterns = "/*")
filterName Is the filter name ,urlPatterns Is the access path ,/* Indicates access to all / The opening page , This class also needs to implement filter, Then implement filter Methods
package com.itheima.filter;
import lombok.extern.slf4j.Slf4j;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* Check whether the user has finished logging in
*/
@Slf4j
@WebFilter(filterName = "loginCheckFilter", urlPatterns = "/*")
public class LoginCheckFilter implements Filter {
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
// Strong go
HttpServletRequest request = (HttpServletRequest)servletRequest;
HttpServletResponse response = (HttpServletResponse)servletResponse;
log.info(" Interceptors intercept requests :{}", request.getRequestURI());
filterChain.doFilter(request, response);
}
}
1.2 Annotate the startup class @ServletComponentScan
package com.itheima;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;
@Slf4j
@ServletComponentScan
@SpringBootApplication
public class ReggieApplication {
public static void main(String[] args) {
SpringApplication.run(ReggieApplication.class);
log.info(" The project started successfully ...");
}
}
1.3 Improve the processing logic of the filter
See next section
test
Access on Browser :http://localhost:8080/backend/index.html , Presentation of the console

Improve the processing logic of the filter
- Get this request's URI
- . Judge whether this request needs to be processed
- If it doesn't need to be dealt with , Then direct release
- Determine login status , If you are logged in , Then direct release
- If you are not logged in, the result of not logging in will be returned
package com.itheima.filter; import com.alibaba.fastjson.JSON; import com.itheima.reggie.common.R; import lombok.extern.slf4j.Slf4j; import org.springframework.util.AntPathMatcher; import javax.servlet.*; import javax.servlet.annotation.WebFilter; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; /** * Check whether the user has finished logging in */ @Slf4j @WebFilter(filterName = "loginCheckFilter", urlPatterns = "/*") public class LoginCheckFilter implements Filter { // Path matcher Support for wildcards public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher(); @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { // Strong go HttpServletRequest request = (HttpServletRequest)servletRequest; HttpServletResponse response = (HttpServletResponse)servletResponse; // 1. Get this request's URI String requestURI = request.getRequestURI(); String[] urls = new String[]{ "/employee/login", "/employee/logout", "/backend/**", "/front/**" }; log.info(" Intercept request :{}",requestURI); // 2. Judge whether this request needs to be processed boolean check = check(urls, requestURI); // 3. If it doesn't need to be dealt with , Then direct release if(check){ log.info(" This request does not need to be processed ",requestURI); filterChain.doFilter(request, response); return; } // 4. Determine login status , If you are logged in , Then direct release if(request.getSession().getAttribute("employee") != null){ log.info(" The user has logged in , user id by : {}",request.getSession().getAttribute("employee")); filterChain.doFilter(request, response); return; } log.info(" The user is not logged in "); // 5. If you are not logged in, the result of not logging in will be returned response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN"))); return; } /** * Path matching , Check whether this request needs to be released * @param urls * @param requestURI * @return */ public boolean check(String[] urls, String requestURI){ for(String url : urls){ boolean match = PATH_MATCHER.match(url, requestURI); if(match){ return true; } } return false; } }Two 、 New employees
- Demand analysis
- Data model
- Code development
- A functional test
Demand analysis : New employees

We need to pay attention to ,employee The table is right username Field adds a unique constraint , because username Is the login account of the employee , Must be unique

employee In the table status The field has been set to the default value 1, Indicates that the state is normal .
Code development :
Before developing code , Sort out the execution process of the whole program :
- Page sending ajax request , The data entered in the new employee page is displayed in json Submit to the server in the form of
- Server side Controller Receive the data submitted by the page and call Service Save the data
- Service call Mapper Operating the database , Save the data

Page sending ajax request , The data entered in the new employee page is displayed in json Submit to the server in the form of
@PostMapping
public R<String> save(@RequestBody Employee employee){
log.info(" Information of new employees :{}",employee.toString());
return R.success(" Add employee successfully ");
}
Server side Controller Receive the data submitted by the page and call Service Save the data
/**
* New employee information
* @param employee
* @return
*/
@PostMapping
public R<String> save(HttpServletRequest request,@RequestBody Employee employee) {
log.info(" New employee information : {}", employee.toString());
employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));
employee.setCreateTime(LocalDateTime.now());
employee.setUpdateTime(LocalDateTime.now());
// Forced to long type Get the current logged in user id
Long empID = (Long) request.getSession().getAttribute("employee");
employee.setCreateUser(empID);
employee.setUpdateUser(empID);
employeeService.save(employee);
return R.success(" Add employee successfully ");
}Check whether to add new employees to the database :
We found that the employee information we added has been added to the database

Add the same... Again username( Employee account number )
Something unusual happened , Because it has been said above username( Employee account number ) The index type of is unique, Therefore, you cannot add the existing username

Add the same employee and make an exception :
Global exception handler
There is still a problem with the previous program , That is, when we add new employees, the account number entered already exists , because employee A unique constraint is added to this field in the table , At this point, the program will throw an exception :
java.sql. SQLIntegrityConstraintViolationException: Duplicate entry 'zhangsan’for key 'idx_username
At this time, we need our program to catch exceptions , There are usually two ways of handling :
1. stay Controller Add... To the method try、catch Exception capture
2. Use exception handler for global exception capture ( The second method is recommended )
Use the exception handler to handle exceptions
Method : stay common It's a bag , establish GlobalExceptionHandler class , And add exceptionHandler Method is used to catch exceptions , And return the result
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import java.sql.SQLIntegrityConstraintViolationException;
/**
* Global exception handling
*/
// Intercept controller Add above RestController Class
@ControllerAdvice(annotations = {RestController.class, Controller.class})
// return JSON
@ResponseBody
@Slf4j
public class globalExceptionHandle {
/**
* Exception handling method
* @return
*/
@ExceptionHandler(SQLIntegrityConstraintViolationException.class)
public R<String> exceptionHandler(SQLIntegrityConstraintViolationException ex){
log.error(ex.getMessage());
if (ex.getMessage().contains("Duplicate entry")){
String[] split = ex.getMessage().split(" ");
String msg = split[2] + " Already exists ";
return R.error(msg);
}
return R.error(" Unknown error ");
}
}
Summary of new employee information :
summary
- Define the business requirements according to the product prototype
- Focus on the analysis of data flow process and data format
- adopt debug Breakpoint debugging trace program execution process
边栏推荐
- Chapter 7: drawing rotating cubes
- Gateway technology of IOT technology stack
- [CS231N]Lecture_2:Image Classification pipelin
- Oracle database objects
- The binary search boundary value processing based on leetcode35 is used to clarify the boundary value of the judgment condition using the idea of interval
- SQL注入 Less38(堆叠注入)
- mysql create语句能不能用来建立表结构并追加新的记录
- 2021年数学建模B组代码
- 40. 组合总和 II
- tutorial/detailed_ workflow. Ipynb quantitative finance qlib Library
猜你喜欢
随机推荐
Ordinary practice of JS DOM programming
第 7 篇:绘制旋转立方体
Intranet penetration learning (III) horizontal movement of domain - planning tasks
LVS+KeepAlived高可用部署实战应用
[machine learning] naive Bayesian classification of text -- Classification of people's names and countries
Necessary for in-depth learning: split the data set, split the labels according to the split pictures, and check the interval of all marked labels
Basic introduction of Rockwell AB PLC rslogix digital quantity IO module
Oracle built-in functions
get和post的区别
内网渗透学习(三)域横向移动——计划任务
tutorial/detailed_workflow.ipynb 量化金融Qlib库
Jmeter 安装第三方插件 Plugins Manager
小程序 监听目标节点出现到屏幕中
04.toRef 默认值
04. Default value of toref
迪赛智慧数——折线图(堆叠面积图):2022年不同职业人群存款额占月收入比例排名
IFLYTEK written examination
HYDAC overflow valve db08a-01-c-n-500v
小程序 canvas 生成海报
The applet listens for the target node to appear on the screen









