Controller与RestFul

1. Controller

1. 控制器Controller

  • 控制器复杂提供访问应用程序的行为,通常通过接口定义或注解定义两种方法实现。
  • 控制器负责解析用户的请求并将其转换为一个模型。
  • 在Spring MVC中一个控制器类可以包含多个方法
  • 在Spring MVC中,对于Controller的配置方式有很多种

2. 利用接口定义控制器

1. 实现Controller接口

在类中重写ModelAndView方法实现功能

package com.wang.controller;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; //只要实现了Controller接口的类, 说明这就是一个控制器了
public class ControllerTest1 implements Controller {
@Override
public ModelAndView handleRequest(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
ModelAndView mv = new ModelAndView(); //设置视图的属性
mv.addObject("msg", "ControllerTest1");
//设置跳转的页面
mv.setViewName("test"); return mv;
}
}

2. 在spring配置文件中注册请求的bean

其中, name对应请求的路径, class对应处理请求的类

<?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
https://www.springframework.org/schema/mvc/spring-mvc.xsd"> <context:component-scan base-package="com.wang.controller"/> <mvc:default-servlet-handler/> <mvc:annotation-driven/> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"
id="internalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean> <bean name="/t1" class="com.wang.controller.ControllerTest1"/> </beans>

3. 编写前端jsp

<%--
Created by IntelliJ IDEA.
User: Wang
Date: 2020/9/8
Time: 14:17
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>ControllerTest</title>
</head>
<body> <h1>${msg}</h1> </body>
</html>

4. 注意

  • 实现Controller接口是一个较老的办法, 最好不要使用它!

  • 要在web.xml中配置DispatcherServlet

    <?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"> <!--配置DispatcherServlet-->
    <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-servlet.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. 利用注解实现控制器

1. 在spring配置文件中声明组件扫描

<context:component-scan base-package="com.wang.controller"/>

2. 在Spring配置文件中配置三大件与静态资源过滤

<?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
https://www.springframework.org/schema/mvc/spring-mvc.xsd"> <context:component-scan base-package="com.wang.controller"/> <mvc:default-servlet-handler/> <mvc:annotation-driven/> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"
id="internalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean> </beans>

3. 在类中利用注解实现

两个关键注解

  • @Controller

    • 代表这个类会被Spring接管, 这个注解的类中的所有方法, 如果返回值是String, 并且有具体的页面可以跳转, 那么就会被视图解析器解析!
  • @RequestMapping("/...")
package com.wang.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping; //代表这个类会被Spring接管, 这个注解的类中的所有方法, 如果返回值是String, 并且有具体的页面可以跳转, 那么就会被视图解析器解析!
@Controller
public class ControllerTest2 { //映射访问路径
@RequestMapping("/t2")
public String test1 (Model model) { model.addAttribute("msg", "ControllerTest2"); //此处的返回的字符串与要跳转的页面名一致!
return "test";
} }

4. 注意

可以使两个请求指向同一个视图, 但是返回不同的页面结果, 从而实现视图的复用, 控制器与视图之间是弱耦合关系

package com.wang.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping; //代表这个类会被Spring接管, 这个注解的类中的所有方法, 如果返回值是String, 并且有具体的页面可以跳转, 那么就会被视图解析器解析!
@Controller
public class ControllerTest2 { //映射访问路径
@RequestMapping("/t2")
public String test2 (Model model) { model.addAttribute("msg", "ControllerTest2"); //此处的返回的字符串与要跳转的页面名一致!
return "test";
} //映射访问路径
@RequestMapping("/t3")
public String test3 (Model model) { model.addAttribute("msg", "ControllerTest3"); //此处的返回的字符串与要跳转的页面名一致!
return "test";
} }

4. RequestMapping

ResquestMapping可以加在类或者方法上(源码中的@Target)

同时注解了类和方法, 则存在父子关系

package com.wang.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping; @Controller
@RequestMapping("/c3")
public class ControllerTest3 { //此时要访问/c3/t1才能访问到下面写的资源
@RequestMapping("/t1")
public String test3(Model model) {
model.addAttribute("msg", "ControllerMapping");
return "test";
}
}

2. RestFul风格

1. 原来的url风格

url: http://localhost:8080/add?a=1&b=2

package com.wang.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping; @Controller
public class RestFulController { //原来的
//http://localhost:8080/add?a=1&b=2
//由于此处要求有两个参数, url必须传参, 否则报500错误
@RequestMapping("/add")
public String test(int a, int b, Model model) {
int res = a + b;
model.addAttribute("msg", "结果为" + res);
return "test";
} }

2. RestFul风格

1. 简单的RestFul

在Spring MVC中可以使用 @PathVariable 注解,让方法参数的值对应绑定到一个URI模板变量上

url: http://localhost:8080/add/1/2

package com.wang.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping; @Controller
public class RestFulController { //使用RestFul风格, 变量用 / 分隔
//此时的url: http://localhost:8080/add/1/2
@RequestMapping("/add/{a}/{b}")
public String test(@PathVariable int a, @PathVariable int b, Model model) {
int res = a + b;
model.addAttribute("msg", "结果为" + res);
return "test";
} }

2. 使用method属性指定请求类型

用于约束请求的类型,可以收窄请求范围。指定请求谓词的类型如GET, POST, HEAD, OPTIONS, PUT, PATCH, DELETE, TRACE等

