springmvc配置文件配置说明

来源:互联网 发布:一点通打印软件 编辑:程序博客网 时间:2024/06/05 09:35

最近在自学springmvc,通过阅读Paul Deck的Spring MVC学习指南,边看书边做书里贯穿的项目,同时在博客中记录下来,一为加深记忆,深入理解,二来记性差,方便日后翻看。项目github地址:https://github.com/huajianduzhuo/testSpringMVC

1、<context:annotation-config />

启用spring基于annotation的DI(依赖注入),如@Autowired、@Resource等。controller需要调用service等服务来完成业务逻辑,通过@Autowired注入service。

2、<context:component-scan base-package="controller" /><context:annotation-config />

自动扫描配置包下所有标注@Controller的bean。只需要扫描controller,不需要扫描service、dao,service、dao在spring的配置文件里配置扫描

3、<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> 

 <property name="prefix" value="WEB-INF/jsp/"></property>  

 <property name="suffix" value=".jsp"></property> 

     </bean>

配置viewResolver试图解析器,如上配置有前缀和后缀两个属性,可使controller中返回的view视图路径缩短。如WEB-INF/jsp/index.jsp,只需提供index,试图解析器会自动增加前后缀。

4、<mvc:annotation-driven/>

     <mvc:resources location="/css/" mapping="/css/**"/>

如果在web.xml中,配置DispatcherServlet的url-pattern为“/”,那么所有请求都会映射到DispatcherServlet,包括静态资源文件(如js、css、图片等),此时需要在springmvc的配置文件中配置如上resource元素,使静态资源单独处理,不通过DispatcherServlet。

5、

<!-- 从请求和响应读取/编写字符串 --><bean id="stringHttpMessage" class="org.springframework.http.converter.StringHttpMessageConverter"><property name="supportedMediaTypes"><list><value>text/html;charset=UTF-8</value></list></property></bean><!-- 用于将对象转化为JSON --><bean id="jsonConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"><property name="supportedMediaTypes"><list><value>application/json;charset=UTF-8</value></list></property></bean><bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"><property name="messageConverters"><list><ref bean="stringHttpMessage"/><ref bean="jsonConverter"/></list></property></bean>
controller需要返回JSON字符串时,需要进行以上配置


0 0
原创粉丝点击