1、新建web項目,並在web.xml加入spring mvc的servlet
<!-- spring mvc容器和servlet的定義 --> <servlet> <servlet-name>springMVC</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!-- 這里的參數如果不配置,則默認查找web-inf下的{servlet-name}-servlet.xml文件 --> <init-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/springMVC.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>
2、加入spring mvc的依賴jar包
備注:我這里除了spring的jar包外還添加了一些其他的功能(quartz、JSR303的hibernate實現、c3p0連接池、DB2驅動、spring json的支持(jackson)),這里並未完全加入spring的包,可根據項目的需要增減jar.
3、配置spring mvc的配置文件。
<?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:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:task="http://www.springframework.org/schema/task" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.0.xsd"> <!-- Spring MVC配置 --> <context:annotation-config /> <!--掃描注解 --> <context:component-scan base-package="com.tf" /> <!--默認的mvc注解映射的支持 --> <mvc:annotation-driven/> <!-- 支持異步方法執行 --> <task:annotation-driven /> <!-- 視圖解析器和json解析器 --> <bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver"> <property name="mediaTypes"> <map> <entry key="html" value="text/html"/> <entry key="json" value="application/json"/> </map> </property> <property name="viewResolvers"> <list> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/jsp/" /> <!--可為空,方便實現自已的依據擴展名來選擇視圖解釋類的邏輯 --> <property name="suffix" value=".jsp"/> </bean> </list> </property> <property name="defaultViews"> <list> <bean class="org.springframework.web.servlet.view.json.MappingJackson2JsonView" /> </list> </property> </bean> <!-- 文件上傳解析器 --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!-- one of the properties available; the maximum file size in bytes --> <property name="maxUploadSize" value="-1"/> </bean> <!-- 總錯誤處理 --> <bean id="exceptionResolver" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver"> <property name="defaultErrorView"> <value>/error</value> </property> <property name="defaultStatusCode"> <value>500</value> </property> <property name="warnLogCategory"> <value>org.springframework.web.servlet.handler.SimpleMappingExceptionResolver </value> </property> </bean> <!-- 對靜態資源文件的訪問 --> <mvc:resources mapping="/images/**" location="/images/" cache-period="31556926" /> <mvc:resources mapping="/js/**" location="/js/" cache-period="31556926" /> <mvc:resources mapping="/css/**" location="/css/" cache-period="31556926" /> <!-- 數據庫和事務配置 --> <!-- 加載配置文件 --> <context:property-placeholder location="classpath:jdbc.properties" /> <!-- 定義數據源 --> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close"> <property name="driverClass"> <value>${jdbc.driverClass}</value> </property> <property name="jdbcUrl"> <value>${jdbc.url}</value> </property> <property name="user"> <value>${jdbc.username}</value> </property> <property name="password"> <value>${jdbc.password}</value> </property> <!--連接池中保留的最小連接數。 --> <property name="minPoolSize"> <value>${c3p0.minPoolSize}</value> </property> <!--連接池中保留的最大連接數。Default: 15 --> <property name="maxPoolSize"> <value>${c3p0.maxPoolSize}</value> </property> <!--初始化時獲取的連接數,取值應在minPoolSize與maxPoolSize之間。Default: 3 --> <property name="initialPoolSize"> <value>${c3p0.initialPoolSize}</value> </property> <!--每30秒檢查所有連接池中的空閑連接。Default: 0 --> <property name="idleConnectionTestPeriod"> <value>${c3p0.idleConnectionTestPeriod}</value> </property> </bean> <!-- weblogic推薦使用jndi連接池 --> <!-- <bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean"> <property name="jndiName"> <value>java:comp/env/jdbc/myDatasource</value> </property> </bean> --> <!-- 定義jdbcTemplate --> <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> <property name="dataSource"> <ref bean="dataSource"/> </property> </bean> <bean id="namedParameterJdbcTemplate" class="org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate"> <constructor-arg><ref bean="dataSource"/></constructor-arg> </bean> <!-- 定義事務管理器 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource"> <ref bean="dataSource" /> </property> </bean> <!-- 配置事務特性 ,配置add、delete和update開始的方法,事務傳播特性為required --> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="save*" propagation="REQUIRED" /> <tx:method name="insert*" propagation="REQUIRED" /> <tx:method name="delete*" propagation="REQUIRED" /> <tx:method name="update*" propagation="REQUIRED" /> <tx:method name="login*" propagation="REQUIRED" /> <tx:method name="regist*" propagation="REQUIRED" /> <tx:method name="*" read-only="true" /> </tx:attributes> </tx:advice> <!-- 配置那些類的方法進行事務管理 --> <aop:config> <aop:pointcut id="allManagerMethod" expression="execution (* com.tf.*.service.*.*(..))" /> <aop:advisor advice-ref="txAdvice" pointcut-ref="allManagerMethod" /> </aop:config> </beans>
4、配置log4j
log4j.rootCategory=INFO, stdout , R
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=[TF] %p [%t] %C.%M(%L) | %m%n
log4j.appender.R=org.apache.log4j.DailyRollingFileAppender
log4j.appender.R.File=E:/mylog.log
log4j.appender.R.layout=org.apache.log4j.PatternLayout
log4j.appender.R.Threshold = WARN
log4j.appender.R.layout.ConversionPattern=%d-[TF] %p %t %c - %m%n
#全局異常記錄
log4j.logger.org.springframework.web.servlet.handler.SimpleMappingExceptionResolver=WARN
#項目的異常記錄
log4j.logger.com.tf=ERROR
5、編寫測試代碼
package com.tf.model1.controller; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import javax.validation.Valid; import org.springframework.stereotype.Controller; import org.springframework.validation.BindingResult; import org.springframework.validation.ObjectError; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.context.WebApplicationContext; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import org.springframework.web.servlet.support.RequestContextUtils; import com.tf.model1.bean.User; import com.tf.model1.service.TestService; @Controller //@RequestMapping(value="/test") public class TestRestController { @Resource private TestService testService; //接收get請求 @RequestMapping(value="/test",method=RequestMethod.GET) //可以自動根據名稱映射參數,也可以手動指定 public String test(@RequestParam(value="name",defaultValue="admin")String username,HttpServletRequest request){ //public String test(@RequestParam("name")String username,HttpServletRequest request){ //public String test(String name,HttpServletRequest request){ //獲取到spring的applicationContext對象 WebApplicationContext context = RequestContextUtils.getWebApplicationContext(request); System.out.println("-------------------> name:" +username); return "test"; } //redirect/forward:url方式轉到另一個Action進行連續的處理 @RequestMapping("/redirect") public String testRedirect(){ return "redirect:/index.jsp"; } //重定向並攜帶參數 @RequestMapping("/redirectAttribute") public String testRdirectWithAttribute(RedirectAttributes attributes){ attributes.addAttribute("name", "zhangsan"); return "redirect:/login.jsp"; } //上傳1 @RequestMapping(value = "/upload", method = RequestMethod.POST) public String upload(@RequestParam("name") String name, @RequestParam("file") MultipartFile file,RedirectAttributes attributes){ System.out.println("param:"+name); if(!file.isEmpty()){ System.out.println("upload ok"); } attributes.addAttribute("name", "upload success"); return "redirect:/login.jsp"; } //接收ajax請求 //使用url的表達式動態傳遞參數 //返回json @RequestMapping("/uri/{userId}") //多個url參數可以用多個注解和方法參數來接收 public @ResponseBody Map uriTemplate(@PathVariable String userId){ //也可以這么寫 //public @ResponseBody Map uriTemplate(@PathVariable("userId") String loginUserId){ System.out.println("url的參數為:"+userId); Map<String, String> map = new HashMap<String, String>(); map.put("user", userId); return map; } //測試另外一種json方式 @RequestMapping(value="/nextjson",produces="application/json") //寫在方法上還是返回參數前效果一致 //@ResponseBody public @ResponseBody String testNextJson(){ return "json"; } //調用業務類執行保存操作 @RequestMapping(value="/save",produces="application/json") public @ResponseBody Map<String, String> testSave(){ this.testService.save(); Map<String, String> map = new HashMap<String, String>(); map.put("isOk", "success"); return map; } //spring使用hibernate的valid進行數據校驗 @RequestMapping("/login") public String testValid(@Valid User user, BindingResult result){ if (result.hasErrors()){ List<ObjectError> errorList = result.getAllErrors(); for(ObjectError error : errorList){ System.out.println(error.getDefaultMessage()); } } return "test"; } }
package com.tf.model1.bean; import javax.validation.constraints.Max; import javax.validation.constraints.NotNull; import org.hibernate.validator.constraints.Email; import com.tf.common.db.PK; import com.tf.common.db.Table; /** * @Null 限制只能為null @NotNull 限制必須不為null @AssertFalse 限制必須為false @AssertTrue 限制必須為true @DecimalMax(value) 限制必須為一個不大於指定值的數字 @DecimalMin(value) 限制必須為一個不小於指定值的數字 @Digits(integer,fraction) 限制必須為一個小數,且整數部分的位數不能超過integer,小數部分的位數不能超過fraction @Future 限制必須是一個將來的日期 @Max(value) 限制必須為一個不大於指定值的數字 @Min(value) 限制必須為一個不小於指定值的數字 @Past 限制必須是一個過去的日期 @Pattern(value) 限制必須符合指定的正則表達式 @Size(max,min) 限制字符長度必須在min到max之間 * * @author yzl * */ @Table("T_USER") public class User { @PK private String userId; @NotNull(message="名字不能為空") private String userName; @Max(value=120,message="年齡最大不能查過120") private int age; @Email(message="郵箱格式錯誤") private String email; public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } }
<mvc:annotation-driven />的具體說明:
<mvc:annotation-driven /> 是一種簡寫形式,完全可以手動配置替代這種簡寫形式,簡寫形式可以讓初學都快速應用默認配置方案。
<mvc:annotation-driven /> 會自動注冊DefaultAnnotationHandlerMapping與AnnotationMethodHandlerAdapter 兩個bean,是spring MVC為@Controllers分發請求所必須的。
並提供了:數據綁定支持,@NumberFormatannotation支持,@DateTimeFormat支持,@Valid支持,讀寫XML的支持(JAXB),讀寫JSON的支持(Jackson)。