【SpringBoot】| SpringBoot 和 web组件

客官°小女子只卖身不卖艺 2024-03-26 17:28 149阅读 0赞

目录

一:SpringBoot 和 web组件

  1. SpringBoot中使用拦截器Interceptor(重点)

  2. SpringBoot中使用Servlet

  3. SpringBoot中使用过滤器Filter(重点)

  4. 字符集过滤器的应用

    图书推荐:《硅基物语·我是灵魂画手》


一:SpringBoot 和 web组件

1. SpringBoot中使用拦截器Interceptor(重点)

拦截器是SpringMVC中一种对象,能够拦截器对Controller的请求!

拦截器框架中有系统的拦截器, 还可以自定义拦截器, 实现对请求预先处理!

实现自定义拦截器:

第一步:创建一个类实现SpringMVC框架的HandlerInterceptor接口,重写方法。

HandlerInterceptor接口源码中有三个默认方法,常用的是preHandle方法中进行拦截:

  1. package org.springframework.web.servlet;
  2. import javax.servlet.http.HttpServletRequest;
  3. import javax.servlet.http.HttpServletResponse;
  4. import org.springframework.lang.Nullable;
  5. public interface HandlerInterceptor {
  6. default boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
  7. return true;
  8. }
  9. default void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {
  10. }
  11. default void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
  12. }
  13. }

编写LoginInterceptor类实现HandlerInterceptor接口,并重写preHandler方法

  1. package com.zl.web;
  2. import org.springframework.web.servlet.HandlerInterceptor;
  3. import javax.servlet.http.HttpServletRequest;
  4. import javax.servlet.http.HttpServletResponse;
  5. // 自定义拦截器
  6. public class LoginInterceptor implements HandlerInterceptor {
  7. /**
  8. * @param request
  9. * @param response
  10. * @param handler 被拦截的控制器对象
  11. * @return boolean,true:表示请求能被Controller处理,false:表示被截断
  12. * @throws Exception
  13. */
  14. @Override
  15. public boolean preHandle(HttpServletRequest request,
  16. HttpServletResponse response,
  17. Object handler) throws Exception { // handler是被拦截的控制器对象
  18. System.out.println("请求拦截器执行了");
  19. return true;
  20. }
  21. }

第二步:SpringBoot中注册声明拦截器

SpringMVC框架中注册声明拦截器

  1. <mvc:interceptors>
  2. <mvc:interceptor>
  3. <mvc:path="url" />
  4. <bean class="拦截器类全限定名称"/>
  5. </mvc:interceptor>
  6. </mvc:interceptors>

SpringBoot框架中注册声明拦截器

