SpringMVC-03 RestFul和控制器
SpringMVC-03 RestFul和控制器
控制器Controller
- 控制器复杂提供访问应用程序的行为,通常通过接口定义或注解定义两种方法实现。
- 控制器负责解析用户的请求并将其转换为一个模型。
- 在Spring MVC中一个控制器类可以包含多个方法
- 在Spring MVC中,对于Controller的配置方式有很多种
RequestMapping
注解方式是平时使用的最多的方式!
@RequestMapping
@RequestMapping注解用于映射url到控制器类或一个特定的处理程序方法。可用于类或方法上。用于类上,表示类中的所有响应请求的方法都是以该地址作为父路径。
为了测试结论更加准确,我们可以加上一个项目名测试
只注解在方法上面
@Controller
public class TestController {
@RequestMapping("/h1")
public String test(){
return "test";
}
}
访问路径:http://localhost:8080 / 项目名 / h1
同时注解类与方法
@Controller
@RequestMapping("/admin")
public class TestController {
@RequestMapping("/h1")
public String test(){
return "test";
}
}
访问路径:http://localhost:8080 / 项目名/ admin /h1
RestFul 风格
1.概念
Restful就是一个资源定位及资源操作的风格。不是标准也不是协议,只是一种风格。基于这个风格设计的软件可以更简洁,更有层次,更易于实现缓存等机制。
2.功能
资源:互联网所有的事物都可以被抽象为资源
资源操作:使用POST、DELETE、PUT、GET,使用不同方法对资源进行操作。
分别对应 添加、 删除、修改、查询。
传统方式操作资源 :通过不同的参数来实现不同的效果,方法单一,post 和 get
http://localhost:8080/item/queryItem.action?id=1 查询,GET
http://localhost:8080/item/saveItem.action 新增,POST
http://localhost:8080/item/updateItem.action 更新,POST
http://localhost:8080/item/deleteItem.action?id=1 删除,GET或POST
使用RESTful操作资源 :可以通过不同的请求方式来实现不同的效果。如下:请求地址一样,但是功能可以不同。
http://localhost:8080/item/1 查询,GET
http://localhost:8080/item 新增,POST
http://localhost:8080/item 更新,PUT
http://localhost:8080/item/1 删除,DELETE
3.案例测试
3.1 编写web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
3.2 创建springmvc.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<context:component-scan base-package="Controller"/>
<mvc:annotation-driven/>
<mvc:default-servlet-handler/>
<!-- 添加 视图解析器 -->
<!--视图解析器:DispatcherServlet给他的ModelAndView-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="InternalResourceViewResolver">
<!--前缀-->
<property name="prefix" value="/jsp/"/>
<!--后缀-->
<property name="suffix" value=".jsp"/>
</bean>
</beans>
3.3 新建一个Controller类
@Controller
public class RestFulController {
//映射访问路径
@RequestMapping("/commit/{p1}/{p2}")
public String index(@PathVariable int p1, @PathVariable int p2, Model model){
int result = p1+p2;
//Spring MVC会自动实例化一个Model对象用于向视图中传值
model.addAttribute("msg", "结果:"+result);
//返回视图位置
return "test";
}
}
3.4 创建test.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>RestFul</title>
</head>
<body>
${msg}
</body>
</html>
3.5 配置Tomcat,测试

思考:使用路径变量的好处?
- 使路径变得更加简洁;
- 获得参数更加方便,框架会自动进行类型转换;
- 通过路径变量的类型可以约束访问参数,如果类型不一样,则访问不到对应的请求方法,如这里访问是的路径是
/commit/1/a,则路径与方法不匹配,而不会是参数转换失败;
3.6 修改参数类型
@Controller
public class RestFulController {
//映射访问路径
@RequestMapping("/commit/{p1}/{p2}")
public String index(@PathVariable int p1, @PathVariable String p2, Model model){
String result = p1+p2;
//Spring MVC会自动实例化一个Model对象用于向视图中传值
model.addAttribute("msg", "结果:"+result);
//返回视图位置
return "test";
}
}

3.7 指定请求类型
使用method属性指定请求类型
用于约束请求的类型,可以收窄请求范围。指定请求谓词的类型如GET, POST, HEAD, OPTIONS, PUT, PATCH, DELETE, TRACE......
我们来测试一下:
- 增加一个方法:
//映射访问路径,必须是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" name="_method" value="PUT">
<p>姓名:</p><input type="text" name="name" /><br/>
<p>性别:</p><input type="text" name="sex" /><br/>
<p>年龄:</p><input type="text" name="age" /><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
4.测试

