maven搭建springmvc框架介绍:
pom.xml文件:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.somnus</groupId> <artifactId>SpringMVC</artifactId> <packaging>war</packaging> <version>0.0.1-SNAPSHOT</version> <name>SpringMVC Maven Webapp</name> <url>http://maven.apache.org</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </properties> <!-- 指定Maven仓库 --> <repositories> <!-- oschina的maven仓库 --> <repository> <id>oschinaRepository</id> <name>local private nexus</name> <url>http://maven.wozsz.com/content/groups/public/</url> <releases> <enabled>true</enabled> </releases> <snapshots> <enabled>true</enabled> </snapshots> </repository> </repositories> <!-- maven依赖包的书写是有顺序的,请不要更改下面dependency的顺序,避免造成JAR包冲突 --> <dependencies> <!-- servlet & jsp --> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>2.5</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>jsp-api</artifactId> <version>2.2</version> <scope>provided</scope> </dependency> <!-- 加入springmvc依赖包 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>3.2.5.RELEASE</version> </dependency> <!-- xml --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-oxm</artifactId> <version>3.2.5.RELEASE</version> </dependency> <dependency> <groupId>com.thoughtworks.xstream</groupId> <artifactId>xstream</artifactId> <version>1.4.7</version> </dependency> <!-- 加入fileupload依赖包 --> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.1</version> </dependency> <!-- jackson --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.2.3</version> </dependency> <!-- bean validator --> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-validator</artifactId> <version>4.3.2.Final</version> </dependency> <!-- alibaba json --> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.16</version> </dependency> </dependencies> <build> <finalName>SpringMVC</finalName> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <configuration> <target>1.7</target> <resource>1.7</resource> <encoding>${project.build.sourceEncoding}</encoding> </configuration> </plugin> <!-- 配置maven集成jetty和tomcat插件 --> <plugin> <groupId>org.mortbay.jetty</groupId> <artifactId>jetty-maven-plugin</artifactId> <version>8.1.9.v20130131</version> <configuration> <webAppConfig> <contextPath>/${project.build.finalName}</contextPath> </webAppConfig> <scanIntervalSeconds>5</scanIntervalSeconds> <!-- 设置端口号为8095默认为8080 --> <connectors> <connector implementation="org.eclipse.jetty.server.nio.SelectChannelConnector"> <port>8095</port> <maxIdleTime>60000</maxIdleTime> </connector> </connectors> <!-- 设置停止启动端口号9966 --> <stopKey>shutdown</stopKey> <stopPort>9966</stopPort> </configuration> </plugin> <plugin> <groupId>org.apache.tomcat.maven</groupId> <artifactId>tomcat7-maven-plugin</artifactId> <version>2.2</version> <configuration> <path>/${project.build.finalName}</path> <port>8080</port> <uriEncoding>UTF-8</uriEncoding> <finalName>${project.build.finalName}</finalName> <server>tomcat7</server> </configuration> </plugin> </plugins> </build> </project>
web.xml文件:
<?xml version="1.0" encoding="UTF-8"?> <web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"> <display-name>SpringMVC</display-name> <!--字符过滤器及编码utf-8--> <filter> <filter-name>characterEncodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> <init-param> <param-name>forceEncoding</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>characterEncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <servlet> <servlet-name>spring</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!-- <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:/spring-servlet.xml</param-value> </init-param> --> <!-- 不写,使用默认值:/WEB-INF/[servlet-name]-servlet.xml --> <!-- <param-value>/WEB-INF/classes/spring-servlet.xml</param-value> --> <!-- <param-value>classpath:/spring-servlet.xml</param-value> --> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>spring</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app>
我们在学SpringMVC的时候都知道,它需要一个spring配置文件,用来初始化SpringMVC子容器,既可以指定也可以不指定文件位置。
如果不指定,如上面所配置,那么org.springframework.web.servlet.DispatcherServlet会从默认位置(/WEB-INF/[servlet-name]-servlet.xml)加载,也就是/WEB-INF/spring-servlet.xml。如下截图:
如果需要指定呢,比如需要把spring配置文件放在src/main/resources中呢,如下图:
则配置方式如下:
<servlet> <servlet-name>spring</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:/spring-mvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet>
springmvc的请求路径url后缀:
方式一:
<servlet-mapping> <servlet-name>spring</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping>
方式二:
<servlet-mapping> <servlet-name>dispatcher</servlet-name> <url-pattern>*.html</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>dispatcher</servlet-name> <url-pattern>*.action</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>dispatcher</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping>
它们有什么区别呢,以及在开发中注意的地方:
方式一:任意路径都会被映射,能够被org.springframework.web.servlet.DispatcherServlet处理
方式二:只有指定的路径才会被处理,如html、action、do结尾
两种方式其实任意一种都可以,但是使用方式二静态资源文件(js、css、images、plugins、fonts)就不能放在WEB-INF里面,只能放在webapp里面,因为映射里没有包含静态文件的路径。方式一就没问题,但是需要在springmvc配置文件中做静态资源映射。
方式一静态资源文件存放如下截图:
方式二静态资源文件存放如下截图:
方式一需要在springmvc配置文件中做静态资源映射如下:
spring-servlet.xml配置文件
<?xml version="1.0" encoding="UTF-8" standalone="no"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" 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 http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"> <!-- 启动注解驱动的Spring MVC功能,注册请求url和注解POJO类方法的映射--><!-- <mvc:annotation-driven /> --> <mvc:annotation-driven validator="validator" conversion-service="conversion-service" /> <bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean"> <property name="providerClass" value="org.hibernate.validator.HibernateValidator"/> <!--不设置则默认为classpath下的 ValidationMessages.properties --> <property name="validationMessageSource" ref="validatemessageSource"/> </bean> <bean id="conversion-service" class="org.springframework.format.support.FormattingConversionServiceFactoryBean" /> <bean id="validatemessageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource"> <property name="basename" value="classpath:message/validatemessages"/> <property name="fileEncodings" value="utf-8"/> <property name="cacheSeconds" value="120"/> </bean> <!-- 如果当前请求为"/"时,则转发到“/helloworld/index" --> <mvc:view-controller path="/" view-name="forward:/helloworld/index"/> <!-- 静态资源映射 --> <mvc:resources mapping="/js/**" location="/WEB-INF/js/" /> <mvc:resources mapping="/css/**" location="/WEB-INF/css/" /> <mvc:resources mapping="/fonts/**" location="/WEB-INF/fonts/" /> <mvc:resources mapping="/plugins/**" location="/WEB-INF/plugins/" /> <mvc:resources mapping="images/**" location="/WEB-INF/images/" /> <!-- 当上面要访问的静态资源不包括在上面的配置中时,则根据此配置来访问 --> <mvc:default-servlet-handler/> <!-- 开启controller注解支持 --> <!-- use-default-filters="false" 只扫描指定的注解 --> <context:component-scan base-package="com.somnus.controller" use-default-filters="false"> <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/> </context:component-scan> <!-- 视图解析器 --> <!-- <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/> <property name="contentType" value="text/html"/> <property name="prefix" value="/WEB-INF/views/"/> <property name="suffix" value=".jsp"/> </bean> --> <!-- 视图解析器 --> <bean id="viewResolver" class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver"> <property name="mediaTypes"> <map> <entry key="html" value="text/html" /> <entry key="json" value="application/json" /> <entry key="xml" value="application/xml" /> </map> </property> <property name="viewResolvers"> <list> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/views/" /> <property name="suffix" value=".jsp" /> </bean> </list> </property> <property name="defaultViews"> <list> <!-- 不加配置返回 {"account":{"username":"admin","password":"123456"}} --> <!-- 加配置返回 {"username":"admin","password":"123456"}--> <!--视图解析器解析json数据--> <bean class="org.springframework.web.servlet.view.json.MappingJackson2JsonView"> <property name="extractValueFromSingleKeyModel" value="true" /> </bean> <!--视图解析器解析xml数据--> <bean class="org.springframework.web.servlet.view.xml.MarshallingView"> <property name="marshaller"> <bean class="org.springframework.oxm.xstream.XStreamMarshaller"/> </property> </bean> </list> </property> </bean> <!-- 支持上传文件 --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!-- 设置上传文件的最大尺寸为1MB --> <property name="maxUploadSize"> <value>1048576</value> </property> <property name="defaultEncoding"> <value>UTF-8</value> </property> </bean> <mvc:interceptors> <mvc:interceptor> <mvc:mapping path="/helloworld/*"/> <!-- 如果不定义 mvc:mapping path 将拦截所有的URL请求 --> <bean class="com.somnus.interceptor.AuthInterceptor"></bean> </mvc:interceptor> <!-- 国际化操作拦截器 如果采用基于(请求/Session/Cookie)则必需配置 --> <bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor" /> </mvc:interceptors> <!-- ################################################################ --> <!-- 注意:当spring-servlet.xml中使用<mvc:annotation-driven/>时, --> <!-- 如果是3.1之前已经默认注入AnnotationMethodHandlerAdapter, --> <!-- 3.1之后默认注入RequestMappingHandlerAdapter只需加上相关jackson的jar包即可! --> <!-- ################################################################ --> <!-- <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"> <property name="messageConverters"> <list> <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"/> </list> </property> </bean> --> </beans>
开启注解映射支持,它是为了简化配置的缩写形式,它相当于以下2个配置:
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"/> <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"/>
由于我们在web.xml文件里面配置的是拦截所有的请求到该servlet,所以我们在这里要对静态资源文件映射作一下配置,否则请求这些资源文件会返回
404:
<!-- 静态资源映射 --> <mvc:resources mapping="/js/**" location="/WEB-INF/js/" /> <mvc:resources mapping="/css/**" location="/WEB-INF/css/" /> <mvc:resources mapping="/fonts/**" location="/WEB-INF/fonts/" /> <mvc:resources mapping="/plugins/**" location="/WEB-INF/plugins/" /> <mvc:resources mapping="images/**" location="/WEB-INF/images/" /> <!-- 当上面要访问的静态资源不包括在上面的配置中时,则根据此配置来访问 --> <mvc:default-servlet-handler/>
开启Controller注解支持,并配置只扫描指定包下面的Controller:
<context:component-scan base-package="com.demo.web.controllers" use-default-filters="false"> <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/> </context:component-scan>
配置视图解析器,并指定视图所在的文件夹:
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/> <property name="contentType" value="text/html"/> <property name="prefix" value="/WEB-INF/views/"/> <property name="suffix" value=".jsp"/> </bean>
springmvc数据绑定注解:
1.@RequestParam,绑定单个请求数据,可以是URL中的数据,表单提交的数据或上传的文件;
(经常使用如在请求的url中带参数url:basePath+’/SpringMVC/databand/queryByName.do?name=’+name
后台接受参数方法:public String queryByName(@RequestParam(‘name’) String name){}
)
2.@PathVariable,绑定URL模板变量值;
3.@CookieValue,绑定Cookie数据;
4.@RequestHeader,绑定请求头数据;
5.@ModelAttribute,绑定数据到Model;
6.@SessionAttributes,绑定数据到Session;
7.@RequestBody,用来处理Content-Type不是application/x-www-form-urlencoded编码的内容,例如application/json, application/xml等;
8.@RequestPart,绑定“multipart/data”数据,并可以根据数据类型进项对象转换;
备注:
[email protected],[email protected]
@RequestParam(value=”username”, required=true, defaultValue=”AAA”)。
value表示要绑定请求中参数的名字;
required表示请求中是否必须有这个参数,默认为true这是如果请求中没有要绑定的参数则返回404;
defaultValue表示如果请求中指定的参数值为空时的默认值;
要绑定的参数如果是值类型必须要有值否则抛异常,如果是引用类型则默认为null(Boolean除外,默认为false);
[email protected] [email protected]如下:
@RequestMapping(value="/modelautobind", method = {RequestMethod.POST}) public String modelAutoBind(HttpServletRequest request, Model model, AccountModel accountModel){ model.addAttribute("accountmodel", accountModel); return "modelautobindresult"; }
[email protected] 我们可以更简单的讲数据添加到Model中,把上面的代码修改为:
@RequestMapping(value="/modelautobind", method = {RequestMethod.POST}) public String modelAutoBind(HttpServletRequest request, @ModelAttribute("accountmodel") AccountModel accountModel){ return "modelautobindresult"; }
[email protected],[email protected]ncoded请求中的内容转换为指定的对象,如请求类型content-type为“application/json”,[email protected],@[email protected],他把指定的对象转换为合适的内容(请求头为Accept:application/json 则返回json数据)并返回。
注意Spring默认解析json用的是Jackson,让实体类继承Serializable接口并添加一个空的构造函数(为了Jackson做转换)。
原创文章,作者:Maggie-Hunter,如若转载,请注明出处:https://blog.ytso.com/11197.html