springBoot 整合thymeleaf捕捉异常

SpringBoot返回json数据

  • 直接返回一个对象 springBoot会自动转换成一个json
  • 一些常用的json注解(jackson的注解)
    //生成json时忽略
    @JsonIgnore
    private String password;
    //当为空时不会生成
    @JsonInclude(JsonInclude.Include.NON_NULL)
    private String desc;
    //对date进行格式化 
    @JsonFormat(pattern = "yyyy-MM-dd hh:mm:ss",locale = "zh",timezone = "GTM+8")
    private Date date;

SpringBoot进行热部署

  • 加入依赖
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-devtools</artifactId>
    <optional>true</optional>
</dependency>
  • 配置plugin(但是不配置也可以)
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <fork>true</fork>
                </configuration>
            </plugin>
  • application.yml加入
spring.devtools.restart.enabled: true

thymeleaf的使用

存:

@GetMapping("/test")
    public String showUser(ModelMap map){
        map.addAttribute("name", name);
        return "/test";
 }

取:

       name:<span th:text="${name}"></span>
  • 在thymeleaf使用properties中的内容

添加配置

#配置i18n 提供给thymeleaf使用
spring.messages.basename=i18n/messages
spring.messages.encoding=UTF-8

在reosurces文件夹下创建/i18n/messages.properties文件

#资源文件的使用
name.tom=tom
name.john=john

在thymeleaf中使用

 <div th:text="#{name.tom}">your name is tom </div>

SpringBoot整合thymeleaf

  • 添加依赖
         <dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-thymeleaf</artifactId>
		</dependency>
  • 在配置文件中添加属性配置
#配置thymeleaf
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
spring.thymeleaf.mode=HTML
spring.thymeleaf.encoding=UTF-8
spring.freemarker.content-type=text/html
#禁用缓存
spring.thymeleaf.cache=false

捕获异常

  • 定义一个类用以处理异常
  @ControllerAdvice
public class ExceptionHandler {
    public static final String error="error";
    @org.springframework.web.bind.annotation.ExceptionHandler(Exception.class)
    public Object toErrorPage(HttpServletRequest request, HttpServletResponse response,Exception e){
        e.printStackTrace();
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("message",e.getMessage() );
        modelAndView.addObject("url", request.getRequestURL());
        modelAndView.setViewName(error);
        return modelAndView;
    }
}

转载于:https://my.oschina.net/helloXia/blog/1820183

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值