SpringMVC系列之基本配置


一、概述

  Spring Web MVC是一種基於Java的實現了Web MVC設計模式的請求驅動類型的輕量級Web框架,即使用了MVC架構模式的思想,將web層進行職責解耦,基於請求驅動指的就是使用請求-響應模型。

  1、什么是MVC?

  模型-視圖-控制器(MVC)是一個以設計界面應用程序為基礎的設計模式。它主要通過分離模型、視圖及控制器在應用程序中的角色將業務邏輯從界面中解耦。通常,模型負責封裝應用程序數據在視圖層展示。視圖僅僅只是展示這些數據,不包含任何業務邏輯。控制器負責接收來自用戶的請求,並調用后台服務來處理業務邏輯。處理后,后台業務層可能會返回了一些數據在視圖層展示。控制器收集這些數據及准備模型在視圖層展示。MVC模式的核心思想是將業務邏輯從界面中分離出來,允許它們單獨改變而不會相互影響。

  

  在Spring MVC中,模型通常由POJO對象組成,它在業務層中被處理,在持久層被持久化,視圖通常是用JSP標准標簽庫(JSTL)編寫的JSP模板,控制器部分是由dispatcher servlet負責。

2、Spring MVC架構

  SpringMVC是一個基於請求驅動的Web框架,使用前端控制器模式來進行設計,在根據映射規則分發給相應的頁面控制器進行處理。其請求處理流程如下圖所示:

  

  具體執行步驟如下:

  1、客戶端發出一個HTTP請求,Web應用服務器接收到這個請求,如果匹配DispatcherServlet的請求映射路徑(web.xml中指定),Wen容器就會將該請求轉交給DispatcherServlet處理。

  2、DispatcherServlet接收到這個請求后,將根據請求的信息和HandlerMapping的配置找到處理請求的處理器(Handler)。

  3、得到Handler后,通過HandlerAdapter對Handler進行封裝,再以統一的適配器接口調用Handler。

  4、處理器完成業務邏輯的處理后返回一個ModelAndView給DispatcherServlet,ModelAndView包含了視圖邏輯名和模型數據信息。

  5、DispatcherServlet借由ViewResolver完成邏輯視圖名到真實視圖對象的解析工作。

  6、當得到真實的視圖對象view后,DispatcherServlet就使用這個View對象對ModelAndView中模型數據進行渲染。

  7、客戶端最終得到的響應消息可能是一個普通的HTML頁面,也可能是一個XML或者是JSON串。

二、基本配置(非注解)

  1、新建工程,導入構建SpringMVC工程所需的jar包

  

  2、配置前端控制器

  在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>day_0301_springMVC</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>
  <!-- 前端控制器 -->
  <servlet>
      <servlet-name>springmvc</servlet-name>
      <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
     <!-- contextConfigLocation配置springmvc加載的配置文件(配置處理器映射器、適配器等等) 
         如果不配置contextConfigLocation,默認加載的是/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>
      <!--
          第一種:*.action,訪問以.action結尾由DispatcherServlet進行解析
          第二種:/, 所有訪問的地址都由DispatcherServlet進行解析,對於靜態文件的解析需要配置不讓DispatcherServlet進行解析
       -->
      <url-pattern>*.action</url-pattern>
  </servlet-mapping>
</web-app>

  3、配置處理器映射器

  在classpath下的springmvc.xml中配置處理器映射器

  

<!-- 處理器映射器  ,將bean的name作為URL進行查找,需要在配置Handler時指定beanName(就是URL)-->
    <bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"></bean>

  4、配置處理器適配器

<!-- 處理器適配器,所有的處理器適配器都實現HandlerAdapter接口 -->
    <bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter">
    </bean>

  5、配置視圖解析器

<!-- 配置視圖解析器 
     解析jsp視圖,默認使用jstl標簽
     CLASSPATH下面要有jstl jar包
-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"></bean>

  6、編寫Handler

  需要實現Controller接口,才能由SimpleControllerHandlerAdapter適配器執行。

  先要創建POJO對象:

public class Items
{
    private String name;
    private int price;
    public String getName()
    {
        return name;
    }
    public void setName(String name)
    {
        this.name = name;
    }
    public int getPrice()
    {
        return price;
    }
    public void setPrice(int price)
    {
        this.price = price;
    }
}

  創建Handler:

