3、SpringBoot Web开发

  • Springboot web实际上就是在SpringMvc上做了进一步的封装,同时引入自己的很多特性和思想,使开发进一步简化。
  • 扩展:(1)如果Spring Boot提供的Sping MVC不符合要求,则可以通过一个配置类(注解有@Configuration的类)加上@EnableWebMvc注解来实现完全自己控制的MVC配置。(2)通常情况下,Spring Boot的自动配置是符合我们大多数需求的,在你既需要保留Spring Boot提供的便利,有需要增加自己的额外的配置的时候,可以定义一个配置类并实现WebMvcConfigurer或者继承WebMvcConfigurationSupport 类,无需使用@EnableWebMvc注解。

一、Springboot整合thymleaf模板

1、Springboot模板简介

  • Spring Boot提供了默认配置的模板引擎主要有以下几种:Thymeleaf
    、FreeMarker、Velocity、Groovy、Mustache等模板引擎
  • 当你使用上述模板引擎中的任何一个,它们默认的模板配置路径为:src/main/resources/templates;静态资源放置在src/main/resources/static目录下面。

2、使用案例

(1)引入依赖


    org.springframework.boot
    spring-boot-starter-thymeleaf

(2)controller类

@Controller
public class ThymleafController {

    @RequestMapping("/index")
    public String index(ModelMap map) {
        // 加入一个属性,用来在模板中读取
        map.addAttribute("host", "http://blog.didispace.com");
        // return模板文件的名称,对应src/main/resources/templates/index.html
        return "index";  
    }
}

(3)在templates下面创建thymleaf文件,index.html




    
    


Hello World

(4)核心配置文件中配置

  • Thymeleaf的默认参数配置
# Enable template caching.
spring.thymeleaf.cache=true 
# Check that the templates location exists.
spring.thymeleaf.check-template-location=true 
# Content-Type value.
spring.thymeleaf.content-type=text/html 
# Enable MVC Thymeleaf view resolution.
spring.thymeleaf.enabled=true 
# Template encoding.
spring.thymeleaf.encoding=UTF-8 
# Comma-separated list of view names that should be excluded from resolution.
spring.thymeleaf.excluded-view-names= 
# Template mode to be applied to templates. See also StandardTemplateModeHandlers.
spring.thymeleaf.mode=HTML5 
# Prefix that gets prepended to view names when building a URL.
spring.thymeleaf.prefix=classpath:/templates/ 
# Suffix that gets appended to view names when building a URL.
spring.thymeleaf.suffix=.html  
spring.thymeleaf.template-resolver-order= # Order of the template resolver in the chain. 
spring.thymeleaf.view-names= # Comma-separated list of view names that can be resolved.

可以参考博文:http://tengj.top/2017/03/13/springboot4/

二、文件上传和下载

  • 上传到本地服务器
    (1)客户端


download

(2)文件上传和下载controller类

