当前位置:网站首页>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
边栏推荐
- Esp8266 Arduino programming example - timer and interrupt
- [cloud native kubernetes] mapping external service under kubernetes cluster eendpoint
- 想要快速成长,先要经历重大打击!
- Oracle database objects
- Openresty request authentication
- Small program canvas generates posters
- HCIP(14)
- Esp8266 Arduino programming example - SPIFs and data upload (Arduino IDE and platformio IDE)
- typeof原理
- hcip实验(15)
猜你喜欢

使用百度EasyDL实现明厨亮灶厨师帽识别

HCIP(15)

HCIP(12)

Desai wisdom number - line chart (stacking area chart): ranking of deposits of different occupational groups in the proportion of monthly income in 2022

HCIP(14)

Hcip experiment (15)

39. Combined sum

Basic introduction of Rockwell AB PLC rslogix digital quantity IO module

CDN工作原理

熊市下 DeFi 的未来趋势
随机推荐
LCR测试仪最为主要的功能和用途都是什么
Static route and default route experiment
II. Explanation of the sequence and deserialization mechanism of redistemplate
如何在 Web3中建立一个去中心化社区
【NLP】生成词云
ssh 免密码登录
想要快速成长,先要经历重大打击!
第 7 篇:绘制旋转立方体
Brief introduction to PCB materials
DHCP和PPPoE协议以及抓包分析
HCIP(13)
Part 8: creating camera classes
HCIP(10)
乌官员:乌克兰一半农产品经多瑙河港口出口
What testing services do third-party software testing institutions provide? Charging standard of software test report
成立不到一年!MIT衍生量子计算公司完成900万美元融资
JS DOM编程之平平无奇小练习
行内元素和块级元素有什么区别?语义化作用
Oracle triggers
[machine learning] naive Bayesian classification of text -- Classification of people's names and countries
