springboot项目3——web开发

Spring Boot使用thymeleaf模板引擎开发页面

Spring Boot默认就是使用thymeleaf模板引擎。

pom.xml:

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>

application.properties配置:
Thymeleaf缓存在开发过程中,需要把缓存关闭:

########################################################
###THYMELEAF (ThymeleafAutoConfiguration)
########################################################
#spring.thymeleaf.prefix=classpath:/templates/
#spring.thymeleaf.suffix=.html
#spring.thymeleaf.mode=HTML5
#spring.thymeleaf.encoding=UTF-8
# ;charset=<encoding> is added
#spring.thymeleaf.content-type=text/html
# set to false for hot refresh
spring.thymeleaf.cache=false

编写模板文件src/main/resources/templates/hello.html
springboot项目默认是不允许直接访问template下的文件的,是受保护的。

Spring Boot使用freemarker模板引擎开发页面

pom.xml:

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-freemarker</artifactId>
        </dependency>

application.properties配置:

########################################################
###FREEMARKER (FreeMarkerAutoConfiguration)
########################################################
spring.freemarker.allow-request-override=false
spring.freemarker.cache=true
spring.freemarker.check-template-location=true
spring.freemarker.charset=UTF-8
spring.freemarker.content-type=text/html
spring.freemarker.expose-request-attributes=false
spring.freemarker.expose-session-attributes=false
spring.freemarker.expose-spring-macro-helpers=false
#spring.freemarker.prefix=
#spring.freemarker.request-context-attribute=
#spring.freemarker.settings.*=
#spring.freemarker.suffix=.ftl
#spring.freemarker.template-loader-path=classpath:/templates/#comma-separatedlist
#spring.freemarker.view-names= #whitelistofviewnamesthatcanberesolved

编写模板文件src/main/resources/templates/hello.ftl
thymeleaf和freemarker是可以共存的。

Spring Boot配置jsp支持

JSP 貌似Spring Boot官方不推荐,STS创建的项目会在src/main/resources 下有个templates 目录,这里就是让我们放模版文件的,然后并没有生成诸如 SpringMVC 中的webapp目录。

需要的有:
1.tomcat支持、servlet 依赖、jstl
2.配置响应页面默认后缀、默认前缀目录
3.启动类需要继承SpringBootServletInitializer
具体操作详见这里

在 spring-boot-starter-web 中用 jetty 代替 tomcat

在 spring-boot-starter-web 移除现有的依赖项,并把下面这些添加进去。

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
    <exclusions>
        <exclusion>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
        </exclusion>
    </exclusions>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-jetty</artifactId>
</dependency>

Spring Boot的静态资源处理

Spring Boot的默认配置

