日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

spring boot 整合web开发(二)

發(fā)布時(shí)間:2025/1/21 编程问答 23 豆豆
生活随笔 收集整理的這篇文章主要介紹了 spring boot 整合web开发(二) 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

目錄

?


  • 自定義錯(cuò)誤頁
  • CORS支持(前端跨域請求)
  • 攔截器HandlerInterceptor
  • 啟動系統(tǒng)任務(wù)
  • springboot配置AOP
  • 整合servlet、filter、listener

?下圖為本節(jié)內(nèi)容

?

1、自定義錯(cuò)誤頁

springboot中默認(rèn)錯(cuò)誤是由BasicErrorController類來處理的,該類核心方法有errorHtml(返回Html),error(返回json),DefaultErrorViewResolver是Springboot默認(rèn)錯(cuò)誤解析器。該類源碼中可以看出4xx、5xx文件作為錯(cuò)誤視圖,找不到會回到errorHtml方法中,使用error作為默認(rèn)的錯(cuò)誤頁面視圖。

1)、自定義Error數(shù)據(jù)

BasicErrorController的errorHtml、error都是通過getErrorAttributes方法獲取error信息。該方法會調(diào)用DefaultErrorAttributes類的getErrorAttributes方法,而DefaultErrorAttributes類是在ErrorMvcAutoCongfigutration默認(rèn)提供的。

@Bean @ConditionalOnMissingBean(value = {ErrorAttributes.class},search = SearchStrategy.CURRENT ) public DefaultErrorAttributes errorAttributes() {return new DefaultErrorAttributes(this.serverProperties.getError().isIncludeException()); }

從這段源碼可以看出,當(dāng)系統(tǒng)沒有聽過ErrorAttributes時(shí)才會采用DefaultErrorAttributes,因此自定義錯(cuò)誤時(shí),只需要自己提供一個(gè)ErrorAttributes。

@Component public class MyErrorAttribute extends DefaultErrorAttributes {@Overridepublic Map<String, Object> getErrorAttributes(WebRequest webRequest, boolean includeStackTrace) {Map<String, Object> errorAttributes = super.getErrorAttributes(webRequest, includeStackTrace);errorAttributes.put("custommsg","出錯(cuò)了");errorAttributes.remove("error");return errorAttributes;} }

?

2)、自定義error視圖

BasicErrorController的errorHtml方法中調(diào)用resolveErrorView方法獲取一個(gè)ModelAndView實(shí)例。resolveErrorView是由ErrorViewResolver提供的。

@Bean @ConditionalOnBean({DispatcherServlet.class}) @ConditionalOnMissingBean public DefaultErrorViewResolver conventionErrorViewResolver() {return new DefaultErrorViewResolver(this.applicationContext, this.resourceProperties); }

?

?想要自定義自己的視圖,只需要提供自己的ErrorViewResolver

@Component public class MyErrorViewResolver implements ErrorViewResolver {@Overridepublic ModelAndView resolveErrorView(HttpServletRequest request, HttpStatus status, Map<String, Object> model) {ModelAndView modelAndView = new ModelAndView("errorPage");modelAndView.addObject("custommsg","出錯(cuò)了");modelAndView.addAllObjects(model);return modelAndView;} }

?3)、自定義視圖和自定義數(shù)據(jù)

查看Error自動化配置類ErrorMvcAutoConfiguration,BasicErrorController是一個(gè)默認(rèn)的配置。

@Bean @ConditionalOnMissingBean(value = {ErrorController.class},search = SearchStrategy.CURRENT ) public BasicErrorController basicErrorController(ErrorAttributes errorAttributes) {return new BasicErrorController(errorAttributes, this.serverProperties.getError(), this.errorViewResolvers); }

?

從這段源碼可以看到,如果沒有提供自己的ErrorController,則springboot提供BasicErrorController作為默認(rèn)的ErrorController。

@Controller public class MyErrorController extends BasicErrorController {public MyErrorController(ErrorAttributes errorAttributes, ServerProperties serverProperties,List<ErrorViewResolver> errorViewResolvers) {super(errorAttributes,serverProperties.getError(),errorViewResolvers);}@Overridepublic ModelAndView errorHtml(HttpServletRequest request, HttpServletResponse response) {HttpStatus status = getStatus(request);Map<String, Object> model =getErrorAttributes(request, isIncludeStackTrace(request, MediaType.TEXT_HTML));model.put("custommsg","出錯(cuò)了");ModelAndView modelAndView = new ModelAndView("myErrorPage",model,status);return modelAndView;}@Overridepublic ResponseEntity<Map<String, Object>> error(HttpServletRequest request) {Map<String, Object> errorAttributes = getErrorAttributes(request, isIncludeStackTrace(request, MediaType.ALL));errorAttributes.put("custommsg","出錯(cuò)了");HttpStatus status = getStatus(request);return new ResponseEntity<>(errorAttributes,status);} }

