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)引入依赖

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

(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

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8" />
    <title></title>
</head>
<body>
<h1 th:text="${host}">Hello World</h1>
</body>
</html>

(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)客户端
<form method="POST" action="/upload" enctype="multipart/form-data">
    <input type="file" name="files" /><br/><br/>
    <input type="submit" value="Submit" />
</form>
<a href="/download">download</a>

(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<HttpMessageConverter<?>> 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<MediaType> fastMediaTypes = new ArrayList<MediaType>();
        fastMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
        fastJsonHttpMessageConverter.setSupportedMediaTypes(fastMediaTypes);

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

八、其他(用的少)

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 199,830评论 5 468
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 83,992评论 2 376
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 146,875评论 0 331
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 53,837评论 1 271
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,734评论 5 360
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,091评论 1 277
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,550评论 3 390
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,217评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,368评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,298评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,350评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,027评论 3 315
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,623评论 3 303
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,706评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,940评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,349评论 2 346
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 41,936评论 2 341

推荐阅读更多精彩内容