spingmvc淺嘗之一:小試牛刀

來源:互聯網
上載者:User

標籤:springmvc   架構   

      Spring MVC是當前最優秀的MVC架構,自從Spring 2.5版本發布後,由於支援註解配置,易用性有了大幅度的提高。Spring 3.0更加完善,實現了對Struts 2的超越。現在越來越多的Team Dev選擇了Spring MVC。

 

       Struts2也是非常優秀的MVC構架,優點非常多比如良好的結構,攔截器的思想,豐富的功能。但這裡想說的是缺點,Struts2由於採用了值棧、OGNL運算式、struts2標籤庫等,會導致應用的效能下降,應避免使用這些功能。而Struts2的多層攔截器、多執行個體action效能都很好。


     Spring的官方下載網址是:http://www.springsource.org/download

        Eclipse   http://yunpan.cn/Q7ws623WhxEZg  提取碼 ca2c   

    小馬哥說過,最好的學習方法就是活學活用,所以先配置一個小項目感受一下。

     1)建立一個web project,這裡我用的是Eclipse。

    

     匯入相關包

   

     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">    <!-- web.xml 的載入順序是:context-param - listener - filter - servlet ,而同個類型之間的實際程式調用的時候的順序是根據對應的 mapping 的順序進行調用的 -->         <listener>  <listener-class>org.springframework.web.context.ContextLoaderListener </listener-class>  </listener>              <!-- 使用ContextLoaderListener配置時,需要告訴它Spring設定檔的位置 --> <!-- 如果沒有指定,上下文載入器會在/WEB-INF/applicationContext.xml中找Spring設定檔 --> <!-- 我們可以通過在Servlet上下文中設定contextConfigLocation參數,來為上下文載入器指定一個或多個Spring設定檔 --> <!-- 注意:contextConfigLocation參數是一個用逗號分隔的路徑列表,其路徑是相對於Web系統的根路徑的 --><!-- SpringMVC的前端控制器 -->    <!-- 當DispatcherServlet載入後,它將從一個XML檔案中載入Spring的應用上下文,該XML檔案的名字取決於<servlet-name> -->  <!-- 這裡DispatcherServlet將試圖從一個叫做springmvc-servlet.xml的檔案中載入應用上下文,其預設位於WEB-INF目錄下 -->     <!-- 所以ContextLoaderListener參數值也可寫成<param-value>classpath:applicationContext-*.xml</param-value> -->  <servlet>          <servlet-name>springMVC</servlet-name>          <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>       <load-on-startup>1</load-on-startup>   </servlet>    <servlet-mapping>             <servlet-name>springMVC</servlet-name>              <url-pattern>/</url-pattern>     </servlet-mapping>  <!-- 解決編碼問題-->  <filter>             <filter-name>encodingFilter</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> <pre>        <param-name>forceEncoding</param-name>            <param-value>true</param-value>         </init-param>    </filter>    <!-- encoding filter for jsp page -->    <filter-mapping>             <filter-name>encodingFilter</filter-name>          <url-pattern>/*</url-pattern>    </filter-mapping> <!-- 通過錯誤碼來配置error-page ,配置了當系統發生404錯誤時,跳轉到錯誤處理頁面NotFound.--><error-page>     <error-code>404</error-code>     <location>/page404.html</location> </error-page> <!--  通過異常的類型配置error-page ,配置了當系統發生java.lang.NullException(即null 指標異常)時,跳轉到錯誤處理頁面error.jsp  --><error-page>     <exception-type>java.lang.NullPointerException</exception-type>     <location>/WEB-INF/jsp/error.jsp</location> </error-page></web-app>




