spring mvc的基本配置

来源:互联网 发布:软件授权码绑定 编辑:程序博客网 时间:2024/04/30 22:59

    最近项目中一直在用springmvc,个人感觉mvc比起struts2来说,更轻量化,对开发人员更友好,有更多的自由度进行操作。特别是在注解方式下,使得访问和处理都显得很自由。

    简单说下springmvc中的关键类,DispatcherServlet,对于spring来说,每一个dispatcherServlet都对应了一个子容器,如果存在父级容器,那么这些子容器是共享父级容器的,如果不存在会将本身作为父级容器。其中的contextConfigLocation用于指定该servlet需要加载配置文件,即:需要其管理的实体。在一般情况下,建议项目中还是只有一个dispatcherservlet,这样比较便于操作,也不需要担心共享一类的问题。以下为其在web.xml中的配置。

<servlet><servlet-name>springmvc</servlet-name><servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class><init-param><param-name>contextConfigLocation</param-name><param-value>classpath:com/jb/**/*.xml</param-value></init-param><load-on-startup>1</load-on-startup></servlet><servlet-mapping><servlet-name>springmvc</servlet-name><url-pattern>*.do</url-pattern></servlet-mapping>
   这里我们指定编译路径下的com/jb/下的所有.xml文件都为spring的配置文件。下面为主配置文件springmvc.xml,注意我们这里不涉及于hibernate等的整合,仅仅是说明mvc本身。

<?xml version="1.0" encoding="UTF-8"?><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/beanshttp://www.springframework.org/schema/beans/spring-beans-3.2.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context-3.2.xsdhttp://www.springframework.org/schema/mvchttp://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd"><context:annotation-config /> <context:component-scan base-package="com.jb" /><mvc:annotation-driven /><mvc:interceptors><mvc:interceptor><mvc:mapping path="/**/*.do"/><bean class="com.jb.test.interceptor.MvcInterceptor"></bean></mvc:interceptor></mvc:interceptors></beans>  

实际上,我们仅仅需要配置,使用注解就可以运行整个程序了。下面为我们测试的后台实例,我们这里全部采用注解的方式:

@Controller("testController")//注意这里必须使用controller注解,用于指定该类为mvc的控制层处理类public class TestController {//这里配置url中对应的处理方法@RequestMapping("test.do")public void testMvc(HttpServletResponse response) throws IOException{response.getWriter().write("bbb");}}

在地址栏中输入:http://localhost:8080/springmvc/test.do
应该会在页面中显示我们输出的字符串“bbb”.
到此可以任务springmvc的基本框架已经搭建完成。
上面的配置中,额外增加了一个拦截器的配置,interceptor,spring的拦截器需要继承HandlerInterceptorAdapter
需要注意的是,这里的拦截器是在spring找到匹配的路径后,在调用相关方法前会执行里面的方法,如果路径没有匹配成功,这里也不会调用。
大家可以试试里面的3个方法的调用时机,方便开发中灵活使用。详细代码会在下面定时任务中一块上传。



原创粉丝点击