public class TestController implements Controller
{
    @Override
    public ModelAndView handleRequest(HttpServletRequest request,HttpServletResponse response) throws Exception
    {
        List<Items> itemsList=new ArrayList<Items>();
        Items items1=new Items();
        items1.setName("聯想筆記本");
        items1.setPrice(2500);
        Items items2=new Items();
        items2.setName("三星筆記本");
        items2.setPrice(5000);
        itemsList.add(items1);
        itemsList.add(items2);
        ModelAndView modelAndView=new ModelAndView();
        modelAndView.addObject("itemsList", itemsList);
        modelAndView.setViewName("/WEB-INF/jsp/items/itemsList.jsp");
        return modelAndView;
    }
}

  7、編寫視圖jsp

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
    <head>
        <%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
        <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
        <%@taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
        <title>查詢商品列表</title>
    </head>
    <body>
        <form action="${pageContext.request.contentLength}/item/queryItem.action" method="post">
            查詢條件:
            <table width="100%" border="1">
            <tr>
            <td><input type="submit" value="查詢"/></td>
            </tr>
            </table>
            商品列表:
            <table width="100%" border="1">
                <tr>
                <td>商品名稱</td>
                <td>商品價格</td>
                <td>操作</td>
                </tr>
            <c:forEach items="${itemsList}" var="item">
                <tr>
                    <td>${item.name }</td>
                    <td>${item.price }</td>    
                    <td><a href="${pageContext.request.contextPath}/item/editItem.action?name=${item.name}">修改</a></td>
                </tr>
            </c:forEach>
            </table>
        </form>
    </body>
</html>

  8、配置Handler

<bean name="/queryItems.action" class="com.demo.ssm.controller.TestController"></bean>

  到此,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:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd
        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-4.1.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.1.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd">

    <bean name="/queryItems.action" class="com.demo.ssm.controller.TestController"></bean>
    
    <!-- 處理器適配器,所有的處理器適配器都實現HandlerAdapter接口 -->
    <bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter">
    </bean>
    
    <!-- 處理器映射器  ,將bean的name作為URL進行查找,需要在配置Handler時指定beanName(就是URL)-->
    <bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"></bean>

    <!-- 配置視圖解析器 
        解析jsp視圖,默認使用jstl標簽
        CLASSPATH下面要有jstl jar包
    -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"></bean>
</beans>

  9、部署調式

  訪問的地址:http://localhost:8080/day_0301_springMVC/queryItems.action

  結果如下圖所示:

三、基於注解的映射器和適配器配置

  再基於注解的映射器和適配器配置中,注解Handler的編寫如下:

@Controller
public class TestController2
{
    @RequestMapping("/queryItemsTest")
    public ModelAndView queryItems()
    {
        List<Items> itemsList=new ArrayList<Items>();
        Items items1=new Items();
        items1.setName("聯想筆記本");
        items1.setPrice(2500);
        Items items2=new Items();
        items2.setName("apple");
        items2.setPrice(5000);
        itemsList.add(items1);
        itemsList.add(items2);
        ModelAndView modelAndView=new ModelAndView();
        modelAndView.addObject("itemsList", itemsList);
        modelAndView.setViewName("/WEB-INF/jsp/items/itemsList.jsp");
        return modelAndView;
    }
}

  springmv.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:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd
        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-4.1.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.1.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd">
    <bean class="com.demo.ssm.controller.TestController2"></bean>
    <!-- 注解映射器 -->
    <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"/>
    <!-- 注解適配器 -->
    <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"/>
    <!--使用下面的mvc:annotation-driven可以代替上面的注解映射器和注解適配器-->
    <mvc:annotation-driven></mvc:annotation-driven>
    <!-- <context:component-scan base-package="com.demo.ssm.controller"></context:component-scan> -->
    <!-- 配置視圖解析器 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"></bean>
</beans>

  部署后,訪問地址:http://localhost:8080/day_0301_springMVC/queryItemsTest.action,運行結果同上。

四、工程源代碼

  點擊工程源代碼下載鏈接


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2026 CODEPRJ.COM