Spring SpringMVC配置

来源:互联网 发布:微商和淘宝的区别 编辑:程序博客网 时间:2024/05/01 23:38

参考文章:

http://www.cnblogs.com/xing901022/p/5240044.html

http://www.admin10000.com/document/6436.html

为什么使用springMVC:

1、Struts2是类级别的拦截, 一个类对应一个request上下文,SpringMVC是方法级别的拦截,一个方法对应一个request上下文,而方法同时又跟一个url对应,所以说从架构本身上SpringMVC就容易实现restful url,而struts2的架构实现起来要费劲,因为Struts2中Action的一个方法可以对应一个url,而其类属性却被所有方法共享,这也就无法用注解或其他方式标识其所属方法了。
2、由上边原因,SpringMVC的方法之间基本上独立的,独享request response数据,请求数据通过参数获取,处理结果通过ModelMap交回给框架,方法之间不共享变量,而Struts2搞的就比较乱,虽然方法之间也是独立的,但其所有Action变量是共享的,这不会影响程序运行,却给我们编码 读程序时带来麻烦,每次来了请求就创建一个Action,一个Action对象对应一个request上下文。
3、由于Struts2需要针对每个request进行封装,把request,session等servlet生命周期的变量封装成一个一个Map,供给每个Action使用,并保证线程安全,所以在原则上,是比较耗费内存的。
4、 拦截器实现机制上,Struts2有以自己的interceptor机制,SpringMVC用的是独立的AOP方式,这样导致Struts2的配置文件量还是比SpringMVC大。
5、SpringMVC的入口是servlet,而Struts2是filter(这里要指出,filter和servlet是不同的。以前认为filter是servlet的一种特殊),这就导致了二者的机制不同,这里就牵涉到servlet和filter的区别了。
6、SpringMVC集成了Ajax,使用非常方便,只需一个注解@ResponseBody就可以实现,然后直接返回响应文本即可,而Struts2拦截器集成了Ajax,在Action中处理时一般必须安装插件或者自己写代码集成进去,使用起来也相对不方便。
7、SpringMVC验证支持JSR303,处理起来相对更加灵活方便,而Struts2验证比较繁琐,感觉太烦乱。
8、Spring MVC和Spring是无缝的。从这个项目的管理和安全上也比Struts2高(当然Struts2也可以通过不同的目录结构和相关配置做到SpringMVC一样的效果,但是需要xml配置的地方不少)。
9、 设计思想上,Struts2更加符合OOP的编程思想, SpringMVC就比较谨慎,在servlet上扩展。
10、SpringMVC开发效率和性能高于Struts2。
11、SpringMVC可以认为已经100%零配置。

SpringMVC所需jar包:


aopalliance.jar

aspectjweaver.jar

commons-logging-1.1.3.jar

jackson-annotations-2.0.2.jar

jackson-core-2.0.2.jar
jackson-databind-2.0.2.jar

spring-aop-4.2.3.RELEASE.jar
spring-beans-4.2.3.RELEASE.jar
spring-context-4.2.3.RELEASE.jar
spring-core-4.2.3.RELEASE.jar
spring-expression-4.2.3.RELEASE.jar
spring-web-4.2.3.RELEASE.jar
spring-webmvc-4.2.3.RELEASE.jar

jar包下载地址:http://download.csdn.net/detail/u014607184/9589548

web.xml配置:

<?xml version="1.0" encoding="UTF-8"?><web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  xmlns="http://java.sun.com/xml/ns/javaee"  xmlns:web="http://java.sun.com/xml/ns/javaee"  xsi:schemaLocation="http://java.sun.com/xml/ns/javaee   http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"  metadata-complete="true" version="2.5">  <display-name>SpringMVC</display-name>  <welcome-file-list>    <welcome-file>/login.jsp</welcome-file>  </welcome-file-list>    <context-param>    <param-name>contextConfigLocation</param-name>    <param-value>/WEB-INF/spring/spring-core.xml</param-value>  </context-param>    <listener>    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>  </listener>    <servlet>    <servlet-name>springMVC</servlet-name>    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>    <init-param>      <param-name>contextConfigLocation</param-name>      <param-value>/WEB-INF/spring/spring-servlet.xml</param-value>    </init-param>    <load-on-startup>1</load-on-startup>  </servlet>  <servlet-mapping>    <servlet-name>springMVC</servlet-name>    <url-pattern>/</url-pattern>  </servlet-mapping>  </web-app>

其中,必要的配置就是指定servlet和listener.
ContextLoaderListener指定了IOC容器初始化的方法
DispatcherServlet则定义了mvc的相关内容,并配置拦截的url,如上面所示,所有/开头的请求,都会通过SpringMVC这个servlet进行处理。

spring-servlet.xml配置:

