SpringMVC:Controller及RestFul风格

本文详细介绍了SpringMVC中控制器的两种实现方式:接口定义和注解定义,并通过示例展示了如何配置和使用。还探讨了使用注解@Controller的便利性和在实际项目中的应用,包括@RequestMapping的使用以及Restful风格的HTTP请求方法。此外,还通过一个RestFulController的例子解释了如何处理路径变量和指定请求类型。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

控制器Controller

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

实现控制器的方式

公共配置文件

  • 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-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>
  • springmvc-servlet.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
       https://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <context:component-scan base-package="indi.stitch.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="indi.stitch.controller.ControllerTest1"></bean>
</beans>

实现Controller接口

  • Contoller是一个接口,在org.springframework.web.servlet.mvc包下,接口中只有一个方法:
package org.springframework.web.servlet.mvc;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.lang.Nullable;
import org.springframework.web.servlet.ModelAndView;

// 实现该接口的类获得控制器功能
@FunctionalInterface
public interface Controller {
	// 处理请求并返回一个模型与视图对象
    @Nullable
    ModelAndView handleRequest(HttpServletRequest var1, HttpServletResponse var2) throws Exception;
}
  • 在springmvc-servlet.xml中配置Controller访问路径
<bean name="/t1" class="indi.stitch.controller.ControllerTest1"></bean>
  • 创建test.jsp文件,展示处理后的ModuleAndVIew对象
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
${msg}
</body>
</html>
  • 启动Tomcat,访问http://localhost:8080/t1
    在这里插入图片描述

说明

  • 实现接口Controller定义控制器是较老的办法
  • 缺点是:一个控制器中只能写一个方法,如果要多个方法需要定义多个Controller;定义的方式比较麻烦。

使用注解Controller

  • @Controller注解类型用于声明Spring类的实例是一个控制器;
  • Spring可以使用扫描机制来找到应用程序中所有基于注解的控制器类,为了保证Spring能找到自己的控制器,需要在配置文件中声明组件扫描。
<!--自动扫描执行的包,下面所有注解类交给IOC容器管理-->
    <context:component-scan base-package="indi.stitch.controller" />
  • 新建ControllerTest2类,使用注解实现:
package indi.stitch.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

// 使用@Controller注解的类会自动添加到Spring上下文中
@Controller
public class ControllerTest2 {
    // 映射访问路径
    @RequestMapping("/t2")
    public String test2(Model model) {
        // SpringMVC会自动实例化一个Model对象用于向视图中传值
        model.addAttribute("msg", "ControllerTest2");
        // 返回视图位置
        return "test";
    }

    @RequestMapping("/t3")
    public String test3(Model model) {
        // SpringMVC会自动实例化一个Model对象用于向视图中传值
        model.addAttribute("msg", "ControllerTest3");
        // 返回视图位置
        return "test";
    }
}
  • 重新发布Tomcat,访问http://localhost:8080/t2
    在这里插入图片描述

两个请求都可以指向同一个视图,但是页面的结果是不一样的,可以看出视图是被复用的,控制器和视图之间是弱耦合关系。

使用注解可以在一个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风格

  概念
  RestFul就是一个资源定位及资源操作的风格,不是标准也不是协议,只是一种风格。基于这个风格设计的软件可以更简洁,更有层次,更易于实现缓存等机制。
  功能

  • 资源:互联网所有事物都可以被抽象为资源
  • 资源操作:使用POST、DELETE、PUT、GET,使用不同方法对资源进行操作。
  • 分别对应添加、删除、修改、查询

  传统方式操作资源:通过不同的方式来实现不同的效果,方法单一,post和get

  • http://127.0.0.1/item/queryItem.action?id=1 查询,GET
  • http://127.0.0.1/item/saveItem.action 新增,POST
  • http://127.0.0.1/item/updateItem.action 修改,POST
  • http://127.0.0.1/item/deleteItem.action?id=1 删除,GET或POST

  使用RestFul操作资源:可以通过不同的请求方式来实现不同的效果,请求地址一样,但是功能可以不同!

  • http://127.0.0.1/item/1 查询,GET
  • http://127.0.0.1/item 新增,POST
  • http://127.0.0.1/item 更新,PUT
  • http://127.0.0.1/item/1 删除,DELETE

  学习测试
1、创建RestFulController类

@Controller
public class RestFulController {

}

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

package indi.stitch.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 {
    @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";
    }
}

3、测试请求
在这里插入图片描述
使用路径变量的好处:
   (1)使路径变得更加简洁;
   (2)获得参数更加方便,框架会自动进行类型转换;
   (3)通过路径变量类型可以约束访问参数,如果类型不一样就访问不到对应的请求方法,如果这里访问的路径是/add/1/a,则路径与方法不匹配,导致请求失败
在这里插入图片描述
4、修改对应的参数类型,再次进行测试

package indi.stitch.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 {
    @RequestMapping("/add/{a}/{b}")
    public String test(@PathVariable int a, @PathVariable String b, Model model) {
        String res = a + b;
        model.addAttribute("msg", "结果为:" + res);
        return "test";
    }
}

在这里插入图片描述
  使用method属性指定请求类型
  用于约束请求的类型,可以收窄请求范围。指定请求谓词的类型如GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS, TRACE等
  学习测试
  新增一个方法,指定请求类型为POST:

 @RequestMapping(value = "/hello", method = {RequestMethod.POST})
    public String test2(Model model) {
        model.addAttribute("msg", "Hello!");
        return "test";
    }

浏览器默认的请求方式为GET,此时会报错405:
在这里插入图片描述

将POST改为GET就可以正常访问了:

@RequestMapping(value = "/hello", method = {RequestMethod.GET})
    public String test2(Model model) {
        model.addAttribute("msg", "Hello!");
        return "test";
    }

在这里插入图片描述
方法级别的注解变体有如下几个组合注解:

@GetMapping
@PostMapping
@PutMapping
@DeleteMapping
@PatchMapping

组合注解的使用方式,如:

@GetMapping

等同于

@RequestMapping(method={RequestMethod.GET})
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值