@RestController
public class UpAndDownFileController {

    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    public String upload(HttpServletRequest request, MultipartFile[] files) {
        try {
            //获取web项目的全路径
            //  String uploadDir = request.getSession().getServletContext().getRealPath("/");
            //获取自定义目录
            String uploadDir = "F://a";
            File file = new File(uploadDir);
            if (!file.exists()) {
                file.mkdir();
            }
            for (int i = 0; i < files.length; i++) {
                if (files[i] != null) {
                    //进行文件上传
                    uploadFile(uploadDir, files[i]);
                }

            }
            return "success";
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "error";
    }

    private void uploadFile(String dir, MultipartFile file) throws IOException {
        String fileSuffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        String fileName = UUID.randomUUID() + fileSuffix;
        File serverFile = new File(dir + fileName);
        file.transferTo(serverFile);
    }
    @RequestMapping("/download")
    public String downloadFile(HttpServletRequest request, HttpServletResponse response) {
        String fileName = "a.txt";// 设置文件名,根据业务需要替换成要下载的文件名
        if (fileName != null) {
            //设置文件路径
            String realPath = "f://a";
            File file = new File(realPath , fileName);
            if (file.exists()) {
                //response.setContentType("application/octet-stream");
                response.setContentType("application/force-download");// 设置强制下载不打开
                response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);// 设置文件名
                byte[] buffer = new byte[1024];
                FileInputStream fis = null;
                BufferedInputStream bis = null;
                try {
                    fis = new FileInputStream(file);
                    bis = new BufferedInputStream(fis);
                    OutputStream os = response.getOutputStream();
                    int i = bis.read(buffer);
                    while (i != -1) {
                        os.write(buffer, 0, i);
                        i = bis.read(buffer);
                    }
                    System.out.println("success");
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (bis != null) {
                        try {
                            bis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (fis != null) {
                        try {
                            fis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
        return null;
    }

}
  • 上传到图片服务器(下次讨论)

三、Springboot web静态问价路径规则

  • Spring Boot默认提供静态资源目录位置需置于classpath下,目录名需符合如下规则:

/static
/public
/resources
/META-INF/resources

  • SpringBoot默认给我们配置了静态资源的地址转发,我们只需要将静态文件放到/resources/static目录下,就可以直接访问了但是这样往往会暴露给用户我们的项目结构,针对这一点我们需要修改静态资源的路径.
@Configuration
public class Chapter9Configuration extends WebMvcConfigurationSupport 
{
//自定义静态资源文件路径,访问http://localhost/resources/a.js则
//会直接定位到项目根目录下面的/my/static/
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
       registry.addResourceHandler("/resources/**")
              .addResourceLocations("classpath:/my/static/");
    }
}

四、拦截器使用

  • 拦截器是一个重要的概念,可以做很多的事情。拦截器主要是在进入接口方法之前和执行完接口返回数据给前台之前进行响应的逻辑操作。拦截器可以完成比如:日志的记录,ip黑白名单拦截,ip限流、用户登录状态拦截,安全拦截等等。
  • 注意在整个项目中只有一个WebMvcConfigurationSupport类出现,否则其他不生效

(1)简单使用

1、创建拦截器
public class MyInterceptor implements HandlerInterceptor {
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("在DispatcherServlet渲染页面之前执行");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("在完成所有请求处理后,也就是说在渲染完页面后,返回前台之前执行");
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("执行handler之前执行");
        return true;
    }
}
2、在配置中进行拦截器注册
@Configuration
public class InterceptorConfig extends WebMvcConfigurationSupport {
    //注册自定义拦截器
    @Override
    protected void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new MyInterceptor()).addPathPatterns("/**");
    }
}

(2)应用举例

  • 日志记录(AOP也可以实现)
  • ip拦截和限流
  • 用户登录验证(token验证)
  • 黑白名单验证

参考博文:http://tengj.top/2017/03/30/springboot6/

五、跨域

六、监听器使用

七、fastjson使用

  • 例如使用列表返回的时候就有可能需要使用下面的配置,但是如果先使用JSON.toJSONString方法转为string后再传就可以不需要下面的方法
@Configuration
public class FastJson extends WebMvcConfigurationSupport {
    @Override
    protected void configureMessageConverters(List> converters) {
        super.configureMessageConverters(converters);
        FastJsonHttpMessageConverter fastJsonHttpMessageConverter = new FastJsonHttpMessageConverter();
        FastJsonConfig fastJsonConfig = new FastJsonConfig();
        fastJsonConfig.setSerializerFeatures(
                //消除对同一对象循环引用的问题,默认为false(如果不配置有可能会进入死循环)
                SerializerFeature.DisableCircularReferenceDetect,
                //List字段如果为null,输出为[],而非null
                SerializerFeature.WriteNullListAsEmpty,
                //字符类型字段如果为null,输出为"",而非null
                SerializerFeature.WriteNullStringAsEmpty,
                //Boolean字段如果为null,输出为false,而非null
                SerializerFeature.WriteNullBooleanAsFalse,
                //是否输出值为null的字段,默认为false。
                SerializerFeature.WriteMapNullValue
        );
        //处理中文乱码问题(不然出现中文乱码)
        List fastMediaTypes = new ArrayList();
        fastMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
        fastJsonHttpMessageConverter.setSupportedMediaTypes(fastMediaTypes);

        fastJsonHttpMessageConverter.setFastJsonConfig(fastJsonConfig);
        converters.add(fastJsonHttpMessageConverter);
    }
}
  • 原理

八、其他(用的少)

  • 嵌入servlet
  • 嵌入jsp
    参考博文:http://tengj.top/2017/03/13/springboot5/

你可能感兴趣的:(3、SpringBoot Web开发)