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())上