<?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:tx="http://www.springframework.org/schema/tx"xmlns:aop="http://www.springframework.org/schema/aop" 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.3.xsd        http://www.springframework.org/schema/context        http://www.springframework.org/schema/context/spring-context-4.3.xsd      http://www.springframework.org/schema/mvc        http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd      http://www.springframework.org/schema/tx      http://www.springframework.org/schema/tx/spring-tx-4.3.xsd      http://www.springframework.org/schema/aop       http://www.springframework.org/schema/aop/spring-aop-4.3.xsd"><description>MVC配置文件 </description>    <!-- 激活组件扫描功能,自动扫描通过注解配置的组件 --><context:component-scan base-package="com.mvc.*"/><!-- 开启注解 --><mvc:annotation-driven><mvc:message-converters register-defaults="true"><bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter" p:supportedMediaTypes="text/html; charset=UTF-8" /></mvc:message-converters></mvc:annotation-driven><context:annotation-config /><!-- 开启AOP自动代理功能 --><aop:aspectj-autoproxy proxy-target-class="true"/>        <!-- 事务(注解 )-->        <tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true" />    <!-- 视图解释器 --><bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"><property name="prefix" value="/WEB-INF/pages/" /><property name="suffix" value=".jsp" /></bean>        <!-- 静态资源访问 --><mvc:resources mapping="/js/**" location="/resources/js/"/><mvc:resources mapping="/css/**" location="/resources/css/"/></beans>  

<context:annotation-config/>配置

使用@Autowired注解,必须事先在Spring容器中声明AutowiredAnnotationBeanPostProcessor的Bean:

<bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor "/>
使用 @Required注解,就必须声明RequiredAnnotationBeanPostProcessor的Bean:

<bean class="org.springframework.beans.factory.annotation.RequiredAnnotationBeanPostProcessor"/>
类似地,使用@Resource、@PostConstruct、@PreDestroy等注解就必须声明 CommonAnnotationBeanPostProcessor;使用@PersistenceContext注解,就必须声明 PersistenceAnnotationBeanPostProcessor的Bean。
这样的声明未免太不优雅,而Spring为我们提供了一种极为方便注册这些BeanPostProcessor的方式,即使用<context:annotation- config/>隐式地向 Spring容器注册AutowiredAnnotationBeanPostProcessor、RequiredAnnotationBeanPostProcessor、CommonAnnotationBeanPostProcessor以及PersistenceAnnotationBeanPostProcessor这4个BeanPostProcessor。如下:

<context:annotation-config/> 
在我们使用注解时一般都会配置扫描包路径选项:
<context:component-scan base-package="pack.pack"/>
该配置项其实也包含了自动注入上述processor的功能,因此当使用<context:component-scan/>后,即可将<context:annotation-config/>省去。

项目文件目录



controller文件

package com.mvc.controller;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;@Controller@RequestMapping(value="/mvc")public class MvcController {@RequestMapping(value="/test",method = {RequestMethod.POST,RequestMethod.GET})    public String hello(){          return "/test";    }}
测试页面test.jsp

<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html>  <head>    <base href="<%=basePath%>">        <title>My JSP 'test.jsp' starting page</title>    <meta http-equiv="pragma" content="no-cache"><meta http-equiv="cache-control" content="no-cache"><meta http-equiv="expires" content="0">    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"><meta http-equiv="description" content="This is my page"><!--<link rel="stylesheet" type="text/css" href="styles.css">-->  </head>    <body>       测试数据访问<br>  </body></html>

访问:http://localhost:8080/SpringMVCTest/mvc/test

 配置解析

  1.Dispatcherservlet
  DispatcherServlet是前置控制器,配置在web.xml文件中的。拦截匹配的请求,Servlet拦截匹配规则要自已定义,把拦截下来的请求,依据相应的规则分发到目标Controller来处理,是配置spring MVC的第一步。
  2.InternalResourceViewResolver
  视图名称解析器
  3.以上出现的注解
  @Controller 负责注册一个bean 到spring 上下文中
  @RequestMapping 注解为控制器指定可以处理哪些 URL 请求


SpringMVC常用注解
  @Controller
  负责注册一个bean 到spring 上下文中
  @RequestMapping
  注解为控制器指定可以处理哪些 URL 请求
  @RequestBody
  该注解用于读取Request请求的body部分数据,使用系统默认配置的HttpMessageConverter进行解析,然后把相应的数据绑定到要返回的对象上 ,再把HttpMessageConverter返回的对象数据绑定到 controller中方法的参数上
  @ResponseBody
  该注解用于将Controller的方法返回的对象,通过适当的HttpMessageConverter转换为指定格式后,写入到Response对象的body数据区
  @ModelAttribute    
  在方法定义上使用 @ModelAttribute 注解:Spring MVC 在调用目标处理方法前,会先逐个调用在方法级上标注了@ModelAttribute 的方法
  在方法的入参前使用 @ModelAttribute 注解:可以从隐含对象中获取隐含的模型数据中获取对象,再将请求参数 –绑定到对象中,再传入入参将方法入参对象添加到模型中 
  @RequestParam 
  在处理方法入参处使用 @RequestParam 可以把请求参 数传递给请求方法
  @PathVariable
  绑定 URL 占位符到入参
  @ExceptionHandler
  注解到方法上,出现异常时会执行该方法
  @ControllerAdvice
  使一个Contoller成为全局的异常处理类,类中用@ExceptionHandler方法注解的方法可以处理所有Controller发生的异常

出现过的问题

错误1:

No mapping found for HTTP request with URI

解决:

(1)在spring的配置文件中添加如下一行

<mvc:default-servlet-handler/>

注意:需要是spring3.0.5以上版本

(2)在spring的配置文件中配置静态访问

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





0 0
原创粉丝点击