当前位置:网站首页>Can you believe it? It took me only two days to develop a management system
Can you believe it? It took me only two days to develop a management system
2022-07-26 11:32:00 【Hua Weiyun】
Preface :
Because of the epidemic , The school informed that the summer vacation will be held in advance this semester , So the teacher announced the final homework to the public in advance , Develop a department store center supply chain management system according to the requirements , The development cycle is half a month , The title cannot be changed , Including early database design 、 System requirements document , In the later stage, it should be submitted in the form of text . Come here , Tell the truth , I'm in a panic !! That's why let's start from 0 To 1 Build a project by yourself , The key is to work in groups !
Blog's front page : send Big star
️ Welcome to your attention give the thumbs-up Collection ️ Leaving a message.
This article was originally compiled by paidaxing
Series column : The project from 0 build
This series of projects from the design to the realization of the source code are all open source, free to learn and use , Pursue the ideal together , Welcome to supervise the development of punch in !

Difficulty analysis
Although, when I heard the news , I'm still shocked , After all, it is a complete management system , The function interface should not be too simple . And from the database design to the delivery of the whole system is completed by one person , The challenge effect will directly fill ! But calm down and think , It's not that hard , The overall project process is : Design ——> file ——> code ——> deliver . After the overall process is clarified , Start to realize from scratch step by step , I didn't expect the last step , I used it A day and a half Time for !! Later, it took half a day to optimize the overall project !
Project review
Final effect demonstration :

