SpringMvc框架使用
- 導(dǎo)包
- 配置web.xml文件
<?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:p="http://www.springframework.org/schema/p"
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-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/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">
<!--掃描@Controler @Service-->
<context:component-scan base-package="com.fmt.springmvc"></context:component-scan>
<!--<!–處理器映射器–>-->
<!--<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"></bean>-->
<!--<!–處理器引射器–>-->
<!--<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"></bean>-->
<!--視圖解析器-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
<!--注解驅(qū)動-->
<mvc:annotation-driven/>
</beans>
配置springmvc.xml
<?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:p="http://www.springframework.org/schema/p"
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-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/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">
<!--掃描@Controler @Service-->
<context:component-scan base-package="com.fmt.springmvc"></context:component-scan>
<!--<!–處理器映射器–>-->
<!--<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"></bean>-->
<!--<!–處理器引射器–>-->
<!--<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"></bean>-->
<!--注解驅(qū)動-->
<mvc:annotation-driven/>
</beans>
實現(xiàn)一個Controller
@Controller
public class ItemController {
@RequestMapping(value = "/item/itemlist.action",method = {RequestMethod.POST,RequestMethod.GET})
public ModelAndView itemList(){
ModelAndView mav=new ModelAndView();
//mav.setViewName("/WEB-INF/jsp/itemList.jsp");
//配置了視圖解析器后
mav.setViewName("itemList");
return mav;
}
}
訪問http://localhost:8080/item/itemlist.action
參數(shù)綁定
//直接方法上寫提交上來的參數(shù)名字可以直接獲得
@RequestMapping(value = "/item/paramer.action")
public ModelAndView getParamer(@RequestParam(value = "age",required = false,defaultValue = "1") int age,Integer id, String name){
System.out.println(id);
System.out.println(name);
List<Items> itemselect = itemService.getItemselect();
ModelAndView mav=new ModelAndView();
mav.setViewName("itemList");
return mav;
}
對象綁定
@RequestMapping(value = "/item/user.action")
public ModelAndView getUser(User user){
System.out.println(user);
ModelAndView mav=new ModelAndView();
mav.setViewName("itemList");
return mav;
}
//http://localhost:8080/item/user.action?age=12&name=xiaohon(自動封裝一個User)
在類上處理映射
@RequestMapping(value = "/item")
public class ItemController {
//多個url映射到同一個方法上
@RequestMapping(value ={ "/paramer.action"," "/paramexxxr.action""})
public ModelAndView getParamer(){
}
}
自定義參數(shù)綁定
如果提交了一個date為2017:12-02 15_22-22鲜侥,springmvc沒辦法把字符串轉(zhuǎn)換成日期類型蛛砰。所以需要自定義參數(shù)綁定。
@RequestMapping(value = "/item/user.action")
public ModelAndView getUser(User user,Date date){
System.out.println(user);
ModelAndView mav=new ModelAndView();
mav.setViewName("itemList");
return mav;
}
public class DateConver implements Converter<String,Date>{
@Override
public Date convert(String s) {
try {
if (null!=s){
DateFormat format=new SimpleDateFormat("yyyy:MM-dd HH_mm-ss");
return format.parse(s);
}
}catch (Exception e){
}
return null;
}
}
<!--注解驅(qū)動-->
<mvc:annotation-driven conversion-service="formattingConversionService"/>
<!--配置Conveter轉(zhuǎn)換器 轉(zhuǎn)換日期-->
<bean id="formattingConversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
<!--配置多個轉(zhuǎn)換器-->
<property name="converters">
<set>
<bean class="com.fmt.springmvc.conver.DateConver"></bean>
</set>
</property>
</bean>
PathVariable
@RequestMapping(value ="/itemEdit/{id}.action")
public void test(@PathVariable Integer id){
}
Controller的返回
- ModelAndView
- String
public String testController(Model model){
//return "forward:path";//path代表轉(zhuǎn)發(fā)的地址
return "redirect:path";//path代表重定向的地址
}
- Void(返回這種結(jié)果的時候可以在Controller方法的形參中定義HTTPServletRequest和HTTPServletResponse對象進(jìn)行請求的接收和響應(yīng))
異常處理器
當(dāng)發(fā)生異常了,捕獲到異常信息
public class CustomExceptionResolver implements HandlerExceptionResolver {
@Override
public ModelAndView resolveException(javax.servlet.http.HttpServletRequest httpServletRequest,
javax.servlet.http.HttpServletResponse httpServletResponse,
Object o,
Exception e) {
// 發(fā)生異常的地方sevice 方法
//可以記錄到日志
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("error","發(fā)生錯誤");
modelAndView.setViewName("error");
return modelAndView;
}
}
在springmvc.xml中注冊
<!--SpringMvc的異常處理器-->
<bean class="com.fmt.springmvc.exception.CustomExceptionResolver"/>
訪問進(jìn)入異常界面歉摧,在上方能捕獲到
@RequestMapping(value = "/item/itemlist.action",method = {RequestMethod.POST,RequestMethod.GET})
public ModelAndView itemList(){
List<Items> itemselect = itemService.getItemselect();
ModelAndView mav=new ModelAndView();
mav.setViewName("itemList");
int i=1/0;
return mav;
}
圖片上傳
@RequestMapping(value = "update.action")
public void file(MultipartFile file) throws IOException {
file.transferTo(new File("D:\\"));
}
在springmvc中配置
<!--上傳圖片的實現(xiàn)類-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!--上傳圖片的大小 單位是B-->
<property name="maxUploadSize" value="500000"/>
</bean>
json交互
客戶端提交json數(shù)據(jù),服務(wù)器返回json數(shù)據(jù)
@RequestMapping(value = "/json.action")
@ResponseBody
//客戶端提交json數(shù)據(jù)蜕衡,自動解析成User
public User json(@RequestBody User user){
return user;
}
如果提示415錯誤的話參考下面文章
http://blog.csdn.net/tiantiandjava/article/details/46125141
攔截器
springmvc.xml配置
<!--SpringMvc的攔截器-->
<mvc:interceptors>
<!--多個攔截器-->
<mvc:interceptor>
<!--/aaa/bbb-->
<mvc:mapping path="/**"/>
<!--自定義攔截器類-->
<bean class="com.fmt.springmvc.interceptor.interceptor1"></bean>
</mvc:interceptor>
<mvc:interceptor>
<!--/aaa/bbb-->
<mvc:mapping path="/**"/>
<!--自定義攔截器類-->
<bean class="com.fmt.springmvc.interceptor.interceptor2"></bean>
</mvc:interceptor>
</mvc:interceptors>
public class interceptor1 implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
System.out.println("方法前1");
//是否攔截
return false;
}
@Override
public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
System.out.println("方法后1");
}
@Override
public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
System.out.println("頁面渲染后1");
}
}
SpringMvc 流程
架構(gòu)流程
? 用戶發(fā)送請求至前端控制器DispatcherServlet
? DispatcherServlet收到請求調(diào)用HandlerMapping處理器映射器李滴。
? 處理器映射器根據(jù)請求url找到具體的處理器,生成處理器對象及處理器攔截器(如果有則生成)一并返回給DispatcherServlet测摔。
? DispatcherServlet通過HandlerAdapter處理器適配器調(diào)用處理器
? 執(zhí)行處理器(Controller置济,也叫后端控制器)。
? Controller執(zhí)行完成返回ModelAndView
? HandlerAdapter將controller執(zhí)行結(jié)果ModelAndView返回給DispatcherServlet
? DispatcherServlet將ModelAndView傳給ViewReslover視圖解析器
? ViewReslover解析后返回具體View
? DispatcherServlet對View進(jìn)行渲染視圖(即將模型數(shù)據(jù)填充至視圖中)锋八。
? DispatcherServlet響應(yīng)用戶
處理器映射器浙于、處理器適配器、視圖解析器稱為springmvc的三大組件挟纱。
整合mybatis
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<!-- Spring監(jiān)聽器 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<!-- 處理POST提交亂碼問題 -->
<filter>
<filter-name>encoding</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>
</filter>
<filter-mapping>
<filter-name>encoding</filter-name>
<url-pattern>*.action</url-pattern>
</filter-mapping>
<!--前端控制器-->
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!--默認(rèn)找/WEB-INF/[servlet的名稱]-servlet.xml-->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<!--
1./*攔截所有jsp js png .css全攔截 建議不適用
2.*.action *.do 以do action結(jié)尾的請求 肯定能使用
3./ 攔截所有(不包括jsp)(包含 .js .png .css)強(qiáng)烈建議使用
-->
<url-pattern>*.action</url-pattern>
</servlet-mapping>
</web-app>
springmvc與struts2不同
? springmvc的入口是一個servlet即前端控制器羞酗,而struts2入口是一個filter過濾器。
? springmvc是基于方法開發(fā)(一個url對應(yīng)一個方法)紊服,請求參數(shù)傳遞到方法的形參檀轨,可以設(shè)計為單例或多例(建議單例)胸竞,struts2是基于類開發(fā),傳遞參數(shù)是通過類的屬性参萄,只能設(shè)計為多例卫枝。
? Struts采用值棧存儲請求和響應(yīng)的數(shù)據(jù),通過OGNL存取數(shù)據(jù)讹挎, springmvc通過參數(shù)解析器是將request請求內(nèi)容解析校赤,并給方法形參賦值,將數(shù)據(jù)和視圖封裝成ModelAndView對象筒溃,最后又將ModelAndView中的模型數(shù)據(jù)通過request域傳輸?shù)巾撁媛砝骸sp視圖解析器默認(rèn)使用jstl。
SSM整合
配置sqlMapConfig.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!--別名-->
<typeAliases>
<package name="com.fmt.ssm.pojo"/>
</typeAliases>
</configuration>
配置applicationContext-dao.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:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
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.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/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">
<!-- 配置 讀取properties文件 jdbc.properties -->
<context:property-placeholder location="classpath:jdbc.properties" />
<!-- 配置 數(shù)據(jù)源 -->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="${jdbc.driver}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</bean>
<!-- 配置SqlSessionFactory -->
<bean class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 設(shè)置MyBatis核心配置文件 -->
<property name="configLocation" value="classpath:mybatis/sqlMapConfig.xml" />
<!-- 設(shè)置數(shù)據(jù)源 -->
<property name="dataSource" ref="dataSource" />
</bean>
<!-- 配置Mapper掃描 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- 設(shè)置Mapper掃描包 -->
<property name="basePackage" value="com.fmt.ssm.map" />
</bean>
</beans>
配置applicationContext-service.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:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
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.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/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">
<!-- 配置Service掃描 -->
<context:component-scan base-package="com.fmt.ssm.service" />
</beans>
配置SpringMvc.xml
<?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:p="http://www.springframework.org/schema/p"
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-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/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">
<!-- 配置Controller掃描 -->
<context:component-scan base-package="com.fmt.ssm.controller" />
<context:property-placeholder location="classpath:resource.properties" />
<!-- 配置注解驅(qū)動 -->
<mvc:annotation-driven />
<!-- 對靜態(tài)資源放行 -->
<mvc:resources location="/css/" mapping="/css/**"/>
<mvc:resources location="/js/" mapping="/js/**"/>
<mvc:resources location="/fonts/" mapping="/fonts/**"/>
<!-- 配置視圖解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!-- 前綴 -->
<property name="prefix" value="/WEB-INF/jsp/" />
<!-- 后綴 -->
<property name="suffix" value=".jsp" />
</bean>
</beans>
配置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" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>ssm</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<!-- 配置spring -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring/applicationContext-*.xml</param-value>
</context-param>
<!-- 配置監(jiān)聽器加載spring -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 配置過濾器怜奖,解決post的亂碼問題 -->
<filter>
<filter-name>encoding</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>
</filter>
<filter-mapping>
<filter-name>encoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- 配置SpringMVC -->
<servlet>
<servlet-name>ssm</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring/springmvc.xml</param-value>
</init-param>
<!-- 配置springmvc什么時候啟動积蔚,參數(shù)必須為整數(shù) -->
<!-- 如果為0或者大于0,則springMVC隨著容器啟動而啟動 -->
<!-- 如果小于0烦周,則在第一次請求進(jìn)來的時候啟動 -->
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>ssm</servlet-name>
<!-- 所有的請求都進(jìn)入springMVC -->
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
原文鏈接:http://blog.csdn.net/qq_22329521/article/details/75116264