您的位置:首页 > 编程语言 > Java开发

springMVC笔记(一) Controller的实现和配置(一)

2016-01-03 15:51 489 查看
在SpringMVC 中,控制器Controller 负责处理由DispatcherServlet 分发的请求,它把用户请求的数据经过业务处理层处理之后封装成一个Model ,然后再把该Model 返回给对应的View 进行展示。

Spring 2.5 介绍了一种基于注解的编程模型来实现一个controller,例如

使用@RequestMapping, @RequestParam, @ModelAttribute等等。 如果controller通过这种方式实现就不需要继承特定的基类或者实现特定的接口 。

案例一:

@Controller
public class HomeController {
@RequestMapping("/home")
public String hello() {
return "home";
}
}


可以看出,@Controller和@RequestMapping允许你使用灵活的方法名和标识符。这个例子当中,helloWorld方法返回一个字符串类型的视图名。

@Controller:表示这个特定的类是一个controller

你可以显式定义这个被注解的controller,使用标准的Spring bean的定义。

<?xml version="1.0" encoding="UTF-8"?>
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:p="http://www.springframework.org/schema/p"
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-3.0.xsd                   http://www.springframework.org/schema/context                    http://www.springframework.org/schema/context/spring-context-3.0.xsd                   http://www.springframework.org/schema/mvc                    http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd"> <bean name="/test" class="web.HomeController"&g
9e5c
t;</bean>
<!-- 配置视图解析器 -->
<bean id="viewResolver" class="org.springframework.web.
servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/"/>
<property name="suffix" value=".jsp"/>
</bean>
</beans>


在这种显式定义的情况下,xml文件中的bean name属性,经过测试这个属性是没有作用的,比如你想通过url访问例子中的controller,/test/home是访问不到的,应该使用/home来访问。

@Controller也允许自动扫描(auto detection),你只需要把component scanning加到你的配置当中。

<?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:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="web"/>
<!-- ... -->
</beans>


因为@RequestMapping是把url映射到方法级,如果想前面加一个类级的前缀,可以通过这种方法:

@Controller
@RequestMapping("/test")
public class HomeController {
@RequestMapping("/home")
public String hello() {
return "home";
}
}


现在要访问hello()方法的话,就要使用/test/home这个url了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: