1. 程式人生 > >SpringMvc使用以及ssm整合

SpringMvc使用以及ssm整合

SpringMvc框架使用

  • 導包
  • 配置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> <!--&lt;!&ndash;處理器對映器&ndash;&gt;--> <!--<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"></bean>-->
<!--&lt;!&ndash;處理器引射器&ndash;&gt;--> <!--<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> <!--註解驅動--> <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>


    <!--&lt;!&ndash;處理器對映器&ndash;&gt;-->
    <!--<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"></bean>-->

    <!--&lt;!&ndash;處理器引射器&ndash;&gt;-->
    <!--<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"></bean>-->


    <!--註解驅動-->
    <mvc:annotation-driven/>
</beans>

實現一個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;
    }
}

引數繫結

//直接方法上寫提交上來的引數名字可以直接獲得
  @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;
    }

在類上處理對映

@RequestMapping(value = "/item")
public class ItemController {
//多個url對映到同一個方法上
@RequestMapping(value ={ "/paramer.action"," "/paramexxxr.action""})
    public ModelAndView getParamer(){

    }
}

自定義引數繫結

如果提交了一個date為2017:12-02 15_22-22,springmvc沒辦法把字串轉換成日期型別。所以需要自定義引數繫結。

   @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;
    }
}
<!--註解驅動-->
    <mvc:annotation-driven conversion-service="formattingConversionService"/>
     <!--配置Conveter轉換器 轉換日期-->
    <bean id="formattingConversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
        <!--配置多個轉換器-->
        <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代表轉發的地址
return "redirect:path";//path代表重定向的地址

}
  • Void(返回這種結果的時候可以在Controller方法的形參中定義HTTPServletRequest和HTTPServletResponse物件進行請求的接收和響應)

異常處理器

當發生異常了,捕獲到異常資訊

public class CustomExceptionResolver implements HandlerExceptionResolver {
    @Override
    public ModelAndView resolveException(javax.servlet.http.HttpServletRequest httpServletRequest,
                                         javax.servlet.http.HttpServletResponse httpServletResponse,
                                         Object o,
                                         Exception e) {
//        發生異常的地方sevice 方法
        //可以記錄到日誌
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("error","發生錯誤");
        modelAndView.setViewName("error");

        return modelAndView;
    }
}

在springmvc.xml中註冊

   <!--SpringMvc的異常處理器-->
    <bean class="com.fmt.springmvc.exception.CustomExceptionResolver"/>

訪問進入異常介面,在上方能捕獲到

@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中配置

 <!--上傳圖片的實現類-->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!--上傳圖片的大小 單位是B-->
        <property name="maxUploadSize" value="500000"/>
    </bean>

json互動

客戶端提交json資料,伺服器返回json資料

 @RequestMapping(value = "/json.action")
    @ResponseBody
    //客戶端提交json資料,自動解析成User
    public User json(@RequestBody  User user){
         return user;
    }

攔截器

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 流程

這裡寫圖片描述

架構流程

⦁ 使用者傳送請求至前端控制器DispatcherServlet
⦁ DispatcherServlet收到請求呼叫HandlerMapping處理器對映器。
⦁ 處理器對映器根據請求url找到具體的處理器,生成處理器物件及處理器攔截器(如果有則生成)一併返回給DispatcherServlet。
⦁ DispatcherServlet通過HandlerAdapter處理器介面卡呼叫處理器
⦁ 執行處理器(Controller,也叫後端控制器)。
⦁ Controller執行完成返回ModelAndView
⦁ HandlerAdapter將controller執行結果ModelAndView返回給DispatcherServlet
⦁ DispatcherServlet將ModelAndView傳給ViewReslover檢視解析器
⦁ ViewReslover解析後返回具體View
⦁ DispatcherServlet對View進行渲染檢視(即將模型資料填充至檢視中)。
⦁ DispatcherServlet響應使用者

處理器對映器、處理器介面卡、檢視解析器稱為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監聽器 -->
    <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>
      <!--預設找/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結尾的請求 肯定能使用
          3./ 攔截所有(不包括jsp)(包含 .js .png .css)強烈建議使用
        -->
        <url-pattern>*.action</url-pattern>
    </servlet-mapping>

</web-app>

springmvc與struts2不同

⦁ springmvc的入口是一個servlet即前端控制器,而struts2入口是一個filter過濾器。
⦁ springmvc是基於方法開發(一個url對應一個方法),請求引數傳遞到方法的形參,可以設計為單例或多例(建議單例),struts2是基於類開發,傳遞引數是通過類的屬性,只能設計為多例。
⦁ Struts採用值棧儲存請求和響應的資料,通過OGNL存取資料, springmvc通過引數解析器是將request請求內容解析,並給方法形參賦值,將資料和檢視封裝成ModelAndView物件,最後又將ModelAndView中的模型資料通過request域傳輸到頁面。Jsp檢視解析器預設使用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" />



    <!-- 配置 資料來源 -->
    <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">
        <!-- 設定MyBatis核心配置檔案 -->
        <property name="configLocation" value="classpath:mybatis/sqlMapConfig.xml" />
        <!-- 設定資料來源 -->
        <property name="dataSource" ref="dataSource" />
    </bean>

    <!-- 配置Mapper掃描 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!-- 設定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" />

    <!-- 配置註解驅動 -->
    <mvc:annotation-driven />

    <!-- 對靜態資源放行  -->
    <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>

    <!-- 配置監聽器載入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什麼時候啟動,引數必須為整數 -->
        <!-- 如果為0或者大於0,則springMVC隨著容器啟動而啟動 -->
        <!-- 如果小於0,則在第一次請求進來的時候啟動 -->
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>ssm</servlet-name>
        <!-- 所有的請求都進入springMVC -->
        <url-pattern>/</url-pattern>
    </servlet-mapping>


</web-app>