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. Codeforces Global Round 7 D2. Prefix-Suffix Palindrome (Hard version)(Manacher算法+输出回文字符串)

    This is the hard version of the problem. The difference is the constraint on the sum of lengths of s ...

  2. 二叉排序树的构造 && 二叉树的先序、中序、后序遍历 && 树的括号表示规则

    二叉排序树的中序遍历就是按照关键字的从小到大顺序输出(先序和后序可没有这个顺序) 一.以序列 6 8 5 7 9 3构建二叉排序树: 二叉排序树就是中序遍历之后是有序的: 构造二叉排序树步骤如下: 插 ...

  3. Successor HDU - 4366 分块

    代码+注释: 1 /* 2 题意: 3 一共有n个人,其中0号是总裁(金字塔顶尖).后面输入其他n-1个人的信息啊a.b.c,分别代表第i个人的上级是a,他的 4 忠诚度为b,他的能力为c.后面有m次 ...

  4. kubernetes实战-交付dubbo服务到k8s集群(四)使用blue ocean流水线构建dubbo-demo-service

    使用jenkins创建一个新的项目:dubbo-demo,选择流水线构建 勾选保存构建历史和指定项目为参数化构建项目: 添加构建参数:以下配置项,是王导根据多年生产经验总结出来的甩锅大法: 除了bas ...

  5. hdu-1159 1087 1257(dp)

    本文就最长公共子序列,最长连续递增子序列的长度,最大连续递增子序列的值进行对比. hdu-1159: Common Subsequence Time Limit: 2000/1000 MS (Java ...

  6. we have a problem with promise

    we have a problem with promise Q: What is the difference between these four promises? doSomething() ...

  7. pub package all in one

    pub package all in one best practice The pubspec file https://dart.dev/tools/pub/pubspec demo name: ...

  8. website i18n and L10n all in one

    website i18n and L10n all in one Localization & Internationalization 本地化 & 国际化 https://www.w ...

  9. Rust learning notes

    Rust learning notes Rust Version 1.42.0 $ curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs ...

  10. js 上传图片,用户自定义截取图片大小

    js 上传图片,用户自定义截取图片大小 js 组件