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.功能

资源:互联网所有的事物都可以被抽象为资源

资源操作:使用POSTDELETEPUTGET,使用不同方法对资源进行操作。

分别对应 添加、 删除、修改、查询。

传统方式操作资源 :通过不同的参数来实现不同的效果,方法单一,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请求,可以正常发送的只有GETPOST,而在RestFul风格中PUTDELETEPATCH则不能直接发送,可以使用以下方法:

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>

个人博客为:

MoYu's Github Blog

MoYu's Gitee Blog

SpringMVC-03 RestFul和控制器的更多相关文章

  1. 基于springMVC的RESTful服务实现

    一,什么是RESTful RESTful(RESTful Web Services)一种架构风格,表述性状态转移,它不是一个软件,也不是一个标准,而是一种思想,不依赖于任何通信协议,但是开发时要成功映 ...

  2. 基于 springMVC 的 RESTful HTTP API 实践(服务端)

    理解 REST REST(Representational State Transfer),中文翻译叫"表述性状态转移".是 Roy Thomas Fielding 在他2000年 ...

  3. SpringMVC实现RESTful服务

    SpringMVC实现RESTful服务 这里只说service,controller层的代码.Mapper层则直接继承Mapper<T>则可以,记住mybatis-config.xml一 ...

  4. springMVC基于注解的控制器

    springMVC基于注解的控制器 springMVC基于注解的控制器的优点有两个: 1.控制器可以处理多个动作,这就允许将相关操作写在一个类中. 2.控制器的请求映射不需要存储在配置文件中.使用re ...

  5. springmvc的RESTful风格

    springmvc对RESTful得支持RESTful架构,就是目前最流行得一种互联网软件架构.它结构清晰.符合标准.易于理解.扩展方便,所以挣得到越来越多网站的采用. RESTful(即Repres ...

  6. RestFul和控制器

    RestFul和控制器 控制器Controller 控制器复杂提供访问应用程序的行为,通常通过接口定义或注解定义两种方法实现. 控制器负责解析用户的请求并将其转换为一个模型. 在Spring MVC中 ...

  7. springmvc中配置RESTful风格控制器

    一般的http请求中其实只需要get和post就可以满足项目需求了,而为什么还要使用restful可能就是为了使请求url看起来更加直观,好看吧.. restful常用的请求方式:get,post,p ...

  8. SpringMVC实现Restful风格的WebService

    1.环境 JDK7 MyEclipse2014 tomcat8 maven 3.3.3 spring4.1.4 2.创建maven工程 使用MyEclipse创建maven工程的方式可以参考这篇博文( ...

  9. SpringMVC构建Restful。

    因为spring是依赖jackson来生成json,需要添加jar包. pom.xml文件添加依赖. <dependency> <groupId>org.codehaus.ja ...

随机推荐

  1. 一文弄懂使用Jmeter来进行性能测试

    该文章是基于上一次文章的 软件测试漫谈(web测试,自动化测试,Jmeter) 的续篇, 主要是详细讲解 Jmeter 的入门教程. 因为上次的文章只是简单地讲解了 Jmeter 的使用和一些概念,所 ...

  2. 9.PowerShell DSC之Pull

    前言 一般生产环境都使用Pull模式 配置Pull Server 配置Pull Server需要安装两个WindowsFeture:IIS.windows DSC,这两都可以通过UI界面化引导安装,也 ...

  3. jackson学习之十(终篇):springboot整合(配置类)

    欢迎访问我的GitHub https://github.com/zq2599/blog_demos 内容:所有原创文章分类汇总及配套源码,涉及Java.Docker.Kubernetes.DevOPS ...

  4. OPENSOURCE - libcurl

    本文仅做备份存档,原文地址如下,请点链接进入 https://www.cnblogs.com/moodlxs/archive/2012/10/15/2724318.html https://www.c ...

  5. LINUX - 获取本地ip

    Linux编程获取本机IP地址的几种方法 参考: https://blog.csdn.net/zhongmushu/article/details/89944990 https://www.cnblo ...

  6. linux内核编程入门--系统调用监控文件访问

    参考的资料: hello world   https://www.cnblogs.com/bitor/p/9608725.html linux内核监控模块--系统调用的截获  https://www. ...

  7. C++ 结构体 segment fault

    形如 struct node { int key; int height; int size; //tree node 个数 node *left, *right; node(int x) : key ...

  8. POJ 3581 Sequence(后缀数组)题解

    题意: 已知某字符串\(str\)满足\(str_1 > max\{str_2,str_3 \cdots str_n\}\),现要求把这个字符串分成连续的三组,然后每组都翻转,问字典序最小是什么 ...

  9. apache 解析漏洞(CVE-2017-15715)

    在p牛博客最近更新的文章,传送门,感觉很有意思,自己在自己本地测试了一下 0x01 正则表达式中的 '$' apache这次解析漏洞的根本原因就是这个 $,正则表达式中,我们都知道$用来匹配字符串结尾 ...

  10. Fetch API & cancel duplicate API & cache API

    Fetch API & cancel duplicate API & cache API const usersCache = new Map<string, User>( ...