/** 映射到 /static (或/public/resources/META-INF/resources
/webjars/** 映射到 classpath:/META-INF/resources/webjars/
PS:上面的 static、public、resources 等目录都在 classpath: 下面(如 src/main/resources/static)。
比如,放在sp1\src\main\resources\static\1.JPG的图片,访问地址是http://127.0.0.1:8080/sp1/1.JPG
优先级顺序为:META-INF/resources > resources > static > public

例如,myapp.js 的路径是 resources\static\js\myapp.js
它在 jsp 中的使用方法
<csript src="/js/myapp.js"></script>

使用 WebMvcAutoConfiguration 配置静态资源映射

在@Configuration注解的配置类上增加@EnableWebMvc(@SpringBootApplication 注解的程序入口类已经包含@Configuration),增加该注解以后WebMvcAutoConfiguration中配置就不会生效,你需要自己来配置需要的每一项。这种情况下的配置还是要多看一下WebMvcAutoConfiguration类。

/myres/* 映射到 classpath:/myres/* (本应该映射到classpath:/static/myres/*)为例:

package org.springboot.sample.config;
import org.springboot.sample.interceptor.MyInterceptor1;
import org.springboot.sample.interceptor.MyInterceptor2;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration
public class MyWebAppConfigurer
       extends WebMvcConfigurerAdapter {

   @Override
   public void addResourceHandlers(ResourceHandlerRegistry registry) {
       registry.addResourceHandler("/myres/**").addResourceLocations("classpath:/myres/");
       super.addResourceHandlers(registry);
   }
}

也可以在配置文件里这么写:

spring:
  #静态页面
  resources:
    static-locations: classpath:/static/**

这样使用代码的方式自定义目录映射,并不影响Spring Boot的默认映射,可以同时使用。
如果我们将/myres/* 修改为 /* 与默认的相同时,则会覆盖系统的配置,可以多次使用 addResourceLocations 添加目录,优先级先添加的高于后添加的,也可以这样写 addResourceLocations(“classpath:/img1/”, “classpath:/img2/”, “classpath:/img3/”);

如果我们要指定一个绝对路径的文件夹(如 D:/data/api_files ),同样使用 addResourceLocations 指定即可。
// 可以直接使用addResourceLocations 指定磁盘绝对路径,同样可以配置多个位置,注意路径写法需要加上file:
registry.addResourceHandler("/api_files/**").addResourceLocations("file:D:/data/api_files/**")
html静态资源引用参考
工作中的:

自定义Servlet、过滤器Filter和监听器Listener

Spring boot 的主 Servlet 为 DispatcherServlet,其默认的url-pattern为“/”。也许我们在应用中还需要定义更多的Servlet。

使用@WebServlet声明这是个Servlet、启动类加@ServletComponentScan扫描相应的Servlet包
具体例子详见这里

过滤器(Filter)和监听器(Listener)一样,声明的注解分别使用@WebFilter、@WebListener
具体例子详见这里

自定义拦截器

功能跟过滤器类似,但是提供更精细的的控制能力:在request被响应之前、request被响应之后、视图渲染之前以及request全部结束之后。我们不能通过拦截器修改request内容,但是可以通过抛出异常(或者返回false)来暂停request的执行。

实现自定义拦截器3步:
1、创建自定义拦截器。通过实现Spring的 HandlerInterceptor 接口(重写preHandle方法,只有返回true才会继续向下执行、重写postHandle方法(请求处理之后进行调用,但是在视图被渲染之前(Controller方法调用之后))、重写afterCompletion方法(在整个请求结束之后被调用,也就是在DispatcherServlet 渲染了对应的视图之后执行(主要是用于进行资源清理工作)))。
2、Web配置。创建一个@Configuration的Java类继承WebMvcConfigurerAdapter,并重写 addInterceptors 方法(添加拦截规则等),Springboot2.0(Spring5.0)下更好的做法还是implements WebMvcConfigurer。。
3、实例化我们自定义的拦截器,然后将对像手动添加到拦截器链中(在addInterceptors方法中添加, super.addInterceptors(registry);)。
只有经过DispatcherServlet 的请求,才会走拦截器链,自定义的Servlet 请求是不会被拦截的。
对于过滤器来说,不管是属于哪个Servlet 只要复合过滤器的过滤规则,过滤器都会拦截。
https://412887952-qq-com.iteye.com/blog/2292476

性能优化

如果项目比较大,类比较多,不使用@SpringBootApplication,采用@Compoment指定扫包范围
在项目启动时设置JVM初始内存和最大内存相同
将springboot内置服务器由tomcat设置为undertow

安全问题

安全问题

CSRF 攻击

CSRF 代表跨站请求伪造。这是一种攻击,迫使最终用户在当前通过身份验证的Web 应用程序上执行不需要的操作。CSRF 攻击专门针对状态改变请求,而不是数据窃取,因为攻击者无法查看对伪造请求的响应。

跨域问题

现代浏览器出于安全的考虑, HTTP 请求时必须遵守同源策略,否则就是跨域的 HTTP 请求,默认情况下是被禁止的,IP(域名)不同、或者端口不同、协议不同(比如 HTTP、HTTPS)都会造成跨域问题。

后来 HTML5 支持了 CORS 协议。CORS 是一个 W3C 标准,全称是”跨域资源共享”(Cross-origin resource sharing),允许浏览器向跨源服务器,发出 XMLHttpRequest 请求,从而克服了 AJAX 只能同源使用的限制。它通过服务器增加一个特殊的 Header[Access-Control-Allow-Origin]来告诉客户端跨域的限制,如果浏览器支持 CORS、并且判断 Origin 通过的话,就会允许 XMLHttpRequest 发起跨域请求。
前端使用了 CORS 协议,就需要后端设置支持非同源的请求,Spring Boot 设置支持非同源的请求有两种方式。

配置 CorsFilter

@Configuration
public class GlobalCorsConfig {
    @Bean
    public CorsFilter corsFilter() {
        CorsConfiguration config = new CorsConfiguration();
          config.addAllowedOrigin("*");
          config.setAllowCredentials(true);
          config.addAllowedMethod("*");
          config.addAllowedHeader("*");
          config.addExposedHeader("*");

        UrlBasedCorsConfigurationSource configSource = new UrlBasedCorsConfigurationSource();
        configSource.registerCorsConfiguration("/**", config);

        return new CorsFilter(configSource);
    }
}

在启动类上配置

public class Application extends WebMvcConfigurerAdapter {  

    @Override  
    public void addCorsMappings(CorsRegistry registry) {  

        registry.addMapping("/**")  
                .allowCredentials(true)  
                .allowedHeaders("*")  
                .allowedOrigins("*")  
                .allowedMethods("*");  

    }  
} 

一个http请求,先走filter,到达servlet后才进行拦截器的处理,如果我们把cors放在filter里,就可以优先于权限拦截器执行。

posted @ 2019-04-10 20:07  cashew  阅读(212)  评论(0编辑  收藏  举报