(1)使用类+注解的方式,编写一个类实现WebMvcConfigurer接口(这个接口很重要,很多与SpringMVC有关的功能都在这,并添加@Configuration注解,关于SpringMVC有关的功能都在WebMvcConfigurer接口中实现了!

(2)重写addInterceptors方法,在方法中添加拦截器对象,注入到容器当中;然后在调用addPathPatterns添加拦截的请求,再调用excludePathPatterns排除拦截的请求。

  1. package com.zl.config;
  2. import com.zl.web.LoginInterceptor;
  3. import org.springframework.context.annotation.Configuration;
  4. import org.springframework.web.servlet.HandlerInterceptor;
  5. import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
  6. import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
  7. @Configuration // 这个类当做配置文件使用
  8. public class MyAppConfigurer implements WebMvcConfigurer {
  9. // 添加拦截器对象,注入到容器中
  10. @Override
  11. public void addInterceptors(InterceptorRegistry registry) {
  12. // 创建拦截器对象
  13. HandlerInterceptor interceptor = new LoginInterceptor();
  14. // 调用addInterceptor方法表示注入到容器中
  15. // 调用addPathPatterns方法表示可以拦截的请求
  16. // 调用excludePathPatterns方法表示通过的请求
  17. registry.addInterceptor(interceptor)
  18. .addPathPatterns("/user/**")
  19. .excludePathPatterns("/user/login");
  20. }
  21. }

第三步:编写controller进行访问

  1. package com.zl.controller;
  2. import org.springframework.stereotype.Controller;
  3. import org.springframework.web.bind.annotation.RequestMapping;
  4. import org.springframework.web.bind.annotation.ResponseBody;
  5. @Controller
  6. public class BootController {
  7. @RequestMapping("/user/account") // 会被拦截
  8. @ResponseBody
  9. public String userAccount(){
  10. return "访问user/account地址";
  11. }
  12. @RequestMapping("/user/login")
  13. @ResponseBody
  14. public String userLogin(){
  15. return "访问user/login地址"; // 会被通过
  16. }

2. SpringBoot中使用Servlet

在SpringBoot框架中使用Servlet对象!

使用步骤:

②创建Servlet类继承HttpServlet类

注册Servlet ,让框架能找到Servlet。

第一步:创建Servlet类继承HttpServlet

重写doGet和doPost方法,并且在doGet中调用doPost方法,这样不论发过来post请求还是get请求都没有问题!

  1. package com.zl.web;
  2. import javax.servlet.ServletException;
  3. import javax.servlet.http.HttpServlet;
  4. import javax.servlet.http.HttpServletRequest;
  5. import javax.servlet.http.HttpServletResponse;
  6. import java.io.IOException;
  7. import java.io.PrintWriter;
  8. public class MyServlet extends HttpServlet {
  9. @Override
  10. protected void doGet(HttpServletRequest request, HttpServletResponse response)
  11. throws ServletException, IOException {
  12. // 调用doPost方法
  13. doPost(request,response);
  14. }
  15. @Override
  16. protected void doPost(HttpServletRequest request, HttpServletResponse response)
  17. throws ServletException, IOException {
  18. // 使用HttpServletResponse输出数据,应答结果
  19. response.setContentType("text/html;charset=UTF-8");
  20. PrintWriter out = response.getWriter();
  21. out.println("执行的是Servlet");
  22. out.flush();
  23. out.close();
  24. }
  25. }

第二步:注册Servlet ,让框架能找到Servlet

(1)ServletRegistrationBean用来做在 servlet 3.0+容器中注册 servlet 的功能,但更具有 SpringBean友好性。

(2)首先写一个类,类名随意,加上@Configuration注解,表示这个类是配置信息的类;再类中编写一个servletRegistrationBean()方法返回值是ServletRegistrationBean对象

(3)添加上@Bean注解。@Bean用于将对象存入spring的ioc容器中,同@controller、@Service、@Component、@Configuration、@Repository等几个注解是一样的,都是负责将对象存入容器当中。只不过方式不同,四个注解它们是用在类上面的,然后将当前类通过无参构造函数创建对象然后放入容器;而@Bean是用在方法上,将当前方法的返回值对象放到容器当中!可以理解为前者是由spring自动创建对象,而@Bean创建对象是交给我们自己来控制。

  1. package com.zl.config;
  2. import com.zl.web.MyServlet;
  3. import org.springframework.boot.web.servlet.ServletRegistrationBean;
  4. import org.springframework.context.annotation.Bean;
  5. import org.springframework.context.annotation.Configuration;
  6. import javax.servlet.Servlet;
  7. import javax.servlet.http.HttpServlet;
  8. @Configuration
  9. public class WebAppConfig {
  10. // 定义方法,注册Servlet对象
  11. @Bean // 把ServletRegistrationBean对象放到容器当中
  12. public ServletRegistrationBean servletRegistrationBean(){
  13. // 创建ServletRegistrationBean对象,有两个参数:
  14. // 一个参数是servlet,一个参数是url地址
  15. HttpServlet servlet = new MyServlet();
  16. ServletRegistrationBean bean = new ServletRegistrationBean(servlet,"/myservlet");
  17. return bean;
  18. }
  19. }

当然也可以使用无参数构造方法,调用引用.set方法进行赋值,对于路径也可以赋多个

  1. ServletRegistrationBean bean = new ServletRegistrationBean();
  2. bean.setServlet(servlet);
  3. bean.addUrlMappings("/login","/test"); // 多个路径都可以访问

3. SpringBoot中使用过滤器Filter(重点)

Filter是Servlet规范中的过滤器,可以处理请求、对请求的参数、属性进行调整; 常常在过滤器中处理字符编码。

使用步骤:

①创建自定义过滤器类;

②注册Filter过滤器对象;

注:对于过滤器和拦截器的简单理解

(1)过滤器是用来过滤request或者response参数的(比如:增加一些乱码),侧重于对数据的过滤;

(2)而拦截器是用来验证请求的,能够截断请求!

第一步:创建自定义过滤器类

创建MyFilter类实现Filter接口重写doFilter方法,进行处理;处理好以后调用filterChain参数的doFilter方法,把请求传递出去,继续进行下一步操作。

  1. package com.zl.web;
  2. import javax.servlet.*;
  3. import java.io.IOException;
  4. // 自定义过滤器类
  5. public class MyFilter implements Filter {
  6. @Override
  7. public void doFilter(ServletRequest request,
  8. ServletResponse response,
  9. FilterChain filterChain) throws IOException, ServletException {
  10. // 处理字符集编码
  11. response.setContentType("text/html;charset=UTF-8");
  12. System.out.println("Filter过滤器执行了");
  13. // 把请求转发出去
  14. filterChain.doFilter(request,response);
  15. }
  16. }

第二步:注册过滤器对象

写一个配置类,类名随意,加上@Configuration注解,表示这个类是配置信息的类;再类中编写一个filterRegistrationBean()方法返回值是FilterRegistrationBean对象,并在方法上加上@Bean注解,把返回的对象交给Spring容器管理。

  1. package com.zl.config;
  2. import com.zl.web.MyFilter;
  3. import org.springframework.boot.web.servlet.FilterRegistrationBean;
  4. import org.springframework.context.annotation.Bean;
  5. import org.springframework.context.annotation.Configuration;
  6. import javax.servlet.FilterRegistration;
  7. @Configuration
  8. public class WebApplicationConfig {
  9. @Bean
  10. public FilterRegistrationBean filterRegistrationBean (){
  11. // 调用无参数构造方法
  12. FilterRegistrationBean bean = new FilterRegistrationBean();
  13. bean.setFilter(new MyFilter()); // 指定过滤器对象
  14. bean.addUrlPatterns("/user/*"); // 指定过滤的地址
  15. return bean;
  16. }
  17. }

编写controller进行访问

  1. package com.zl.controller;
  2. import org.springframework.stereotype.Controller;
  3. import org.springframework.web.bind.annotation.RequestMapping;
  4. import org.springframework.web.bind.annotation.ResponseBody;
  5. @Controller
  6. public class CustomerFilterController {
  7. @RequestMapping("/user/account")
  8. @ResponseBody
  9. public String userAccount(){
  10. return "user/account执行了";
  11. }
  12. }

4. 字符集过滤器的应用

CharacterEncodingFilter:解决post请求中乱码的问题;在SpringMVC框架, 在web.xml注册过滤器,配置它的属性,解决乱码问题!

33b59a662d7546bb9755db4fbbc64882.png

创建一个Servlet

  1. package com.zl.servlet;
  2. import javax.servlet.ServletException;
  3. import javax.servlet.http.HttpServlet;
  4. import javax.servlet.http.HttpServletRequest;
  5. import javax.servlet.http.HttpServletResponse;
  6. import java.io.IOException;
  7. import java.io.PrintWriter;
  8. public class MyServlet extends HttpServlet {
  9. @Override
  10. protected void doGet(HttpServletRequest request, HttpServletResponse response)
  11. throws ServletException, IOException {
  12. doPost(request,response);
  13. }
  14. @Override
  15. protected void doPost(HttpServletRequest request, HttpServletResponse response)
  16. throws ServletException, IOException {
  17. response.setContentType("text/html");
  18. PrintWriter out = response.getWriter();
  19. out.println("在Servlet中使用中文");
  20. out.flush();
  21. out.close();
  22. }
  23. }

注册Servlet

  1. package com.zl.web;
  2. import com.zl.servlet.MyServlet;
  3. import org.springframework.boot.web.servlet.ServletRegistrationBean;
  4. import org.springframework.context.annotation.Bean;
  5. import org.springframework.stereotype.Controller;
  6. @Controller
  7. public class WebAppConfig {
  8. // 注册Servlet
  9. @Bean
  10. public ServletRegistrationBean servletRegistrationBean(){
  11. MyServlet myServlet = new MyServlet();
  12. ServletRegistrationBean bean = new ServletRegistrationBean(myServlet, "/myservlet");
  13. return bean;
  14. }
  15. }

进行访问:发现中文乱码

30e43c1363fb4fb9a9512207edf1099b.png

F12,刷新请求并打开,发现默认的编码方式是:ISO-8859-1

2772e243d60841d1b85ea2bddb1ac500.png

第一种解决方式:自定义过滤器,比较麻烦,不推荐

①在注册Servlet中添加过滤器

  1. package com.zl.web;
  2. import com.zl.servlet.MyServlet;
  3. import org.springframework.boot.web.servlet.FilterRegistrationBean;
  4. import org.springframework.boot.web.servlet.ServletRegistrationBean;
  5. import org.springframework.context.annotation.Bean;
  6. import org.springframework.stereotype.Controller;
  7. import org.springframework.web.filter.CharacterEncodingFilter;
  8. @Controller
  9. public class WebAppConfig {
  10. // 注册Servlet
  11. @Bean
  12. public ServletRegistrationBean servletRegistrationBean(){
  13. MyServlet myServlet = new MyServlet();
  14. ServletRegistrationBean bean = new ServletRegistrationBean(myServlet, "/myservlet");
  15. return bean;
  16. }
  17. // 注册Filter
  18. @Bean
  19. public FilterRegistrationBean filterRegistrationBean(){
  20. FilterRegistrationBean bean = new FilterRegistrationBean();
  21. // 使用框架中的字符过滤器
  22. CharacterEncodingFilter filter = new CharacterEncodingFilter();
  23. // 指定使用的编码方式
  24. filter.setEncoding("UTF-8");
  25. // 指定request,response使用encoding的值
  26. filter.setForceEncoding(true);
  27. // 给filter设置参数
  28. bean.setFilter(filter);
  29. bean.addUrlPatterns("/*"); // 过滤所有的地址
  30. return bean;
  31. }
  32. }

②修改application.properties文件, 让自定义的过滤器起作用

默认使用的是系统配置好的

967910a3a74846d2ac7f4ffbedeadf29.png

让自己的配置生效

(1)SpringBoot中默认已经配置启用了CharacterEncodingFilter,编码默认ISO-8859-1;
(2)设置enabled=false 作用是关闭系统中配置好的过滤器, 使用自定义的CharacterEncodingFilter;

  1. server.servlet.encoding.enabled=false

第二种方式:直接使用框架中的过滤器,比较简单,推荐使用

注:实际上SpringBoot已经把字符编码的过滤器自动纳入容器管理了,通过源码分析可以发现这个配置与配置文件application.properties中的server.servlet.encoding配置进行了绑定。

  1. package org.springframework.boot.autoconfigure.web.servlet;
  2. import org.springframework.boot.autoconfigure.AutoConfiguration;
  3. import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
  4. import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
  5. import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
  6. import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
  7. import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication.Type;
  8. import org.springframework.boot.autoconfigure.web.ServerProperties;
  9. import org.springframework.boot.context.properties.EnableConfigurationProperties;
  10. import org.springframework.boot.web.server.WebServerFactoryCustomizer;
  11. import org.springframework.boot.web.servlet.filter.OrderedCharacterEncodingFilter;
  12. import org.springframework.boot.web.servlet.server.ConfigurableServletWebServerFactory;
  13. import org.springframework.boot.web.servlet.server.Encoding;
  14. import org.springframework.context.annotation.Bean;
  15. import org.springframework.core.Ordered;
  16. import org.springframework.web.filter.CharacterEncodingFilter;
  17. @AutoConfiguration
  18. @EnableConfigurationProperties({ServerProperties.class})
  19. @ConditionalOnWebApplication(
  20. type = Type.SERVLET
  21. )
  22. @ConditionalOnClass({CharacterEncodingFilter.class})
  23. @ConditionalOnProperty(
  24. prefix = "server.servlet.encoding",
  25. value = {"enabled"},
  26. matchIfMissing = true
  27. )
  28. public class HttpEncodingAutoConfiguration {
  29. private final Encoding properties;
  30. public HttpEncodingAutoConfiguration(ServerProperties properties) {
  31. this.properties = properties.getServlet().getEncoding();
  32. }
  33. // 自动装入了容器中去
  34. @Bean
  35. @ConditionalOnMissingBean
  36. public CharacterEncodingFilter characterEncodingFilter() {
  37. CharacterEncodingFilter filter = new OrderedCharacterEncodingFilter();
  38. filter.setEncoding(this.properties.getCharset().name());
  39. filter.setForceRequestEncoding(this.properties.shouldForce(org.springframework.boot.web.servlet.server.Encoding.Type.REQUEST));
  40. filter.setForceResponseEncoding(this.properties.shouldForce(org.springframework.boot.web.servlet.server.Encoding.Type.RESPONSE));
  41. return filter;
  42. }
  43. @Bean
  44. public LocaleCharsetMappingsCustomizer localeCharsetMappingsCustomizer() {
  45. return new LocaleCharsetMappingsCustomizer(this.properties);
  46. }
  47. static class LocaleCharsetMappingsCustomizer implements WebServerFactoryCustomizer<ConfigurableServletWebServerFactory>, Ordered {
  48. private final Encoding properties;
  49. LocaleCharsetMappingsCustomizer(Encoding properties) {
  50. this.properties = properties;
  51. }
  52. public void customize(ConfigurableServletWebServerFactory factory) {
  53. if (this.properties.getMapping() != null) {
  54. factory.setLocaleCharsetMappings(this.properties.getMapping());
  55. }
  56. }
  57. public int getOrder() {
  58. return 0;
  59. }
  60. }
  61. }

直接修改application.properties文件进行更改

第一种方式:使用的是自己定义的过滤器,然后让系统的关闭,让自己的生效,比较麻烦;

第二种方式:就是用系统已经配置好的,我们直接修改内部参数的编码方式即可;

  1. #让系统的CharacterEncdoingFilter生效,默认就是开启的,不写也行
  2. server.servlet.encoding.enabled=true
  3. #直接指定使用的编码方式
  4. server.servlet.encoding.charset=utf-8
  5. #直接强制request,response都使用charset属性的值
  6. server.servlet.encoding.force=true

图书推荐:《硅基物语·我是灵魂画手》

当AI遇上绘画,会打开怎样的奇妙世界?

用ChatGPT+Midjourney西出人类的灵魂与梦想

用StableDiffusion+D-ID画出青春绚丽的渴望

激活每个人隐藏的绘画天赋

人人都能成为顶尖绘画大师

如果你问我对于 AI绘画的态度,我会告诉你:新生事物是强大的,它们终将迅猛发展起来,并取代旧事物。这并不是说AI绘画作品会取代此前人类的绘画成果和艺术结品,而是作为一个“过滤网”般的存在,不断地过滤绘画领域的杂质,提升人类绘画的整体水平,并在人类生活中占据越来越重要的地位。

在未来,AI将会成为人类最得心应手的“画笔”,帮助人们成为“神笔马良”,就算是一个普通人,也可以借助 AI成为顶尖的画师。

内容简介

一本将AI绘画讲透的探秘指南,通过丰富的实践案例操作,通俗易懂地讲述AI绘画的生成步骤生动展现了AI绘画的魔法魅力。从历史到未来,跨越百年时空,从理论到实践,讲述案例操作:从技术到哲学,穿越多个维度,从语言到绘画,落地实战演练。AI绘画的诞生,引发了奇点降临,点亮了AGI(通用人工智能),并涉及 Prompt、风格,技术细节、多模态交互,AIGC等一系列详细讲解。让您轻松掌握生图技巧,创造出独特的艺术作品,书写属于自己的艺术时代。

0a234a140b494f51b3730d26b4c8e7a6.png

当当网链接:http://product.dangdang.com/29601870.html

发表评论

表情:
评论列表 (有 0 条评论,149人围观)

还没有评论,来说两句吧...

相关阅读