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 ...
随机推荐
- Ancient Printer HDU - 3460 贪心+字典树
The contest is beginning! While preparing the contest, iSea wanted to print the teams' names separat ...
- PowerShell随笔7 -- Try Catch
PowerShell默认的顺序执行命令,即使中间某一句命令出错,也会继续向下执行. 但是,我们的业务有时并非如此,我们希望出现异常情况后进行捕获异常,进行记录日志等操作. 和其他编程语言一样,我们可以 ...
- 2.Url重定向和重写
虚拟地址===>真实地址映射(搜索引擎优化,抽象能力,防盗链) 之前:IIS重写模块规则,Apache mod_Rewrite.Nginx上的URL重写. 现在:通过中间件来实现. 重定向与重写 ...
- Python 3的f-Strings:增强的字符串格式语法(指南)
最近也在一个视频网站的爬虫,项目已经完成,中间有不少需要总结的经验. 从Python 3.6开始,f-Strings是格式化字符串的一种很棒的新方法.与其他格式化方式相比,它们不仅更具可读性,更简洁且 ...
- WOJ1022 Competition of Programming 贪心 WOJ1023 Division dp
title: WOJ1022 Competition of Programming 贪心 date: 2020-03-19 13:43:00 categories: acm tags: [acm,wo ...
- Leetcode(1)-两数之和
给定一个整数数组和一个目标值,找出数组中和为目标值的两个数. 你可以假设每个输入只对应一种答案,且同样的元素不能被重复利用. 示例: 给定 nums = [2, 7, 11, 15], target ...
- Spring应用上下文生命周期
Spring应用上下文生命周期整体分成四个阶段 ConfigurableApplicationContext#refresh,加载或者刷新持久化配置 ConfigurableApplicationCo ...
- range()函数的使用、while循环、for-in循环等
一.range()函数 用于直接生成一个整数序列 创建range对象的三种方式: (1)range(stop) 创建一个(0,stop)之间的整数序列,步长为1 (2)range(start,s ...
- 设计模式六大原则 All In one
设计模式六大原则 All In one 开闭原则: 对扩展开放,对修改关闭; 设计模式的六大原则: 0.总原则-开闭原则 对扩展开放, 对修改封闭; 在程序需要进行拓展的时候, 不能去修改原有的代码, ...
- Top 10 JavaScript errors
Top 10 JavaScript errors javascript errors https://rollbar.com/blog/tags/top-errors https://rollbar. ...