?

?2、CORS支持(前端跨域請求)

配置跨域可以在方法上加注解、全局配置。

在方法上加注解

@PostMapping("/book") @CrossOrigin(value = "http://localhost:8081",maxAge = 1800,allowedHeaders = "*") public String addBook(String name) {return "receive:" + name; }

全局配置

//跨域全局配置 @Override public void addCorsMappings(CorsRegistry registry) {registry.addMapping("/book/**").allowedHeaders("*").allowedMethods("*").maxAge(1800).allowedOrigins("http://localhost:8081"); }

?

?3、攔截器HandlerInterceptor

配置攔截器,定義配置類進(jìn)行攔截器的配置

@Override public void addInterceptors(InterceptorRegistry registry) {registry.addInterceptor(new MyInterceptor()).addPathPatterns("/**").excludePathPatterns("/static/**"); }

?4、啟動系統(tǒng)任務(wù)

1)、CommandLineRunner

/*** CommandLineRunner 系統(tǒng)啟動時(shí)加載參數(shù)* @author shuliangzhao* @Title: MyCommandLineRunner* @ProjectName spring-boot-learn* @Description: TODO* @date 2019/7/21 12:34*/ @Component @Order(1) public class MyCommandLineRunner implements CommandLineRunner {@Overridepublic void run(String... args) throws Exception {System.out.println("Runner>>>" + Arrays.toString(args));} }

2)、ApplicationRunner

/*** --name = zhangsan getOptionNames getOptionValues* 路遙 平凡的世界 getNonOptionArgs取值* @author shuliangzhao* @Title: MyApplicationRunner* @ProjectName spring-boot-learn* @Description: TODO* @date 2019/7/21 12:36*/ @Component public class MyApplicationRunner implements ApplicationRunner {@Overridepublic void run(ApplicationArguments args) throws Exception {List<String> nonOptionArgs = args.getNonOptionArgs();System.out.println("nonOptionArgs>>>" + nonOptionArgs);Set<String> optionNames = args.getOptionNames();for (String optionName:optionNames) {System.out.println("key:" + optionName + ";value:" + args.getOptionValues(optionName));}} }

?5、springboot配置AOP

Joinpoint:連接點(diǎn),類里面可以被增強(qiáng)的方法即為連接點(diǎn),例如想修改哪個(gè)方法的功能,那么這個(gè)方法即為連接點(diǎn) Pointcut:切入點(diǎn),對于Joinpoint進(jìn)行攔截的定義即為切入點(diǎn),例如攔截所有的insert Advice:通知,攔截到Joinpoint之后所要做的事就是通知, Aspect:切面,Pointcut和Advice的結(jié)合 Target:目標(biāo)對象,要增強(qiáng)類為target @Component @Aspect public class LogAspect {@Pointcut("execution(* com.sl.service.*.*(..))")public void pc() {}@Before(value = "pc()")public void before(JoinPoint jp) {String name = jp.getSignature().getName();System.out.println(name + "方法開始執(zhí)行...");}@After(value = "pc()")public void after(JoinPoint jp) {String name = jp.getSignature().getName();System.out.println(name + "方法執(zhí)行結(jié)束...");}@AfterReturning(value = "pc()",returning = "result")public void afterReturning(JoinPoint jp,Object result) {String name = jp.getSignature().getName();System.out.println(name + "方法返回值為:" + result);}@AfterThrowing(value = "pc()",throwing = "e")public void afterThrowing(JoinPoint jp,Exception e) {String name = jp.getSignature().getName();System.out.println(name + "方法拋出異常,異常時(shí):" + e);}@Around("pc()")public Object around(ProceedingJoinPoint pj) throws Throwable {return pj.proceed();} }

?6、整合servlet、filter、listener

以servle為例,需要在啟動類上加上@ServletComponentScan

@WebServlet public class MyHttpServlet extends HttpServlet {@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {System.out.println("name>>>" + req.getParameter("name"));}@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {super.doGet(req, resp);} }

總結(jié)

以上是生活随笔為你收集整理的spring boot 整合web开发(二)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。