首页
留言
关于
友链
更多
足迹
Search
1
SpringMVC+Spring+MyBatis整合完整版Web实例(附数据)
2,829 阅读
2
关于在Flutter实现Google地图的方法
1,626 阅读
3
druid报异常 “sql injection violation, part alway true condition not allow”的解决方案
1,194 阅读
4
MyBatis的TooManyResultsException异常的解决办法
1,000 阅读
5
如何去掉vue路径中的“#”号
980 阅读
发现
技术
生活
户外
登录
Search
标签搜索
Git
JavaScript
Oracle
Git学习
Java
Flutter
MySQL
SQL Server
IntelliJ IDEA
Spring Boot
Flutter 2.0
对称加密算法
Google地图
Maven
ES6
秦岭户外
linux
Tomcat
Redis
Spring
Bai Keyang
累计撰写
282
篇文章
累计收到
277
条评论
首页
栏目
发现
技术
生活
户外
页面
留言
关于
友链
足迹
搜索到
5
篇与
Spring Boot
的结果
2021-12-02
SpringBoot手动控制启动定时任务
在SpringBoot中启动定时任务只需要添加注解 @EnableScheduling 即可搞定,package cn.org.kcis; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.scheduling.annotation.EnableScheduling; @SpringBootApplication @EnableScheduling public class StartApplication { public static void main(String[] args) { SpringApplication.run(StartApplication.class, args); } } 然后再Job类上面添加 @Component 和 @Scheduled在任务的类上写@Component在任务方法上写@Scheduledpackage cn.org.kcis.xian.task; import cn.org.kcis.xian.controller.IndexController; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.springframework.stereotype.Component; import org.springframework.scheduling.annotation.Scheduled; /** * @Author : BaiKeyang * @Date : Created in 2020/7/16 11:27 * @Description: * @Modified By: * @Version: $ */ @Component public class ScheduledService { private static final Logger log = LogManager.getLogger(IndexController.class); // 表示每隔1小时执行 @Scheduled(cron = "0 0 */1 * * ?") public void test1(){ log.error("=====>>>>>test1 {}",System.currentTimeMillis()); } // 表示每隔3分钟执行 @Scheduled(cron = "0 */3 * * * ?") public void test2(){ log.error("=====>>>>>test2 {}",System.currentTimeMillis()); } // 表示每天15分、45分 执行 @Scheduled(cron = "0 15/30 * * * ?") public void test3(){ log.error("=====>>>>>test3 {}",System.currentTimeMillis()); } // 每天的上午8点到20点执行 @Scheduled(cron = "0 0 8-20 * * ?") public void test6(){ log.error("=====>>>>>test6 {}",System.currentTimeMillis()); } // 表示每天8点30分执行 @Scheduled(cron = "0 0,30 0,8 ? * ? ") public void test7() { log.error("=====>>>>>test7 {}",System.currentTimeMillis()); } // 表示每天凌晨1点执行 @Scheduled(cron = "0 0 1 * * ?") public void test8() { log.error("=====>>>>>test8 {}",System.currentTimeMillis()); } // 表示每隔3秒 @Scheduled(fixedRate = 3000) public void test4() { log.info("=====>>>>>test4{}", System.currentTimeMillis()); } // 表示方法执行完成后5秒 @Scheduled(fixedDelay = 5000) public void test5() { log.info("=====>>>>>test5{}",System.currentTimeMillis()); } } 启动项目后,注解的方法都会根据配置的cron表达式、fixedDelay和fixedRate 参数值去开始运行。如果需要手动的去启动定时任务,再在上面定义实现了ThreadPoolTaskScheduler的实例:package cn.org.kcis; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler; @SpringBootApplication @EnableScheduling public class StartApplication { public static void main(String[] args) { SpringApplication.run(StartApplication.class, args); } @Bean public ThreadPoolTaskScheduler threadPoolTaskScheduler () { return new ThreadPoolTaskScheduler(); } } 创建任务类,注入 ThreadPoolTaskScheduler ,通过 threadPoolTaskScheduler.schedule() 来创建、启动定时任务,并将任务保存,以便于下次关闭;package cn.org.kcis.xian.task; import cn.hutool.core.util.StrUtil; import cn.org.kcis.xian.controller.IndexController; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler; import org.springframework.scheduling.support.CronTrigger; import org.springframework.stereotype.Component; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.Map; import java.util.concurrent.ScheduledFuture; /** * @Author : BaiKeyang * @Date : Created in 2020/7/16 11:27 * @Description: * @Modified By: * @Version: $ */ @Component public class ScheduledService { private static final Logger log = LogManager.getLogger(IndexController.class); @Autowired ThreadPoolTaskScheduler threadPoolTaskScheduler; Map<String, ScheduledFuture<?>> futureMap; public void start (String key) { if(StrUtil.isNotEmpty(key)) { if(futureMap == null){ futureMap = new HashMap<>(); } if("test".equals(key)) { ScheduledFuture<?> future1 = threadPoolTaskScheduler.schedule(new myTask1(), new CronTrigger("0/1 * * * * ?")); futureMap.put("task1", future1); } else if("server".equals(key)) { ScheduledFuture<?> future2 = threadPoolTaskScheduler.schedule(new myTask2(), new CronTrigger("0 */3 * * * ?")); futureMap.put("task2", future2); } else if("ps".equals(key)) { ScheduledFuture<?> future2 = threadPoolTaskScheduler.schedule(new myTask3(), new CronTrigger("0 */1 * * * ?")); futureMap.put("task3", future2); } } } // 关闭指定的定时任务 public String stop (String key) { if(futureMap != null && StrUtil.isNotEmpty(key) && futureMap.get(key) != null) { futureMap.get(key).cancel(true); } System.out.println("定时任务已关闭"); return "定时任务已关闭"; } private class myTask1 implements Runnable { @Override public void run() { System.out.println("test" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())); } } private class myTask2 implements Runnable { @Override public void run() { log.error("=====>>>>>服务可用性扫描 {}",System.currentTimeMillis()); } } private class myTask3 implements Runnable { @Override public void run() { log.error("=====>>>>>数据同步 {}",System.currentTimeMillis()); } } } 在外部通过Controller调用来实现手动开启/关闭某个任务的操作:package cn.org.kcis.xian.controller; import cn.org.kcis.xian.task.ScheduledService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; /** * @Author : BaiKeyang * @Date : Created in 2020/2/4 17:37 * @Description: * @Modified By: * @Version: $ */ @RestController(value = "demoController") public class HelloController { @Autowired ScheduledService scheduledService; @RequestMapping(value = "/run") public String run(String key) { scheduledService.start(key); return "定时任务已启动"; } @RequestMapping(value = "/stop") public String stop(String key) { scheduledService.stop(key); return "定时任务已关闭"; } } 通过上面的方式,这样就实现了SpringBoot中手动控制定时任务的效果了。
2021年12月02日
341 阅读
0 评论
0 点赞
2021-10-22
Spring Boot处理Multipart文件上传
Spring Boot采用Servlet 3 javax.servlet.http.Part API来支持文件上传。默认情况下,Spring Boot配置Spring MVC在单个请求中只处理每个文件最大1Mb,最多10Mb的文件数据。你可以覆盖那些值,也可以设置临时文件存储的位置(比如,存储到/tmp文件夹下)及传递数据刷新到磁盘的阀值(通过使用MultipartProperties类暴露的属性)。如果你需要设置文件不受限制,可以设置spring.http.multipart.max-file-size属性值为-1。当你想要接收multipart编码文件数据作为Spring MVC控制器(controller)处理方法中被@RequestParam注解的MultipartFile类型的参数时,multipart支持就非常有用了。更多详情可参考MultipartAutoConfiguration:// // Source code recreated from a .class file by IntelliJ IDEA // (powered by Fernflower decompiler) // package org.springframework.boot.autoconfigure.web.servlet; import javax.servlet.MultipartConfigElement; import javax.servlet.Servlet; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication; import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication.Type; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.multipart.MultipartResolver; import org.springframework.web.multipart.commons.CommonsMultipartResolver; import org.springframework.web.multipart.support.StandardServletMultipartResolver; @Configuration @ConditionalOnClass({Servlet.class, StandardServletMultipartResolver.class, MultipartConfigElement.class}) @ConditionalOnProperty( prefix = "spring.servlet.multipart", name = {"enabled"}, matchIfMissing = true ) @ConditionalOnWebApplication( type = Type.SERVLET ) @EnableConfigurationProperties({MultipartProperties.class}) public class MultipartAutoConfiguration { private final MultipartProperties multipartProperties; public MultipartAutoConfiguration(MultipartProperties multipartProperties) { this.multipartProperties = multipartProperties; } @Bean @ConditionalOnMissingBean({MultipartConfigElement.class, CommonsMultipartResolver.class}) public MultipartConfigElement multipartConfigElement() { return this.multipartProperties.createMultipartConfig(); } @Bean( name = {"multipartResolver"} ) @ConditionalOnMissingBean({MultipartResolver.class}) public StandardServletMultipartResolver multipartResolver() { StandardServletMultipartResolver multipartResolver = new StandardServletMultipartResolver(); multipartResolver.setResolveLazily(this.multipartProperties.isResolveLazily()); return multipartResolver; } }其中,MultipartProperties中可以看到Spring MVC的默认单个请求中只处理每个文件最大1Mb,最多10Mb的文件数据// // Source code recreated from a .class file by IntelliJ IDEA // (powered by Fernflower decompiler) // package org.springframework.boot.autoconfigure.web.servlet; import javax.servlet.MultipartConfigElement; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.web.servlet.MultipartConfigFactory; import org.springframework.util.StringUtils; @ConfigurationProperties( prefix = "spring.servlet.multipart", ignoreUnknownFields = false ) public class MultipartProperties { private boolean enabled = true; private String location; private String maxFileSize = "1MB"; private String maxRequestSize = "10MB"; private String fileSizeThreshold = "0"; private boolean resolveLazily = false; public MultipartProperties() { } public boolean getEnabled() { return this.enabled; } public void setEnabled(boolean enabled) { this.enabled = enabled; } public String getLocation() { return this.location; } public void setLocation(String location) { this.location = location; } public String getMaxFileSize() { return this.maxFileSize; } public void setMaxFileSize(String maxFileSize) { this.maxFileSize = maxFileSize; } public String getMaxRequestSize() { return this.maxRequestSize; } public void setMaxRequestSize(String maxRequestSize) { this.maxRequestSize = maxRequestSize; } public String getFileSizeThreshold() { return this.fileSizeThreshold; } public void setFileSizeThreshold(String fileSizeThreshold) { this.fileSizeThreshold = fileSizeThreshold; } public boolean isResolveLazily() { return this.resolveLazily; } public void setResolveLazily(boolean resolveLazily) { this.resolveLazily = resolveLazily; } public MultipartConfigElement createMultipartConfig() { MultipartConfigFactory factory = new MultipartConfigFactory(); if (StringUtils.hasText(this.fileSizeThreshold)) { factory.setFileSizeThreshold(this.fileSizeThreshold); } if (StringUtils.hasText(this.location)) { factory.setLocation(this.location); } if (StringUtils.hasText(this.maxRequestSize)) { factory.setMaxRequestSize(this.maxRequestSize); } if (StringUtils.hasText(this.maxFileSize)) { factory.setMaxFileSize(this.maxFileSize); } return factory.createMultipartConfig(); } }
2021年10月22日
267 阅读
0 评论
0 点赞
2018-01-01
Spring Boot 之 Thymeleaf 篇
在Spring boot中,官方默认采用的是Thymeleaf模块引擎,通过org.springframework.boot.autoconfigure.thymeleaf包对Thymeleaf进行了自动配置。通过Thymeleaf2Configuration类对集成所需要的Bean进行自动配置,包括templateResolver、templateViewResolver 和templateEngine 的配置。通过ThymeleafProperties来配置Thymeleaf,在application.properties中以 spring.thymeleaf开头来配置,通过查看ThymeleafProperties的主要源码,可以看出如何设置属性及默认配置:/* * Copyright 2012-2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.boot.autoconfigure.thymeleaf; import java.nio.charset.Charset; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.util.MimeType; /** * Properties for Thymeleaf. * * @author Stephane Nicoll * @since 1.2.0 */ @ConfigurationProperties(prefix = "spring.thymeleaf") public class ThymeleafProperties { private static final Charset DEFAULT_ENCODING = Charset.forName("UTF-8"); private static final MimeType DEFAULT_CONTENT_TYPE = MimeType.valueOf("text/html"); public static final String DEFAULT_PREFIX = "classpath:/templates/"; public static final String DEFAULT_SUFFIX = ".html"; /** * 在渲染之前检查模板是否存在(Thymeleaf 3+)。 */ private boolean checkTemplate = true; /** * 检查模板位置是否存在。 */ private boolean checkTemplateLocation = true; /** * Spring boot 默认模板路径,默认在classpath:/templates/目录下 */ private String prefix = DEFAULT_PREFIX; /** * 后缀设置,默认为html. */ private String suffix = DEFAULT_SUFFIX; /** * 模板模式设置,默认为html5 */ private String mode = "HTML5"; /** * 模板的编码设置,默认UTF-8 */ private Charset encoding = DEFAULT_ENCODING; /** * 模板的媒体类型设置,默认为text/html */ private MimeType contentType = DEFAULT_CONTENT_TYPE; /** * 是否开启模板缓存,默认是开启的,开发时建议关闭 */ private boolean cache = true; /** * Order of the template resolver in the chain. By default, the template resolver is * first in the chain. Order start at 1 and should only be set if you have defined * additional "TemplateResolver" beans. */ private Integer templateResolverOrder; /** * Comma-separated list of view names that can be resolved. */ private String[] viewNames; /** * Comma-separated list of view names that should be excluded from resolution. */ private String[] excludedViewNames; /** * Enable MVC Thymeleaf view resolution. */ private boolean enabled = true; public boolean isEnabled() { return this.enabled; } public void setEnabled(boolean enabled) { this.enabled = enabled; } public boolean isCheckTemplate() { return this.checkTemplate; } public void setCheckTemplate(boolean checkTemplate) { this.checkTemplate = checkTemplate; } public boolean isCheckTemplateLocation() { return this.checkTemplateLocation; } public void setCheckTemplateLocation(boolean checkTemplateLocation) { this.checkTemplateLocation = checkTemplateLocation; } public String getPrefix() { return this.prefix; } public void setPrefix(String prefix) { this.prefix = prefix; } public String getSuffix() { return this.suffix; } public void setSuffix(String suffix) { this.suffix = suffix; } public String getMode() { return this.mode; } public void setMode(String mode) { this.mode = mode; } public Charset getEncoding() { return this.encoding; } public void setEncoding(Charset encoding) { this.encoding = encoding; } public MimeType getContentType() { return this.contentType; } public void setContentType(MimeType contentType) { this.contentType = contentType; } public boolean isCache() { return this.cache; } public void setCache(boolean cache) { this.cache = cache; } public Integer getTemplateResolverOrder() { return this.templateResolverOrder; } public void setTemplateResolverOrder(Integer templateResolverOrder) { this.templateResolverOrder = templateResolverOrder; } public String[] getExcludedViewNames() { return this.excludedViewNames; } public void setExcludedViewNames(String[] excludedViewNames) { this.excludedViewNames = excludedViewNames; } public String[] getViewNames() { return this.viewNames; } public void setViewNames(String[] viewNames) { this.viewNames = viewNames; } } 以上关于ThymeleafProperties类的中文注释,为个人根据代码理解及其原代码英文注释而来。在spring boot中整合Thymeleaf需要加入对Thymeleaf的依赖:<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency>创建一个HelloController 类,通过spring mvc 返回页面,来通过Thymeleaf渲染一个页面。import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class HelloController { @RequestMapping(value = "/hello") public String hello(ModelMap map){ // 加入一个属性,用来在模板中读取 map.addAttribute("host", "http://www.baikeyang.com"); // return模板文件的名称,对应src/main/resources/templates/index.html return "index"; } }<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head lang="en"> <meta charset="UTF-8" > <title></title> </head> <body> <h1 th:text="${host}">Hello World</h1> <br/> </body> </html>直接打开html页面展现Hello World,但是启动程序后,访问http://localhost:8080/hello,则是展示Controller中host的值:http://www.baikeyang.com,做到了不破坏HTML自身内容的数据逻辑分离。#Thymeleaf配置 #Thymeleaf模板模式 spring.thymeleaf.mode = HTML5 #Thymeleaf 编码 spring.thymeleaf.encoding = UTF-8 #模板缓存(热部署静态文件) spring.thymeleaf.cache = false #spring.thymeleaf.prefix=classpath:/templates/:指定Thymeleaf的页面文件放置的位置(也就是页面文件的前缀),这里的classpath:/templates/指的目录就是src/resources/templates,所以需要创建templates这个目录(默认是没有这个目录的) spring.thymeleaf.prefix = classpath:/templates/ #检查模板位置是否存在 spring.thymeleaf.check-template-location = true #指定页面文件的后缀,这里配置所有页面文件都是.html的文件 spring.thymeleaf.suffix = .html #内容类型 spring.thymeleaf.content-type = text/html启动项目,直接访问,会有一个异常抛出:org.xml.sax.SAXParseException: 元素类型 "meta" 必须由匹配的结束标记 "</meta>" 终止。spring.thymeleaf.mode的默认值是HTML5,其实是一个很严格的检查,对.html的内容要求很严格,比如<meta charset="UTF-8" />,如果少最后的标签封闭符号/,就会报错而转到错误页。也比如你在使用<br/>、<link>、<meta>这样的html标签,也会被thymeleaf认为不符合要求而抛出错误。因为,我可以调整spring.thymeleaf.mode,改为LEGACYHTML5可以得到一个可能更友好亲切的格式要求。需要注意的是,LEGACYHTML5需要搭配一个额外的库NekoHTML才可用。需要给项目添加NekoHTML的依赖:<dependency> <groupId>net.sourceforge.nekohtml</groupId> <artifactId>nekohtml</artifactId> <version>1.9.22</version> </dependency>最后重启项目就可以感受到不那么严格的thymeleaf了,访问正常。
2018年01月01日
315 阅读
0 评论
0 点赞
2017-09-30
Spring boot 之 Web应用开发篇
本篇文章主要是围绕如何在Spring Boot中进行Web开发呢? 一、Web中的静态资源配置通常在我们开发Web应用的时候都需要引入大量的JS、CSS、图片 等等的静态资源。在Spring Boot中默认提供的静态资源目录位置需要放置在classpath下,目录名称需要符合如下: ·/static · /public · /resources · /META-INF/resources例如:在src/main/resources/目录下创建一个static目录,在该目录下放置一个图片。启动程序后,尝试访问http://localhost:8080/temp.jpg,如果图片可以正常显示,则就配置成功。二、关于Web页面的显示与渲染在Spring Boot中,使用@RestController来处理请求,返回的内容为JSON对象。如果需要返回渲染或显示页面,可以使用@Controller来处理请求。在Spring Boot中,官方为我们提供并推荐了多款模板引擎的默认配置支持,提供默认配置的模板引擎主要有如下几种: · Thymeleaf · FreeMarker · Velocity · Groovy · Mustache在这里要特别特别说明:Spring Boot建议使用这些模板引擎,避免使用JSP,若一定要使用JSP将无法实现Spring Boot的多种特性,所以,在这里我也就不再说怎么去支持JSP的配置了。当我们要使用上面模板引擎中的任何一个时,它们默认的模板配置路径是 src/main/resources/templates,这个路径也是可以去配置修改的,至于怎么修改,继续往下面看哟 ~在这里就以Thymeleaf为例:简单介绍下Thymeleaf: Thymeleaf是一个XML/XHTML/HTML5模板引擎,可用于Web与非Web环境中的应用开发。它是一个开源的Java库,基于Apache License 2.0许可,由Daniel Fernández创建,该作者还是Java加密库Jasypt的作者。Thymeleaf提供了一个用于整合Spring MVC的可选模块,在应用开发中,你可以使用Thymeleaf来完全代替JSP或其他模板引擎,如Velocity、FreeMarker等。Thymeleaf的主要目标在于提供一种可被浏览器正确显示的、格式良好的模板创建方式,因此也可以用作静态建模。你可以使用它创建经过验证的XML与HTML模板。相对于编写逻辑或代码,开发者只需将标签属性添加到模板中即可。接下来,这些标签属性就会在DOM(文档对象模型)上执行预先制定好的逻辑。下面是一小段关于Thymeleaf模板引擎的示例:<table> <thead> <tr> <th th:text="#{msgs.headers.name}">Name</td> <th th:text="#{msgs.headers.price}">Price</td> </tr> </thead> <tbody> <tr th:each="prod : ${allProducts}"> <td th:text="${prod.name}">Oranges</td> <td th:text="${#numbers.formatDecimal(prod.price,1,2)}">0.99</td> </tr> </tbody> </table> 从上面的实例中可以看到Thymeleaf主要以属性的方式加入到html标签中,浏览器在解析html时,当检查到没有的属性时候会忽略,所以Thymeleaf的模板可以通过浏览器直接打开展现,这样比较有利于前后端的分离。如果我们要在Spring Boot中使用 Thymeleaf 模板,需要引入Spring boot Thymeleaf 的依赖,然后在默认的模板路径下 src/main/resources/templates 下编写模板文件就可以了。<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> 以上配置基本完成。下面来一个简单的例子演示:HelloController.javapackage com.youth.hoel.hello; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.servlet.ModelAndView; @Controller public class HelloController { @RequestMapping("/hello") public ModelAndView index(ModelMap map){ // return "Hello Spring Boot!"; map.addAttribute("host", "http://www.baikeyang.com/"); return new ModelAndView("index"); } } 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> 上面页面直接打开html显示的是Hello World,但是项目启动后访问http://localhost:8080/hello,这显示的 http://www.baikeyang.com/,这就做到了不破坏HTML自身内容的数据逻辑分离。关于Thymeleaf的页面语法,大家可以查看Thymeleaf的官方文档学习使用。下面是Thymeleaf的默认参数配置:如果有需要修改默认配置,只需要将下面的修改属性复制到application.properties文件中,并修改成你说需要的值即可,比如修改模板文件的扩展名、模板路径 等# #thymeleaf 配置 # # 开发时关闭缓存,不然没法看到实时页面 spring.thymeleaf.cache=false # 检查模板位置是否存在 spring.thymeleaf.check-template-location=true # Content-Type值 spring.thymeleaf.content-type=text/html # 启用MVC Thymeleaf视图分辨率 spring.thymeleaf.enabled=true # 模板编码 spring.thymeleaf.encoding=UTF-8 # 应该从解决方案中排除的视图名称的逗号分隔列表 spring.thymeleaf.excluded-view-names= # 要应用于模板的模板模式。 另请参见StandardTemplateModeHandlers spring.thymeleaf.mode=HTML5 # 在构建URL时,先前要查看名称的前缀 spring.thymeleaf.prefix=classpath:/templates/ # 构建URL时附加查看名称的后缀 spring.thymeleaf.suffix=.html # 链中模板解析器的顺序 spring.thymeleaf.template-resolver-order= # 可以解析的视图名称的逗号分隔列表 spring.thymeleaf.view-names= 关于JSP的配置:Spring Boot并不建议使用,但如果一定要使用,可以参考此工程作为脚手架:JSP支持(点我传送>>>)
2017年09月30日
244 阅读
0 评论
0 点赞
2017-09-19
Spring Boot 起步
Spring Boot快速起步。至于什么是Spring Boot?它能干些什么,我在这里不解释,想了解的朋友可以去网站自行搜索,相信你会明白。 好了,废话不多说,直接开始。一、起步1、创建一个普通的Maven项目此处省略N个姿势…… 2、修改pox.xml,添加Spring Boot的相关依赖<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.bkybk</groupId> <artifactId>boot</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>boot</name> <url>http://maven.apache.org</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </properties> <!-- Inherit defaults from Spring Boot --> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.6.RELEASE</version> </parent> <!-- Add typical dependencies for a web application --> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- 增加单元测试的依赖 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> <!-- Package as an executable JAR --> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> <!-- 允许访问Spring里程碑和快照 --> <!-- (如果您在0.5.0.RELEASE之后使用任何内容,则不需要此操作) --> <!-- <repositories> <repository> <id>spring-snapshots</id> <url>http://repo.spring.io/snapshot</url> <snapshots><enabled>true</enabled></snapshots> </repository> <repository> <id>spring-milestones</id> <url>http://repo.spring.io/milestone</url> <snapshots><enabled>true</enabled></snapshots> </repository> </repositories> --> <!-- <pluginRepositories> <pluginRepository> <id>spring-snapshots</id> <url>http://repo.spring.io/snapshot</url> </pluginRepository> <pluginRepository> <id>spring-milestones</id> <url>http://repo.spring.io/milestone</url> </pluginRepository> </pluginRepositories> --> </project> 3、修改或创建App.javapackage com.bkybk.boot; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; /** * Hello world! * */ @Configuration @ComponentScan @EnableAutoConfiguration public class App { public static void main( String[] args ) { SpringApplication.run(App.class); } } 4、创建HelloController.javapackage com.bkybk.boot; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class HelloController { @RequestMapping("/") public String index() { return "Hello,Spring boot!"; } }运行App的main方法,启动Spring Boot微笑:“完美~ ”二、单元测试 1、pox.xml<!-- 增加单元测试的依赖 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency>2、创建HelloTestpackage com.bkybk.boot.test; import static org.assertj.core.api.Assertions.assertThat; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.context.embedded.LocalServerPort; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.web.client.TestRestTemplate; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest(classes=App.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) public class HelloTest { @LocalServerPort private int port; @Autowired private TestRestTemplate restTemplate; @Test public void greetingShouldReturestTemplaternDefaultMessage() throws Exception { assertThat(this.restTemplate.getForObject("http://localhost:" + port + "/", String.class)).contains("Hello,Spring boot!"); } }运行jUnit Test,单元测试运行OK再次微笑:“完美~ ”三:So,怎么部署spring boot? 1、给运行机器搭建并配置Maven 此处省略一万个精彩动作和激情画面……安装并配置完成Maven,查看Maven版本:E:\workspace\boot>mvn -v Apache Maven 3.0.4 (r1232337; 2012-01-17 16:44:56+0800) Maven home: D:\Develop\Maven\apache-maven-3.0.4\bin\.. Java version: 1.8.0_121, vendor: Oracle Corporation Java home: D:\Develop\Java\jdk1.8.0_121\jre Default locale: zh_CN, platform encoding: GBK OS name: "windows 10", version: "10.0", arch: "amd64", family: "dos" E:\workspace\boot> 2、开始打包打包命令:mvn package 如果在打包的时候要跳过自己项目中的一些测试,则添加参数 -DskipTestsE:\workspace\boot>mvn package -DskipTests [INFO] Scanning for projects... [INFO] [INFO] ------------------------------------------------------------------------ [INFO] Building boot 0.0.1-SNAPSHOT [INFO] ------------------------------------------------------------------------ [INFO] [INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ boot --- [INFO] Using 'UTF-8' encoding to copy filtered resources. [INFO] skip non existing resourceDirectory E:\workspace\boot\src\main\resources [INFO] skip non existing resourceDirectory E:\workspace\boot\src\main\resources [INFO] [INFO] --- maven-compiler-plugin:3.1:compile (default-compile) @ boot --- [INFO] Nothing to compile - all classes are up to date [INFO] [INFO] --- maven-resources-plugin:2.6:testResources (default-testResources) @ boot --- [INFO] Using 'UTF-8' encoding to copy filtered resources. [INFO] skip non existing resourceDirectory E:\workspace\boot\src\test\resources [INFO] [INFO] --- maven-compiler-plugin:3.1:testCompile (default-testCompile) @ boot --- [INFO] Changes detected - recompiling the module! [INFO] Compiling 1 source file to E:\workspace\boot\target\test-classes [INFO] [INFO] --- maven-surefire-plugin:2.18.1:test (default-test) @ boot --- [INFO] Tests are skipped. [INFO] [INFO] --- maven-jar-plugin:2.6:jar (default-jar) @ boot --- [INFO] Building jar: E:\workspace\boot\target\boot-0.0.1-SNAPSHOT.jar [INFO] [INFO] --- spring-boot-maven-plugin:1.5.6.RELEASE:repackage (default) @ boot --- Downloading: http://192.168.1.180:8081/content/groups/public/org/codehaus/plexus/plexus-classworlds/2.4/plexus-classworlds-2.4.pom Downloaded: http://192.168.1.180:8081/content/groups/public/org/codehaus/plexus/plexus-classworlds/2.4/plexus-classworlds-2.4.pom (0 B at 0.0 KB/sec) [INFO] ------------------------------------------------------------------------ [INFO] BUILD SUCCESS [INFO] ------------------------------------------------------------------------ [INFO] Total time: 5.675s [INFO] Finished at: Tue Sep 19 18:08:20 CST 2017 [INFO] Final Memory: 32M/277M [INFO] ------------------------------------------------------------------------ E:\workspace\boot> 打包完成在target下面就会有boot-0.0.1-SNAPSHOT.jar这样的jar,打包完成3、在CMD中执行命令“java -jar file”,file就是刚刚打好的包E:\workspace\boot>java -jar target/boot-0.0.1-SNAPSHOT.jar . ____ _ __ _ _ /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \ ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \ \\/ ___)| |_)| | | | | || (_| | ) ) ) ) ' |____| .__|_| |_|_| |_\__, | / / / / =========|_|==============|___/=/_/_/_/ :: Spring Boot :: (v1.5.6.RELEASE) 2017-09-19 18:20:12.072 INFO 10508 --- [ main] com.bkybk.boot.test.App : Starting App v0.0.1-SNAPSHOT on lenovo-PC with PID 10508 (E:\workspace\boot\target\boot-0.0.1-SNAPSHOT.jar started by lenovo in E:\workspace\boot) 2017-09-19 18:20:12.085 INFO 10508 --- [ main] com.bkybk.boot.test.App : No active profile set, falling back to default profiles: default 2017-09-19 18:20:12.167 INFO 10508 --- [ main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@443b7951: startup date [Tue Sep 19 18:20:12 CST 2017]; root of context hierarchy 2017-09-19 18:20:14.503 INFO 10508 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8080 (http) 2017-09-19 18:20:14.520 INFO 10508 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat] 2017-09-19 18:20:14.523 INFO 10508 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/8.5.16 2017-09-19 18:20:14.654 INFO 10508 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext 2017-09-19 18:20:14.654 INFO 10508 --- [ost-startStop-1] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 2490 ms 2017-09-19 18:20:14.830 INFO 10508 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean : Mapping servlet: 'dispatcherServlet' to [/] 2017-09-19 18:20:14.843 INFO 10508 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'characterEncodingFilter' to: [/*] 2017-09-19 18:20:14.849 INFO 10508 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'hiddenHttpMethodFilter' to: [/*] 2017-09-19 18:20:14.853 INFO 10508 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'httpPutFormContentFilter' to: [/*] 2017-09-19 18:20:14.855 INFO 10508 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'requestContextFilter' to: [/*] 2017-09-19 18:20:15.243 INFO 10508 --- [ main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@443b7951: startup date [Tue Sep 19 18:20:12 CST 2017]; root of context hierarchy 2017-09-19 18:20:15.366 INFO 10508 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/]}" onto public java.lang.String com.bkybk.boot.test.HelloController.index() 2017-09-19 18:20:15.372 INFO 10508 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest) 2017-09-19 18:20:15.373 INFO 10508 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse) 2017-09-19 18:20:15.422 INFO 10508 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler] 2017-09-19 18:20:15.422 INFO 10508 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler] 2017-09-19 18:20:15.463 INFO 10508 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler] 2017-09-19 18:20:15.618 INFO 10508 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup 2017-09-19 18:20:15.710 INFO 10508 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http) 2017-09-19 18:20:15.720 INFO 10508 --- [ main] com.bkybk.boot.test.App : Started App in 4.067 seconds (JVM running for 4.596) 2017-09-19 18:20:30.485 INFO 10508 --- [ Thread-3] ationConfigEmbeddedWebApplicationContext : Closing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@443b7951: startup date [Tue Sep 19 18:20:12 CST 2017]; root of context hierarchy 这时程序就部署好了,有没有感觉So Easy?是不是炒鸡简单?
2017年09月19日
326 阅读
0 评论
0 点赞