week 8.17-8.23
- | Study-update |
---|---|
-Mon | 多文件上传,@ControllerAdvice处理全局异常 |
-Tue | @ControllerAdvice全局数据预设,请求参数预处理,自定义异常数据,自定义错误页面 |
-Wes | 系统启动任务,cors跨域,boot配置拦截器 |
-Thu | ApplicationRunner,springboot路径映射,springboot使用类型转换器 |
-Fri | springboot整合aop |
-Sat | springboot 配置mybatis |
- | Study-update |
8.17 Monday
多文件上传
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="/uploads" method="post" enctype="multipart/form-data">
<input type="file" name="files" multiple>
<input type="submit" value="提交">
</form>
</body>
</html>
@PostMapping("/uploads")
public String uploads(MultipartFile[] files, HttpServletRequest request) {
String format = simpleDateFormat.format(new Date());
String realPath = request.getServletContext().getRealPath("/img") + format;
File folder = new File(realPath);
if (!folder.exists()) {
folder.mkdirs();
}
for (MultipartFile file : files) {
String oldName = file.getOriginalFilename();
String newName = UUID.randomUUID().toString() + oldName.substring(oldName.lastIndexOf("."));
try {
file.transferTo(new File(folder, newName));
String url = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + "/img" + format + "/" + newName;
System.out.println(url);
} catch (IOException e) {
e.printStackTrace();
}
}
return "success";
}
@ControllerAdvice处理全局异常
package com.maaoooo.fileupload.exception;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.multipart.MaxUploadSizeExceededException;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
/**
* @author lzr
* @date 2020 08 17 21:18
* @description
*/
@ControllerAdvice
public class MyException {
@ExceptionHandler(MaxUploadSizeExceededException.class)
public void myexception(MaxUploadSizeExceededException e, ServletResponse response, ServletRequest request) throws IOException {
response.setContentType("text/html;charset=utf-8");
PrintWriter out = response.getWriter();
out.write("文件大小超过限制!");
out.flush();
out.close();
}
}
thymeleaf跳转
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1 th:text="${error}"></h1>
</body>
</html>
package com.maaoooo.fileupload.exception;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.multipart.MaxUploadSizeExceededException;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
/**
* @author lzr
* @date 2020 08 17 21:18
* @description
*/
@ControllerAdvice
public class MyException {
// @ExceptionHandler(MaxUploadSizeExceededException.class)
// public void myexception(MaxUploadSizeExceededException e, ServletResponse response, ServletRequest request) throws IOException {
// response.setContentType("text/html;charset=utf-8");
// PrintWriter out = response.getWriter();
// out.write("文件大小超过限制!");
// out.flush();
// out.close();
//
// }
@ExceptionHandler(MaxUploadSizeExceededException.class)
public ModelAndView myexception(MaxUploadSizeExceededException e) throws IOException {
ModelAndView modelAndView = new ModelAndView("error");
modelAndView.addObject("error","文件大小超出范围 ");
return modelAndView;
}
}
8.18 Tuesday
package com.maaoooo.controller_advice;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ModelAttribute;
import java.util.HashMap;
import java.util.Map;
/**
* @author lzr
* @date 2020 08 18 11:07
* @description
*/
@ControllerAdvice
public class GlobalData {//用来做全局数据预设
@ModelAttribute(value = "info")
public Map<String, Object> myData() {
Map<String, Object> map = new HashMap<>();
map.put("name", "Jerry");
map.put("email", "1224337540@qq.com");
return map;
}
}
package com.maaoooo.controller_advice.controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Map;
import java.util.Set;
/**
* @author lzr
* @date 2020 08 18 11:15
* @description 取出全局数据
*/
@RestController
public class HelloController {
@GetMapping("/t1")
public String t1(Model model) {
Map<String, Object> map = model.asMap();
Set<String> keySet = map.keySet();
for (String key : keySet) {
System.out.println(map.get(key));
}
return "hello";
}
}
请求参数预处理
Controller
package com.maaoooo.controller_advice.controller;
import com.maaoooo.controller_advice.pojo.Author;
import com.maaoooo.controller_advice.pojo.Book;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @author lzr
* @date 2020 08 18 20:14
* @description
*/
@RestController
public class BookController {
@PostMapping("/addBook")
public void addBook(@ModelAttribute("b") Book book, @ModelAttribute("a") Author author) {
System.out.println(book);
System.out.println(author);
}
}
Global
package com.maaoooo.controller_advice;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import java.util.HashMap;
import java.util.Map;
/**
* @author lzr
* @date 2020 08 18 11:07
* @description
*/
@ControllerAdvice
public class GlobalData {//用来做全局数据预设
@InitBinder("a")
public void initA(WebDataBinder binder) {
binder.setFieldDefaultPrefix("a.");
}
@InitBinder("b")
public void initB(WebDataBinder binder) {
binder.setFieldDefaultPrefix("b.");
}
}
自定义异常数据
package com.maaoooo.exception;
import org.springframework.boot.web.error.ErrorAttributeOptions;
import org.springframework.boot.web.servlet.error.DefaultErrorAttributes;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.WebRequest;
import java.util.Map;
/**
* @author lzr
* @date 2020 08 18 22:14
* @description 自定义异常 继承DefaultErrirAttributes 重写getErrorAttributes方法
*/
@Component
public class MyError extends DefaultErrorAttributes {
@Override
public Map<String, Object> getErrorAttributes(WebRequest webRequest, ErrorAttributeOptions options) {
Map<String, Object> errorAttributes = super.getErrorAttributes(webRequest, options);
errorAttributes.put("myerror", "自定义异常");
return errorAttributes;
}
}
自定义错误页面
package com.maaoooo.exception;
import org.springframework.boot.autoconfigure.web.ResourceProperties;
import org.springframework.boot.autoconfigure.web.servlet.error.DefaultErrorViewResolver;
import org.springframework.context.ApplicationContext;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;
/**
* @author lzr
* @date 2020 08 18 22:28
* @description 自定义错误页面 继承DefaultErrorViewResolver 重写resolveErrorView
*/
@Component
public class MyErrorViewReslover extends DefaultErrorViewResolver {
@Override
public ModelAndView resolveErrorView(HttpServletRequest request, HttpStatus status, Map<String, Object> model) {
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("DefaultErrorPage");
modelAndView.addAllObjects(model);
return modelAndView;
}
/**
* Create a new {@link DefaultErrorViewResolver} instance.
*
* @param applicationContext the source application context
* @param resourceProperties resource properties
*/
public MyErrorViewReslover(ApplicationContext applicationContext, ResourceProperties resourceProperties) {
super(applicationContext, resourceProperties);
}
}
8.19 Wednesday
系统初始化
package com.maaoooo.interceptor;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
/**
* @author lzr
* @date 2020 08 19 22:10
* @description
*/
@Component
public class MycommandLineRunner implements CommandLineRunner {
@Override
@Order(0) //数字越小启动级别越高
public void run(String... args) throws Exception {
System.out.println("初始化1");
}
}
cors跨域
package com.maaoooo.cors1;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @author lzr
* @date 2020 08 18 22:50
* @description
*/
@RestController
public class HelloController {
@GetMapping("/hello")
// @CrossOrigin("http://localhost:8081") //允许改域访问
public String hello() {
return "hello cors";
}
@PutMapping("doput")
public String doput(){
return "doput";
}
}
全局设定
package com.maaoooo.cors1;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
* @author lzr
* @date 2020 08 19 21:07
* @description
*/
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedOrigins("http://localhost:8081")
.allowedHeaders("*")
.allowedMethods("*")
.maxAge(30 * 1000);
}
}
配置拦截器
package com.maaoooo.interceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* @author lzr
* @date 2020 08 19 21:42
* @description
*/
public class MyInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("preHandle");
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
System.out.println("postHandle");
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
System.out.println("afterHandle");
}
}
package com.maaoooo.interceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
* @author lzr
* @date 2020 08 19 21:44
* @description
*/
@Configuration
public class MvcConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
//拦截所有路径
registry.addInterceptor(myInterceptor()).addPathPatterns("/**");
}
@Bean
public MyInterceptor myInterceptor() {
return new MyInterceptor();
}
}
8.20 Thursday
ApplicationRunner
package com.maaoooo.demo1tomcat;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
/**
* @author lzr
* @date 2020 08 20 22:48
* @description 在web启动时调用
*/
@Component
@Order
public class MyApplicationRunner implements ApplicationRunner {
@Override
public void run(ApplicationArguments args) throws Exception {
System.out.println("程序启动");
}
}
springboot路径映射
package com.maaoooo.pathmapping;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
* @author lzr
* @date 2020 08 20 23:05
* @description
*/
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/test").setViewName("hello");
}
}
springboot使用类型转换器
package com.maaoooo.paramconverter;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Date;
/**
* @author lzr
* @date 2020 08 20 23:28
* @description
*/
@RestController
public class HelloController {
@PostMapping("/hello")
public void hello(Date birth) {
System.out.println(birth);
}
}
package com.maaoooo.paramconverter;
import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* @author lzr
* @date 2020 08 20 23:33
* @description
*/
@Component
public class DateConverter implements Converter<String, Date> {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-mm-dd");
@Override
public Date convert(String s) {
if (s != null && !"".equals(s)) {
try {
return simpleDateFormat.parse(s);
} catch (ParseException e) {
e.printStackTrace();
}
}
return null;
}
}
8.21 Friday
整合aop
导入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
配置切面
package com.maaoooo.aop;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
/**
* @author lzr
* @date 2020 08 21 21:36
* @description
*/
@Component
@Aspect
public class LogComponent {
@Pointcut("execution(* com.maaoooo.aop.service.*.*(..))")
public void pc1() {
}
@Before(value = "pc1()")
public void before(JoinPoint jp) {
String name = jp.getSignature().getName();
System.out.println("before" + name);
}
@After(value = "pc1()")
public void after(JoinPoint jp) {
String name = jp.getSignature().getName();
System.out.println("after" + name);
}
@AfterReturning(value = "pc1()", returning = "result")
public void afterReturn(JoinPoint jp, Object result) {
String name = jp.getSignature().getName();
System.out.println(name + " Returning>>>>>>" + result);
}
@Around(value = "pc1()")
public void around(ProceedingJoinPoint pjp) {
try {
System.out.println("around before");
pjp.proceed();
System.out.println("around after");
} catch (Throwable throwable) {
throwable.printStackTrace();
}
}
}
8.22 Saturday
配置mybaits
通过下面这行配置 可以配置具体的mapper位置。否则得在resources下新建相同的文件夹,或者在pom配置不过滤xml.
mybatis.mapper-locations=classpath:/mapper/*.xml
mapper接口需要加上@Mapper注解,或者在启动类上加@MapperScan
package com.maaoooo.mybatis;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@MapperScan(basePackages = "com.maaoooo.mybatis.mapper")
public class MybatisApplication {
public static void main(String[] args) {
SpringApplication.run(MybatisApplication.class, args);
}
}