会发现填写的中文都成为了?,这时候可以尝试在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 class="org.springframework.http.converter.StringHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>text/plain;charset=UTF-8</value>
<value>text/html;charset=UTF-8</value>
</list>
</property>
</bean>
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>application/json;charset=UTF-8</value>
</list>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>


SpringMVC-03 RestFul和控制器的更多相关文章
- 基于springMVC的RESTful服务实现
一,什么是RESTful RESTful(RESTful Web Services)一种架构风格,表述性状态转移,它不是一个软件,也不是一个标准,而是一种思想,不依赖于任何通信协议,但是开发时要成功映 ...
- 基于 springMVC 的 RESTful HTTP API 实践(服务端)
理解 REST REST(Representational State Transfer),中文翻译叫"表述性状态转移".是 Roy Thomas Fielding 在他2000年 ...
- SpringMVC实现RESTful服务
SpringMVC实现RESTful服务 这里只说service,controller层的代码.Mapper层则直接继承Mapper<T>则可以,记住mybatis-config.xml一 ...
- springMVC基于注解的控制器
springMVC基于注解的控制器 springMVC基于注解的控制器的优点有两个: 1.控制器可以处理多个动作,这就允许将相关操作写在一个类中. 2.控制器的请求映射不需要存储在配置文件中.使用re ...
- springmvc的RESTful风格
springmvc对RESTful得支持RESTful架构,就是目前最流行得一种互联网软件架构.它结构清晰.符合标准.易于理解.扩展方便,所以挣得到越来越多网站的采用. RESTful(即Repres ...
- RestFul和控制器
RestFul和控制器 控制器Controller 控制器复杂提供访问应用程序的行为,通常通过接口定义或注解定义两种方法实现. 控制器负责解析用户的请求并将其转换为一个模型. 在Spring MVC中 ...
- springmvc中配置RESTful风格控制器
一般的http请求中其实只需要get和post就可以满足项目需求了,而为什么还要使用restful可能就是为了使请求url看起来更加直观,好看吧.. restful常用的请求方式:get,post,p ...
- SpringMVC实现Restful风格的WebService
1.环境 JDK7 MyEclipse2014 tomcat8 maven 3.3.3 spring4.1.4 2.创建maven工程 使用MyEclipse创建maven工程的方式可以参考这篇博文( ...
- SpringMVC构建Restful。
因为spring是依赖jackson来生成json,需要添加jar包. pom.xml文件添加依赖. <dependency> <groupId>org.codehaus.ja ...
随机推荐
- 洛谷 P2895 [USACO08FEB]Meteor Shower S (BFS)
题意:你刚开始位于坐标轴的\((0,0)\)点,一共有\(m\)颗流星砸向地面,每颗流星在\(t\)时砸到\((x,y)\)点,其四周上下左右也均有波及,你每秒可以向上下左右移动一个单位,问你是否可以 ...
- C# TCP应用编程三 异步TCP应用编程
利用TcpListener和TcpClient类在同步方式下接收.发送数据以及监听客户端连接时,在操作没有完成之前一直处于阻塞状态,这对于接受.发送数据量不大的情况或者操作勇士较短的情况下是比较方便的 ...
- 2.PowerShell概述
PowerShell PowerShell命令窗一般随系统带着,运行->输入:powershell,即可打开命令窗口. 命令 Powershell有诸多命令,兼容cmd命令 语法和命令 在此我推 ...
- 微服务架构学习Day01-SpringBoot入门
基本概念 SpringBoot的优点: 可以创建独立的Spring应用 SpringBoot嵌入Tomcat,Jetty和Unsertow, 不需要部署war文件 根据需要通过maven获取start ...
- Zabbix 监控 SNMP & JMX
Zabbix 配置清华源 # 安装清华源 yum 仓库 [root@db01 ~]# rpm -ivh https://mirrors.tuna.tsinghua.edu.cn/zabbix/zabb ...
- string logo(字符画),website,html5,css3,atom ide
1 <!DOCTYPE html> <!-- Powered by... _ _ ____. ______ ._______. _______ ___ ___ sssssssss \ ...
- 使用 js 实现一个简易版的 GIPHY 动图搜索 web 应用程序
使用 js 实现一个简易版的 GIPHY 动图搜索 web 应用程序 具有挑战性的前端面试题 API JAMstack refs https://www.infoq.cn/article/0NUjpx ...
- js console 性能测试 & don't-use-array-foreach-use-for-instead
don't-use-array-foreach-use-for-instead slower https://coderwall.com/p/kvzbpa/don-t-use-array-foreac ...
- how to check website offline status in js
how to check website offline status in js https://developer.mozilla.org/en-US/docs/Web/API/Navigator ...
- React & Calendar
React & Calendar 日历 https://github.com/YutHelloWorld/calendar/blob/master/src/Calendar.js // 国际化 ...