基于注解的控制器

本文介绍了Spring框架中基于注解的控制器,讲解了@Controller注解如何标识控制器类,并阐述了Spring如何通过扫描机制找到这些类。此外,还详细解析了@RequestMapping注解,包括在方法和类级别上的使用,以及value和method属性的应用,帮助理解如何映射URI和HTTP方法。

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

1.1 Controller注解类型

使用org.springframework.stereotype.Controller注解类型用于指示Spring类的实例是一个控制器。
在类上方声明@Controller

Spring使用扫描机制找到所有应用程序中基于注解的控制器类。

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans  
           http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
           http://www.springframework.org/schema/mvc    
           http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
           http://www.springframework.org/schema/context 
           http://www.springframework.org/schema/context/spring-context-4.0.xsd">
       <!--在<component-scan/>元素中指定控制器类的基本包 -->
       <context:component-scan base-package="com.example.controller"/>
</beans>

1.2 RequestMapping注解类型

我们要让控制器类的内部为每一个动作开发相应的处理方法,使用
org.springframework.web.bind.annotation.RequestMapping注解类型映射URI和方法

1、在方法上方声明@RequsetMapping,该方法会成为一个请求处理方法。

@Controller
public class CustomerController {
    @RequestMapping(value = "/customer_input",method = RequestMethod.GET)
    public String inputCustomer(){
        //...
        return "CustomerForm";
    }
}

value属性将URI(customer_input)映射到方法(inputCustomer()),可以用如下URL http://xxx/xxx/customer_input访问inputCustomer方法。

method属性用来指示该方法仅处理哪些HTTP方法,如果没有指定属性值则可以处理任意HTTP方法。多个方法需要放在花括号{ }里。

2、在类上方声明@RequsetMapping,所有的方法都将映射为相对应类级别的请求。

@Controller
@RequestMapping("/customer")
public class CustomerController {
    @RequestMapping(value = "/delete",
                    method = {RequestMethod.GET,RequestMethod.POST})
    public String delCustomer(){
        //...
        return ...;
    }
}

则如下URL:http://xxx/xxx/customer/delete 映射到该方法(delCustomer())上

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值