Technology selection :
- SpringBoot
- Thymeleaf
- Mybatis-Plus
- MySQL
- PageHelper
- Lombok
- Redis( Later page optimization )
Project business process introduction
Login module 、 User module management and user role assignment , Management of news announcement module 、 Commodity module ( Including goods 、 Classification of goods 、 Order ) Management of 、 Management of role module ; Whether the front-end resource has permission to operate the resource , It uses thymeleaf Template syntax for judgment and identification, file upload and other basic functions .
Project structures, ( Using a template engine )
1. First create Maven project
Introduce corresponding dependencies , Build the required file directory
![[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-pSr5BJuu-1651898181791)(/Users/wumao/Documents/Typora note /typora-user-images/image-20220507110514539.png)]](https://img-blog.csdnimg.cn/f23645b80ea346de8fa954146284fa49.png)
![[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-yFKPALe7-1651898181792)(/Users/wumao/Documents/Typora note /typora-user-images/image-20220507110657885.png)]](https://img-blog.csdnimg.cn/5878937ac3f1429483434a43218e8b9f.png)
2. To write yaml The configuration file
server: port: 8080spring: datasource: driver-class-name: com.mysql.cj.jdbc.Driver url: jdbc:mysql://localhost:3306/supplier?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8 username: root password: root # thymeleaf To configure thymeleaf: # Turn off caching cache: false prefix: classpath:/templates/mybatis-plus: mapper-locations: classpath*:/mapper/**/*.xml3. The initial stage of the project is basically built
At the beginning of building a project , In order to make the system appear more standardized , I usually make the basic configuration and declaration in advance , The technologies involved in a project from the beginning and some basic configurations corresponding to these technologies , We should plan clearly in advance ( Personal habits ). such as : exception handling 、 Interceptor 、 filter 、 Constant classes, etc .
① exception handling
@ControllerAdvicepublic class ExceptionHandler { private final org.slf4j.Logger logger = LoggerFactory.getLogger(this.getClass()); @org.springframework.web.bind.annotation.ExceptionHandler(Exception.class) public ModelAndView exception(HttpServletRequest request, Exception e ) throws Exception { logger.error("Request URL:{},Exception:{}",request.getRequestURL(),e); if (AnnotationUtils.findAnnotation(e.getClass(), ResponseStatus.class )!= null){ throw e; } ModelAndView mv = new ModelAndView(); mv.addObject("url",request.getRequestURL()); mv.addObject("exception",e); mv.setViewName("error/error"); return mv; }}② Interceptor
Interceptors are mainly used to process some resources , Similar to some resources that require users to log in before they can access , Some are not needed , such as : The login function does not need to be blocked , The various management of users need to add interception operations , Only in this way can the security of the system be improved .
Login blocking
public class LoginInterceptor extends HandlerInterceptorAdapter { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { if (request.getSession().getAttribute("user") == null){ response.sendRedirect("/api"); return false; } return true; }}Resource release
@Configurationpublic class WebConfig extends WebMvcConfigurerAdapter { @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(new LoginInterceptor()) .addPathPatterns("/api/**") .excludePathPatterns("/api","/api/doLogin"); }}4. To write Controller Front end controller code
First create a FileController class
① Jump to the page of file upload
// Jump to the page of file upload @RequestMapping("/file-upload")public String userList(){ return "file-upload";}② Realize the function of file upload
@RequestMapping("/doAddForUser")public String doAdd(User user, @RequestParam("file") MultipartFile files, HttpServletRequest request) throws IOException { //String path = null; if (files != null && !files.isEmpty()){ String name = UUID.randomUUID().toString().replace("-",""); // Get the extension of the file String ext = FilenameUtils.getExtension(files.getOriginalFilename()); // Set the path of file upload String url =request.getSession().getServletContext().getRealPath("/upload/"); File file = new File(url); if (!file.exists()){ file.mkdir(); } // Test path System.out.println(request.getServletPath()+ "/upload"); System.out.println(request.getContextPath() + "/upload/"); // Save the renamed file in an absolute path files.transferTo(new File(url+"/"+name+"."+ext)); user.setAvatar(request.getContextPath() + "/upload/"+name+"."+ext); } user.setId(UUID.randomUUID().toString()); String salt = PasswordUtils.getSalt(); String password = user.getPassword(); String encode = PasswordUtils.encode(password, salt); user.setSalt(salt) ; user.setPassword(encode); user.setCreateTime(new Date()); userService.save(user); return "redirect:/api/users";}notes : How to upload multiple files? The changes are as follows :
![[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-RaebdJda-1651898181792)(/Users/wumao/Documents/Typora note /typora-user-images/image-20220507114014754.png)]](https://img-blog.csdnimg.cn/78080d2e8ec64d1b9a79792f5c363f3d.png)
③ Realize multi file upload function
In this project, the multi file upload function is not realized
private void commons(Object obj, @RequestParam("file") CommonsMultipartFile[] files, HttpServletRequest request) throws IOException { //String path = null; for (int i = 0; i < files.length; i++) { if (files[i] != null && !files[i].isEmpty()){ String name = UUID.randomUUID().toString().replace("-",""); // Get the extension of the file String ext = FilenameUtils.getExtension(files[i].getOriginalFilename()); // Set the path of file upload String url =request.getSession().getServletContext().getRealPath("/upload/"); File file = new File(url); if (!file.exists()){ file.mkdir(); } // Test path System.out.println(request.getServletPath()+ "/upload"); System.out.println(request.getContextPath() + "/upload/"); // Save the renamed file in an absolute path files[i].transferTo(new File(url+"/"+name+"."+ext)); if (i == 0){ obj.setUrl1(request.getContextPath() + "/upload/"+name+"."+ext); } if (i == 1){ obj.setUrl2(request.getContextPath() + "/upload/"+name+"."+ext); } if (i == 2){ obj.setUrl3(request.getContextPath() + "/upload/"+name+"."+ext); } if (i == 3){ obj.setUrl4(request.getContextPath() + "/upload/"+name+"."+ext); } if (i == 4){ obj.setUrl5(request.getContextPath() + "/upload/"+name+"."+ext); } } }}5. Project optimization
For items where the front and rear ends are not separated , Most use Page cache optimization , When the system suffers huge flow at a moment , When the first user accesses a page, the page data can be cached , such , Later, the pages visited by users are obtained from the cache , This reduces Operation on Database , Reduced the pressure on the database , So as to achieve optimal processing .
① Import dependence
<!--Redis--><dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId></dependency><!--commons-pools2 Object pool dependency --><dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-pool2</artifactId></dependency>② yaml To configure
## Redis To configure redis: # Server address host: localhost # port port: 6379 # database database: 0 # Timeout time connect-timeout: 10000ms lettuce: pool: # maximum connection max-active: 8 # Maximum connection blocking wait time Default -1 max-wait: 10000ms # Maximum free time Default 8 max-idle: 200 # Minimum free connection Default 8 min-idle: 5④ Redis Serialization
@Configurationpublic class RedisConfig { @Bean public RedisTemplate<String,Object> redisTemplate(RedisConnectionFactory redisConnectionFactory){ RedisTemplate<String,Object> redisTemplate = new RedisTemplate<>(); //key serialize redisTemplate.setKeySerializer(new StringRedisSerializer()); //value serialize redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer()); //hash type key Serialization redisTemplate.setHashKeySerializer(new StringRedisSerializer()); //hash type value Serialization redisTemplate.setHashValueSerializer(new GenericJackson2JsonRedisSerializer()); redisTemplate.setConnectionFactory(redisConnectionFactory); return redisTemplate; }}③ Optimize processing
@Autowired private NewsService newsService; @Autowired private RedisTemplate redisTemplate; @Autowired private ThymeleafViewResolver viewResolver; @RequestMapping(value = "/news",produces = "text/html;charset=utf-8") @ResponseBody public String roles(Model model, @RequestParam(value = "pageNo",defaultValue = "1")Integer pageNo , @RequestParam(value = "pageSize",defaultValue = "10")Integer pageSize , HttpServletRequest request, HttpServletResponse response){ //Redis Get page , If it's not empty , Then go back to the page ValueOperations valueOperations = redisTemplate.opsForValue(); String html = (String) valueOperations.get("news-list"); if (!StringUtils.isEmpty(html)){ return html; } PageHelper.startPage(pageNo,pageSize); List<News> list = newsService.list(); PageInfo<News> pageInfo = new PageInfo<>(list); model.addAttribute("news",list); model.addAttribute("pageInfo",pageInfo); // If it is empty , Manual rendering , Deposit in Redis And in return WebContext context = new WebContext(request, response, request.getServletContext(), request.getLocale(), model.asMap()); html = viewResolver.getTemplateEngine().process("news-list", context); if (!StringUtils.isEmpty(html)){ // Set the expiration time for the cache valueOperations.set("news-list",html,60, TimeUnit.SECONDS); } return html; }④ Redis see
![[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-hZd4S31W-1651898181792)(/Users/wumao/Documents/Typora note /typora-user-images/image-20220507121029823.png)]](https://img-blog.csdnimg.cn/3b8c958eef0d4f0fb3cc506f4e0867f1.png)
6. matters needing attention
Be careful
@Controllerand@RestControllerThe difference between , This project uses the template to render the page , and@ControllerIs used to respond to the page ; and@RestControllerIt's used to return toJsonIn the project optimization stage, you need to add notes on the method
@ResponseBody, Because we cache the whole page , So convert the page intoJSONFor storage .![[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-seotbkvr-1651898181792)(/Users/wumao/Documents/Typora note /typora-user-images/image-20220507122521057.png)]](https://res.hc-cdn.com/ecology/7.7.103/v2_resources/ydcomm/libs/images/loading.gif)
Inject Thymeleaf Parser , Will be specific The page is parsed into
JsonString to store![[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-3qbGjfEd-1651898181792)(/Users/wumao/Documents/Typora note /typora-user-images/image-20220507122734629.png)]](https://res.hc-cdn.com/ecology/7.7.103/v2_resources/ydcomm/libs/images/loading.gif)
![[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-bp8dZ78Z-1651898181793)(/Users/wumao/Documents/Typora note /typora-user-images/image-20220507122856798.png)]](https://res.hc-cdn.com/ecology/7.7.103/v2_resources/ydcomm/libs/images/loading.gif)
Will deposit Redis Data in plus expiration time , Because the data in the page should be consistent with the database , If the user sees the data tens of seconds or a minute ago, it is still barely acceptable .
![[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-Nt3O3qvl-1651898181793)(/Users/wumao/Documents/Typora note /typora-user-images/image-20220507123528961.png)]](https://res.hc-cdn.com/ecology/7.7.103/v2_resources/ydcomm/libs/images/loading.gif)
At present, the code has been synchronized to Paidaxing department store center management system
If necessary, go to the warehouse and pick it up by yourself , Please don't be stingy with the three companies in your hands !
边栏推荐
- 承认吧 投新能源就是为了安全感
- Caused by: scala.MatchError: None (of class scala.None$)
- Pyqt5 rapid development and practice 3.1 QT designer quick start
- How the ThreadPoolExecutor performs tasks
- MySQL transaction details
- PyQt5快速开发与实战 第1章 认识PyQt5
- 新来个技术总监要我做一个 IP 属地功能~
- Harbor2.2 用户角色权限速查
- 脉冲波形的产生与变换
- Initial learning experience of SQL Server database
猜你喜欢

Le audio specification overview

Novice source code hashtable

服务器内存故障预测居然可以这样做!

MySQL死锁分析

easyui03

产品无力销量下滑 上汽名爵还能否走出阴霾

Getting started step by step using g2o to solve ICP problems - estimating the transformation relationship between two sets of 3D point sets with matching relationship

leetcode-209. 长度最小的子数组(二分、前缀和、滑动窗口)

Reproduce PHP one sentence Trojan horse
![[idea] how to create a new project](/img/33/f210d59ccd3664487f401929dac24c.png)
[idea] how to create a new project
随机推荐
Several ways of communication between threads
Reproduce PHP one sentence Trojan horse
配置文件以rc结尾什么意思
easyui01
常用库安装
Query summary of SQL Server
js使用WebUploader做大文件的分块和断点续传
Rigorous proof of Behrman's expectation equation
easyui02
服务器内存故障预测居然可以这样做!
[vscode] how to connect to the server remotely
ESP8266-Arduino编程实例-开发环境搭建(基于Arduino IDE)
【万字长文】使用 LSM-Tree 思想基于.Net 6.0 C# 实现 KV 数据库(案例版)
In depth interpretation of happens before principle
Leetcode-209. subarray with the smallest length (binary, prefix and, sliding window)
swagger2.9.2教程 与swagger3.0.0教程
【转载】多元高斯分布(The Multivariate normal distribution)
FINEOS宣布2022年GroupTech Connect活动开放注册
[idea]如何新建一个项目
Relationship between pixels and memory
![[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-seotbkvr-1651898181792)(/Users/wumao/Documents/Typora note /typora-user-images/image-20220507122521057.png)]](https://img-blog.csdnimg.cn/2008ef213e77439fb0cc753ba01b635a.png)
![[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-3qbGjfEd-1651898181792)(/Users/wumao/Documents/Typora note /typora-user-images/image-20220507122734629.png)]](https://img-blog.csdnimg.cn/35e0c80ed35648f4837652bab47692b5.png)
![[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-bp8dZ78Z-1651898181793)(/Users/wumao/Documents/Typora note /typora-user-images/image-20220507122856798.png)]](https://img-blog.csdnimg.cn/ef5e592642c94d738e6e3e2943da1699.png)
![[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-Nt3O3qvl-1651898181793)(/Users/wumao/Documents/Typora note /typora-user-images/image-20220507123528961.png)]](https://img-blog.csdnimg.cn/b430a4993270443b89371bbc4e2c436e.png)