增加一个方法:
//映射访问路径,必须是POST请求 @RequestMapping(value = "/hello",method = {RequestMethod.POST}) public String index2(Model model){ model.addAttribute("msg", "hello!"); return "test"; }我们使用浏览器地址栏进行访问默认是Get请求,会报错405:
如果将POST修改为GET则正常了
HTTP 请求我们正常发送HTTP请求,可以正常发送的只有GET、POST,而在RestFul风格中PUT、DELETE,PATCH则不能直接发送,可以使用以下方法:
1.配置web.xml <!-- HTTP PUT Form --> <filter> <filter-name>HiddenHttpMethodFilter</filter-name> <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class> </filter> <filter-mapping> <filter-name>HiddenHttpMethodFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> 2.编写form表单 <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>$Title$</title> </head> <body> <form method="POST" action="put"> <input type="hidden" value="PUT"> <p>姓名:</p><input type="text" /><br/> <p>性别:</p><input type="text" /><br/> <p>年龄:</p><input type="text" /><br/> <button type="submit">提交</button> </form> </body> </html>form表单中有一个隐藏的input,name必须为_method,value="xxx"即为xxx请求。
3.编写Controller类 @Controller public class RestFulController { @PutMapping("/put") @ResponseBody public String index3(HttpServletRequest req, HttpServletResponse resp){ String name = req.getParameter("name"); String sex = req.getParameter("sex"); String age = req.getParameter("age"); return "name:" + name + ",sex:" + sex + ",age:" + age; } }注意:
这里可以使用 @RequestMapping(value = "/put",method = {RequestMethod.PUT})
也可以直接使用: @PutMapping("/put")
由上面可以看出:
是method设置不同类型的请求
或者
@GetMapping
@PostMapping
@PutMapping
@DeleteMapping
@PatchMapping
会发现填写的中文都成为了?,这时候可以尝试在web.xml中设置字符过滤器:
<filter> <filter-name>encoding</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> <init-param> <param-name>forceEncoding</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>encoding</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>这种过滤器对大部分中文乱码都有用了,但是还有一种情况为json中文乱码:
导入依赖
<dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>2.9.9</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.9.9</version> </dependency>在springmvc.xml中配置
<mvc:annotation-driven> <mvc:message-converters> <bean> <property> <list> <value>text/plain;charset=UTF-8</value> <value>text/html;charset=UTF-8</value> </list> </property> </bean> <bean> <property> <list> <value>application/json;charset=UTF-8</value> </list> </property> </bean> </mvc:message-converters> </mvc:annotation-driven>个人博客为:
MoYu's Github Blog
MoYu's Gitee Blog