1. @Controller
该注解用于标记在一个类上,使用它标记的类就是一个SpringMVC的Controller对象。用于分发处理器将会扫描使用了该注解的类的方法,并检测该方法是否使用了 @RequestMapping 注解。@Controller 注解只是定义了一个控制器类,而使用 @RequstMapping 注解的方法才是真正处理请求的处理器。
@Contoller 标记在一个类上还不能真正意义上说它就是SpringMVC的一个控制器,还需要将其交给Spring容器来进行管理:
<!--方式一-->
<bean class="com.cqvie.handler.HelloWorld"/>
<!--方式二-->
< context:component-scan base-package = "com.sztxtech" /> <!-- 路径写到controller的上一层 -->
此外,Controller 不会直接依赖于 HttpServletRequest 和 HttpServletResponse 等 HttpServlet 对象,它们可以通过 Controller 的方法参数灵活的获取到。
2. @RequestMapping
该注解是一个用来处理请求地址映射的注解,可用于类或方法上。用于类上,表示类中的所有方法的请求都是以该地址作为父路径的。
返回值会通过视图解析器解析为实际的物理视图,对于 InternalResourceViewResolver 视图解析器,会做如下的解析:通过 prefix + returnVal + suffix 这样的方式得到实际的物理视图,然后做转发操作。
<!-- 配置视图解析器:如何把 handler 方法返回值解析为实际的物理视图 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
RequestMapping 注解有以下属性:
(1) value :指定请求的实际地址;
(2) method:指定请求的方法类型,包括 GET、POST、PUT、DELETE 等;
/**
* Rest 风格的 URL(以 CRUD 为例):
* 新增:/order POST
* 修改:/order/1 PUT
* 获取:/order/1 GET
* 删除:/order/1 DELETE
* @param id
* @return
*/
@RequestMapping(value = "/testRestPut/{id}", method = RequestMethod.PUT)
public String testRestPut(@PathVariable int id) {
System.out.println("testRestPut:" + id);
return SUCCESS;
}
@RequestMapping(value = "/testRestDelete/{id}", method = RequestMethod.DELETE)
public String testRestDelete(@PathVariable int id) {
System.out.println("testRestDelete:" + id);
return SUCCESS;
}
@RequestMapping(value = "/testRestPost/{id}", method = RequestMethod.POST)
public String testRestPost(@PathVariable int id) {
System.out.println("testRestPost:" + id);
return SUCCESS;
}
@RequestMapping("/testRestGet")
public String testRestGet() {
System.out.println("testRestGet");