一、hello world
相对于基于Controller接口的方式,基于注解的方式配置步骤如下:
- HandlerMapping 与HandlerAdapter 分别配置为RequestMappingHandlerMapping、RequestMappingHandlerAdapter(或者添加配置:<mvc:annotation-driven />,详见:<mvc:annotation-driven/>的作用)
- 定义Controller类,添加注解@Controller
- 实例化为bean(xml中显示配置为bean,或添加配置:<context:component-scan />)
控制器
@Controller //@RequestMapping(value = "/matt") public class TestController { @RequestMapping(value = "/hello") public ModelAndView helloWorld() { ModelAndView mv = new ModelAndView(); mv.addObject("message", "hello world"); mv.setViewName("hello"); return mv; } }
spring-mvc.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" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd"> <!-- HandlerMapping --> <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"></bean> <!-- HandlerAdapter --> <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"/> <!-- ViewResolver --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/> <property name="prefix" value="/WEB-INF/jsp/"/> <property name="suffix" value=".jsp"/> </bean> <bean class="cn.matt.controller.TestController"/> </beans>
hello.jsp
<%@ page language="java" %> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Insert title here</title> </head> <body> ${message} </body> </html>
启动后,访问http://localhost:8080/myweb/hello
二、@RequestMapping的使用
@RequestMapping可使用在方法和类上
- 用于方法:表示处理器映射,如上例
- 用于类:表示窄化请求映射,如上例控制器类上添加@RequestMapping(value = "/matt"),访问路径变为:http://localhost:8080/myweb/matt/hello
三、@ResponseBody与@RestController的使用