package com.wang.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod; @Controller
public class RestFulController { /*
此注解与下面的注解等价, 都是以get方法去提交
@RequestMapping(value = "/add/{a}/{b}", method = RequestMethod.GET)
*/
@GetMapping("/add/{a}/{b}")
public String test(@PathVariable int a, @PathVariable int b, Model model) {
int res = a + b;
model.addAttribute("msg", "结果为" + res);
return "test";
} }

3. 总结

pring MVC 的 @RequestMapping 注解能够处理 HTTP 请求的方法, 比如 GET, PUT, POST, DELETE 以及 PATCH。

*所有的地址栏请求默认都会是 HTTP GET 类型的。*

方法级别的注解变体有如下几个:组合注解

@GetMapping
@PostMapping
@PutMapping
@DeleteMapping
@PatchMapping

@GetMapping 是一个组合注解,平时使用的会比较多!

它所扮演的是 @RequestMapping(method =RequestMethod.GET) 的一个快捷方式。

RestFul的特点:

  • 简洁(用 / 分隔)
  • 高效(支持缓存)
  • 安全(无法看到传递的参数名)

SpringMVC-Controller&RestFul的更多相关文章

  1. [转]SpringMVC Controller介绍及常用注解

    一.简介 在SpringMVC 中,控制器Controller 负责处理由DispatcherServlet 分发的请求,它把用户请求的数据经过业务处理层处理之后封装成一个Model ,然后再把该Mo ...

  2. SpringMVC Controller介绍

    SpringMVC Controller 介绍 一.简介 在SpringMVC 中,控制器Controller 负责处理由DispatcherServlet 分发的请求,它把用户请求的数据经过业务处理 ...

  3. SpringMVC Controller 介绍

    一.简介 在SpringMVC 中,控制器Controller 负责处理由DispatcherServlet 分发的请求,它把用户请求的数据经过业务处理层处理之后封装成一个Model ,然后再把该Mo ...

  4. SpringMVC Controller介绍(转)

    SpringMVC Controller 介绍 一.简介 在SpringMVC 中,控制器Controller 负责处理由DispatcherServlet 分发的请求,它把用户请求的数据经过业务处理 ...

  5. SpringMVC Controller详解

    SpringMVC Controller 介绍 一.简介 在SpringMVC 中,控制器Controller 负责处理由DispatcherServlet 分发的请求,它把用户请求的数据经过业务处理 ...

  6. SpringMVC Controller介绍及常见注解

    一.简介 在SpringMVC中,控制器Controller负责处理由DispatcherServlet分发的请求,它把用户请求的数据经过业务处理层处理之后封装成一个Model,然后再把该Model返 ...

  7. 【转】SpringMVC Controller 介绍

    转自:原文url 一.简介 在SpringMVC 中,控制器Controller 负责处理由DispatcherServlet 分发的请求,它把用户请求的数据经过业务处理层处理之后封装成一个Model ...

  8. SpringMVC实现RESTful服务

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

  9. SpringMVC Controller 介绍及常用注解

    摘要: @Controller.@RequestMapping(属性:value.params .method.headers).@PathVariable.@RequestParam.@Cookie ...

  10. 基于springMVC的RESTful服务实现

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

随机推荐

  1. XCTF-WEB-高手进阶区(1-4)笔记

    1:baby_web 题目描述:想想初始页面是哪个 通过Dirsearch软件扫描发现Index.php被藏起来了,访问他便会指向1.php 于是通过Burp修改Get为index.php,然后放入R ...

  2. C#设计模式之0-简单工厂模式

    简单工厂模式(Simple Factory Pattern) 该文章的最新版本已迁移至个人博客[比特飞],单击链接 https://www.byteflying.com/archives/387 访问 ...

  3. Compilation failed (return status=1): g++.exe: error: CreateProcess: No such file or directory错误

    windows10上 theano安装之后出现的问题 >>> import theano You can find the C code in this temporary file ...

  4. 阙乃祯:网龙在教育领域Cassandra的使用

    网龙是一家游戏公司,以前是做网络在线游戏的,现在开始慢慢转型,开始从事在线教育. 在线教育已经做了5-6年时间了.为什么我们会用Cassandra呢?那我们就来介绍今天的议题. 首先介绍我们的业务背景 ...

  5. 在 Go 语言中,我为什么使用接口

    强调一下是我个人的见解以及接口在 Go 语言中的意义. 如果您写代码已经有了一段时间,我可能不需要过多解释接口所带来的好处,但是在深入探讨 Go 语言中的接口前,我想花一两分钟先来简单介绍一下接口. ...

  6. 【CF1110E】 Magic Stones - 差分

    题面 Grigory has n n magic stones, conveniently numbered from \(1\) to \(n\). The charge of the \(i\)- ...

  7. JS 时间获取 (常用)

    /** * 获取几天之前日期 */ daysAgo(dayNum = 0) { let myDate = new Date() let lw = new Date(myDate - 1000 * 60 ...

  8. hook框架-frida使用-环境配置

    一.python安装模块 pip3 install frida pip3 install frida-tools 二.下载frida-server #下载链接 https://github.com/f ...

  9. Jmeter 常用函数(21)- 详解 __char

    如果你想查看更多 Jmeter 常用函数可以在这篇文章找找哦 https://www.cnblogs.com/poloyy/p/13291704.htm 作用 根据给定的字符值转换成 Unicode ...

  10. 基于 abp vNext 微服务开发的敏捷应用构建平台 - 设计构想

    许多中小企业的管理模式都是在自身的发展过程中不断摸索,逐步建立起来的,每一家都有其独有的管理模式,而且随着企业的不断发展,管理模式也在不断变化中.企业在发展壮大的过程中离不开信息化系统的支撑,企业在构 ...