在 springmvc.xml 中配置消息转换器处理 ResponseBody 中文乱码

2 篇文章 0 订阅

在 springmvc.xml 中配置消息转换器处理 ResponseBody 中文乱码

<mvc:annotation-driven>
    <!-- 消息转换器 -->
    <mvc:message-converters register-defaults="true">
        <bean class="org.springframework.http.converter.StringHttpMessageConverter">
            <property name="supportedMediaTypes" value="text/html;charset=UTF-8"></property>
        </bean>
    </mvc:message-converters>
</mvc:annotation-driven>
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
1. 首先,在Spring配置文件添加Thymeleaf依赖: ```xml <dependency> <groupId>org.thymeleaf</groupId> <artifactId>thymeleaf-spring5</artifactId> <version>3.0.11.RELEASE</version> </dependency> ``` 2. 然后,在Spring MVC配置文件配置Thymeleaf视图解析器: ```xml <!-- 配置Thymeleaf视图解析器 --> <bean id="templateResolver" class="org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver"> <property name="prefix" value="/WEB-INF/views/" /> <property name="suffix" value=".html" /> <property name="templateMode" value="HTML" /> </bean> <bean id="templateEngine" class="org.thymeleaf.spring5.SpringTemplateEngine"> <property name="templateResolver" ref="templateResolver" /> <property name="enableSpringELCompiler" value="true" /> </bean> <bean class="org.thymeleaf.spring5.view.ThymeleafViewResolver"> <property name="templateEngine" ref="templateEngine" /> <property name="characterEncoding" value="UTF-8" /> </bean> ``` 在上面的配置,我们定义了一个Thymeleaf的模板解析器(templateResolver),用于解析模板文件。我们指定了模板文件的前缀和后缀,以及模板文件的类型(HTML)。接着,我们创建一个Thymeleaf的模板引擎(templateEngine),并将模板解析器注入到该引擎。最后,我们定义了一个Thymeleaf的视图解析器(ThymeleafViewResolver),并将模板引擎注入到该解析器。 3. 在Controller返回Thymeleaf视图: ```java @RequestMapping("/hello") public String hello(Model model) { model.addAttribute("name", "Thymeleaf"); return "hello"; } ``` 在上面的Controller,我们使用Model对象将一个名为“name”的属性值设置为“Thymeleaf”,并将视图名设置为“hello”。由于我们在Spring MVC配置文件配置了Thymeleaf视图解析器,因此,Spring会自动将该视图名解析成“/WEB-INF/views/hello.html”文件,并将模板文件的变量替换成具体的值,最终生成HTML页面。 4. 在Thymeleaf模板文件使用变量: ```html <!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>Hello Thymeleaf</title> </head> <body> <h1>Hello, <span th:text="${name}"></span>!</h1> </body> </html> ``` 在上面的模板文件,我们使用了Thymeleaf的语法,在页面输出了变量“name”的值。在Thymeleaf,我们可以使用“${变量名}”的语法来输出变量的值。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值