【Question03】使用 Spring mvc 框架的时候如何处理乱码问题

开篇

如题,反正乱码问题是很常见的,那就记录一下吧。在使用 Spring mvc 的框架过程中,我们经常会出现乱码问题,反正是层出不穷的。这里提供如下的解决方案。

GET 请求乱码问题

在 tomcat 的安装目录下,找到 conf 文件夹,然后打开 server.xml,利用编辑器的检索功能找到如下代码:

<Connector connectionTimeout="20000" port="8080" protocol="HTTP/1.1" redirectPort="8443"/> 

将其替换成:

<Connector URIEncoding="UTF-8" connectionTimeout="20000" port="8080" protocol="HTTP/1.1" redirectPort="8443" />  

GET 请求再无乱码!I promise!

POST 请求乱码问题

这个就很好解决啦,一般乱码都是配置一个过滤器,Spring mvc 也不例外。在项目的 web.xml 文件中做如下配置:

<filter>
    <filter-name>CharacterFilter</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <init-param>
        <param-name>encoding</param-name>
        <param-value>UTF-8</param-value>
    </init-param>
</filter>
<filter-mapping>
    <filter-name>CharacterFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

bingo,一劳永逸,继续去写代码!

Spring MVC中,没有直接使用setAttribute方法来设置属性。相反,Spring MVC使用Model对象来传递数据给视图。Model对象是一个接口,它允许控制器将数据添加到模型中,以便在视图中使用。通过在控制器方法的参数中声明一个Model对象,你可以使用addAttribute方法将数据添加到模型中。例如,你可以在控制器方法中使用以下代码将一个名为"employee"的对象添加到模型中: ```java @RequestMapping("/employee") public String getEmployee(Model model) { Employee employee = new Employee(); // 设置employee对象的属性 model.addAttribute("employee", employee); return "employeeView"; } ``` 在视图中,你可以使用modelAttribute属性来指定模型中的属性名称,以便在表单中绑定数据。例如,你可以在JSP视图中使用以下代码: ```html <form:form modelAttribute="employee" method="POST" action="/saveEmployee"> <label for="name">Name:</label> <form:input path="name" id="name" /> <!-- 其他表单字段 --> <input type="submit" value="Save" /> </form:form> ``` 在这个例子中,modelAttribute属性指定了模型中的属性名称为"employee",而path属性指定了表单字段与模型属性的映射关系。当表单提交时,Spring MVC会自动将表单字段的值绑定到模型对象的对应属性上。 参考文献: \[1\] https://blog.csdn.net/zuihoudebingwen/article/details/78037635 \[2\] https://zhidao.baidu.com/question/304038748840781404.html #### 引用[.reference_title] - *1* *2* *3* [SpringMVC获取页面表单参数的几种方式,setAttribute,addAttribute,modelAttribute,path](https://blog.csdn.net/weixin_37127253/article/details/100594934)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^koosearch_v1,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值