其次是springmvc-servlet.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-3.1.xsd              http://www.springframework.org/schema/context              http://www.springframework.org/schema/context/spring-context-3.1.xsd             http://www.springframework.org/schema/mvc              http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd">        <!-- 啟動掃描所有的controller -->    <context:component-scan base-package="com.test.action"/>        <!--  主要作用於@Controller,啟用該模式            下面是一種簡寫形式,完全可以手動設定替代這種簡寫形式;     它會自動註冊DefaultAnnotationHandlerMapping與AnnotationMethodHandlerAdapter 兩個bean,       是spring MVC為@Controllers分發請求所必須的     --><!--     <mvc:annotation-driven/> -->    <mvc:annotation-driven>        <mvc:message-converters register-defaults="true">            <bean class="org.springframework.http.converter.StringHttpMessageConverter">                <constructor-arg value="UTF-8" />            </bean>        </mvc:message-converters>    </mvc:annotation-driven>          <!-- 配置js,css等靜態檔案直接映射到對應的檔案夾,不被DispatcherServlet處理 -->    <mvc:resources location="/WEB-INF/resources/**" mapping="/resources"/>    <mvc:resources mapping="/javascript/**" location="/static_resources/javascript/"/>      <mvc:resources mapping="/styles/**" location="/static/css/"/>      <mvc:resources mapping="/images/**" location="/static/images/"/>         <!-- 配置頁面訪問地址www.xxx.com/about返回的靜態html檔案 -->    <mvc:resources mapping="/about/**" location="/WEB-INF/html/"/>    <!-- 走servlet的預設配置,先走預設的web.xml配置的servlet,沒有的話才找對應controller -->    <mvc:default-servlet-handler />        <!-- jsp頁面解析器,當Controller返回XXX字串時,先通過攔截器,然後該類就會在jsp/目錄下,尋找XXX.jsp檔案-->    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">    <property name="prefix" value="/WEB-INF/jsp/"></property>    <property name="suffix" value=".jsp"></property>    </bean>        <bean id="multipartResolver"class="org.springframework.web.multipart.commons.CommonsMultipartResolver"><property name="defaultEncoding"><value>UTF-8</value></property><property name="maxUploadSize"><value>32505856</value><!-- 上傳檔案大小限制為31M,31*1024*1024 --></property><property name="maxInMemorySize"><value>4096</value></property></bean>    </beans>
   3)核心控制器 UserController
package com.tgb.web.controller.annotation;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;import org.springframework.web.servlet.ModelAndView;@Controllerpublic class UserController {@RequestMapping(value="/user/addUser",method=RequestMethod.POST)public ModelAndView addUser(){String result = "this is addUser-----";return new ModelAndView("/jquery","result",result);}@RequestMapping(value="/user/delUser",method=RequestMethod.GET)public ModelAndView delUser(){String result = "this is delUser";return new ModelAndView("/jquery","result",result);}@RequestMapping(value="/user/toUser",method=RequestMethod.GET)public ModelAndView toUser(){return new ModelAndView("/jquery");}<ol class="dp-j" start="1"><li class="alt"><span><span class="comment">        //ModelAndView類在SpringMVC中是一個很重要的概念      //控制器執行方法都必須返回一個ModelAndView,ModelAndView對象儲存了視圖以及視圖顯示的模型資料       //第一個參數:視圖組件的邏輯名稱。這裡視圖的邏輯名稱是userlist,視圖解析器會使用該名稱尋找實際的View對象//第二個參數:傳遞給視圖的,模型對象的名稱</span><span>  </span></span></li><li class="alt">//第三個參數:傳遞給視圖的,模型對象的值   }

jsp頁面

<%@ page language="java" contentType="text/html; charset=UTF-8"    pageEncoding="UTF-8"%><%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><script type="text/javascript" src="../js/jquery-1.7.1.min.js"></script><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>Insert title here</title><!-- <script type="text/javascript">$(document).ready(function(){alert(11);});</script> --></head><body><h>jquery請求</h><form action="/springmvc01/user/addUser" method="post"><input type="submit" value="post request" ></form><br><div>${result }</div></body></html>
四、配置tomcat 啟動,並訪問localhost

http://localhost:8080/springmvc01/user/addUser



spingmvc淺嘗之一:小試牛刀

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.