Spring MVC

基於註解驅動的 Spring MVC 3.0

 

工做機制

 


配置方式

Web.xml

<!--  Spring Context初始化的配置文件 -->html

<context-param>           java

<param-name>contextConfigLocation</param-name>       <param-value>/WEB-INF/classes/spring/*-config.xmlweb

</param-value>ajax

   </context-param>spring

 

<!--  Spring 容器啓動監聽器 -->express

<listener>        restful

<listener-class>session

org.springframework.web.context.ContextLoaderListenermvc

        </listener-class>app

    </listener>

 

<!-- 

Servlet 配置與之對應的要有一個配置文件:

{servletname}-servlet.xml

此例應爲:WEB-INF/flex-servlet.xml

-->

<servlet>

      <servlet-name>flex</servlet-name>

      <servlet-class>

org.springframework.web.servlet.DispatcherServlet

</servlet-class>

      <async-supported>true</async-supported>

         <load-on-startup>2</load-on-startup>

   </servlet>

   <servlet-mapping>

      <servlet-name>flex</servlet-name>

      <url-pattern>/</url-pattern>

   </servlet-mapping>

 

 

{servlet name}-servlet.xml

  <!—

web包中的全部類進行掃描,以完成Bean建立和自動依賴注入的功能

-->

<!--Supporting Spring MVC Infrastructure for RESTful @Controllers -->

      <context:component-scanbase-package="com.dn" use-default-filters="false">

<context:include-filter

expression="org.springframework.stereotype.Controller"

type="annotation"/>

       </context:component-scan>

      

<!—註解驅動方式 -->

      <mvc:annotation-driven/>

     

      <mvc:default-servlet-handler/>

     

<bean id="viewResolver"

class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">

             <propertyname="mediaTypes">

                     <map>

                            <entrykey="amf" value="application/x-amf"/>

                     </map>

              </property>

              <propertyname="defaultViews">

                     <list>

                            <beanclass="org.springframework.flex.http.AmfView" />

                     </list>

              </property>

      </bean>

     

      <beanid="jspViewResolver"

class="org.springframework.web.servlet.view.InternalResourceViewResolver"

       <property name="prefix" value="/"/>

       <property name="suffix" value=".jsp"></property>

           <property name="viewClass" 

              value="org.springframework.web.servlet.view.JstlView"/>

       </bean>

prefix:則爲前綴,也就是目錄的地址, 通常以"WEB-INF/xx"爲主,若爲"/" 則爲全局使用

suffix:則爲後綴,也就是文件名的後綴.使用InternalResourceViewResolver類是隻支持jsp,不支持html等其餘後綴,若是強制加入其餘後綴的話會出現死循環

 


 

基本知識

經常使用註解元素

@Controller

         標註在Bean的類定義處

@RequestMapping

真正讓Bean具有 Spring MVC Controller 功能的是 @RequestMapping 這個註解

@RequestMapping 能夠標註在類定義處,將 Controller 和特定請求關聯起來;

還能夠標註在方法簽名處,以便進一步對請求進行分流

 

   配套的屬性有:

   value 須要跳轉的地址

   method 基於RestFul的跳轉參數,RequestMethod.get  post  put  delete

   params 符合某個參數的時候才調用該方法

   Headers 符合頭信息的時候才調用

 

@SessionAttributes

         將結果放入session

@ModelAttribute

存儲在響應內容ModelMap或者ModelAndView進行保存值傳到前臺,當若是你須要保存值比較少

的時候能夠採用這種方式進行保存值而且保存到前臺顯示

 

在默認狀況下,ModelMap 中的屬性做用域是 request 級別,至關於HttpServletRequest中的request.setAttribute()同樣, JSP 視圖頁面中經過 request.getAttribute(「attribute name」) 或者經過

${ attribute name } EL 表達式訪問模型對象中的屬性對象

 

若是但願在ModelMap 的做用域範圍爲 session,能夠有選擇地指定 ModelMap 中的哪些屬性須要轉存到 session 中,以便下一個請求屬對應的 ModelMap 的屬性列表中還能訪問到這些屬性。這一功能是經過類定義處標註 @SessionAttributes 註解來實現如:

 

@Controller

@RequestMapping("/login.do")

@SessionAttributes("currUser")   

public class BbtForumController {。。。。。}

 

 

@ResponseBody

         標註後  返回String對象的結果爲response內容體,不標註的話  做爲dispatcher url使用

 

@PathVariable

   容許將請求路徑的制定內容當作求情的參數使用

返回類型

請求處理方法入參的可選類型                                                   說明

void                                       此時邏輯視圖名由請求處理方法對應的 URL 肯定,如如下的方法:

@RequestMapping("/welcome.do")

public void welcomeHandler(){

}

對應的邏輯視圖名爲「welcome

 

String                                    此時邏輯視圖名爲返回的字符,如如下的方法:

@RequestMapping(method =RequestMethod.GET)

public StringsetupForm(@RequestParam("ownerId") int ownerId, ModelMap model) {

     Owner owner = this.clinic.loadOwner(ownerId);

     model.addAttribute(owner);

     return "ownerForm";

}

                                              對應的邏輯視圖名爲「ownerForm

 

ModelMap                            和返回類型爲 void 同樣,邏輯視圖名取決於對應請求的 URL

以下面的例子:

@RequestMapping("/vets.do")

public ModelMapvetsHandler() {

     return new ModelMap(this.clinic.getVets());

}

 

對應的邏輯視圖名爲「vets」,返回的 ModelMap 將被做爲請求對應的模型對象,

能夠在 JSP 視圖頁面中訪問到。

ModelAndView                 

返回方式

1 使用無返回方法跳轉,若是使用返回方法進行跳轉的話,則會經過視圖解析器進行以

prefix(前綴)+方法名+suffix(後綴)組成的頁面文件名稱.

 

2 使用一個返回的字符串方法做爲跳轉,使用字符串跳轉的話好處就是在return的時候可

以本身指定返回的名字,JSP組成是prefix(前綴)+返回的字符串+suffix(後綴)

 

3 返回一個ModelAndView類型,使用setViewName方法則能夠跳轉到指定的頁面.

 

路徑匹配形式

         一、單一Controller   對應 單一的請求路徑

                    

二、單一Controller   對應多個請求路徑

 

三、單一Controller  對應多個請求路徑,且路徑內能夠含有參數的形式

Demo code and UseCase

@Controller

@RequestMapping("/login.do")

publicclassSinglePathWithController {}

 

@Controller

@SessionAttributes(types = {UserBean.class,String.class},value={"currentUser","message"})

publicclassAdapterMultiPathController {}

 

@Controller

@RequestMapping(value = "/rest")

publicclassRestWithController {}

無返回

//無返回值  無參數返回的是根據 prefix前綴+@RequestMapping value +suffix

後綴組成

      @RequestMapping("/springmvc/common")

      publicvoidnovoid(HttpServletRequest request) {

         request.setAttribute("message", "novoid方法被調用");

      }

 

http://localhost:8088/framework-web/springmvc/common

返回字符串

一、  做爲視圖路徑方式

 

//根據路徑直接匹配

@RequestMapping("/springmvc/multiReqPath1.do")

    publicString multiReqPath1(HttpServletRequest request){

       request.setAttribute("message", "multiReqPath1方法被調用");

       return"springmvc/common";

    }

http://localhost:8088/framework-web/springmvc/multiReqPath1.do

 

    @RequestMapping("/springmvc/multiReqPath2.do")

    publicString multiReqPath2(HttpServletRequest request){

       request.setAttribute("message", "multiReqPath2方法被調用");

       return"/springmvc/common";

    }

http://localhost:8088/framework-web/springmvc/multiReqPath2.do

 

//根據參數匹配

    @RequestMapping(params = "m=method1",method = RequestMethod.GET)

    publicString method1(){

       return"login/success";

}

 

http://localhost:8088/framework-web/login.do?m=method1&name=test

 

//有參數  參數名和請求url內的變量名一致

    @RequestMapping(params = "m=method2")

    publicString method2(String name,String pwd){

       return name;

}

 

http://localhost:8088/framework-web/login.do?m=method2&name=success

http://localhost:8088/framework-web/login.do?m=method2&name=test

 

//測試下不存在的jsp時的狀況

http://localhost:8088/framework-web/login.do?m=method2&name=testunexist


 

 

 

//有參數參數名和請求url內的變量名不一致

    @RequestMapping(params = "m=method3",method = RequestMethod.GET)

    publicString method3(@RequestParam("loginName")String name,@RequestParam("loginPwd")String pwd,HttpServletRequest request){

       request.setAttribute("message",(name + " " + pwd));

       return"login/"+name;

    }

 

http://localhost:8088/framework-web/login.do?m=method3&loginName=test&loginPwd=123456

 

http://localhost:8088/framework-web/login.do?m=method3&loginName=test&loginPwd=123456789

 

//若是參數名與@RequestParam(參數名) 不一致時會報錯

http://localhost:8088/framework-web/login.do?m=method3&loginName=test&pwd=123456

 

二、  做爲Response內容方式

//無參數

    @ResponseBody

    @RequestMapping(params = "m=method4")

    publicString method4(){

       return"hello,guys";

}

 

http://localhost:8088/framework-web/login.do?m=method4

 

//處理方法入參如何綁定 URL 參數

    @ResponseBody

    @RequestMapping(params = "m=method5",method = RequestMethod.GET)

    publicString method5(String name,String pwd,int delay){

       return"name:"+name+","+"pwd:"+pwd+","+"delay:"+delay;

}

 

http://localhost:8088/framework-web/login.do?m=method5&name=rick&pwd=123&delay=10000

 

@ResponseBody

    @RequestMapping(params = "m=method6",method = RequestMethod.GET)

    publicString method6(@RequestParam("userName")String name,DnTest test){

       return"DnTest:"+test.toString();

    }

http://localhost:8088/framework-web/login.do?m=method6&userName=rick&type=DnType&name=rick&value=rick&id=10000

 

http://localhost:8088/framework-web/login.do?m=method6&userName=rick&type=DnType&name=austin&value=austin&id=10001

 

URL 參數: userName參數將綁定到name  其餘與DnTest類內屬性名稱一致的參數將綁定到test的對應的屬性上,若是參數不全  也不會報錯

返回ModelAndView

@RequestMapping("/springmvc/modelAndView")

    publicModelAndView modelAndView(){

       ModelAndView mav = newModelAndView();

       mav.setViewName("/springmvc/common");

       mav.addObject("message", "modelAndView方法被調用");

       return mav;

    }

 

http://localhost:8088/framework-web/springmvc/modelAndView

返回ModelMap

    @RequestMapping("/springmvc/modelMap")

    publicModelMap modelMap(ModelMap modMap){

       List<String> names = newArrayList<String>();

       names.add("Rick");

       names.add("Austin");

        modMap.put("names", names);

       

        modMap.put("message", "hello guys");

        modMap.put("comment", "hello guys");

       

        return modMap;

    }

http://localhost:8088/framework-web/springmvc/modelMap

 


 

返回ModelMap

@RequestMapping("/springmvc/modelMap")

    publicModelMap modelAndView(ModelMap modMap){

       List<String> names = newArrayList<String>();

       names.add("Rick");

       names.add("Austin");

      

        modMap.put("hello", "hello guys");

        modMap.put("names", names);

        return modMap;

    }

 

http://localhost:8088/framework-web/springmvc/modelMap

@SessionAttribute &ModMap

//註解方式

@Controller

@SessionAttributes(types = {UserBean.class,String.class},value={"currentUser","message"})

publicclassAdapterMultiPathController {}

 

//方法體

@RequestMapping("/springmvc/modelMap2")

    publicModelMap modelMapWithSession(ModelMap modMap,HttpServletRequest request){

       List<String> names = newArrayList<String>();

       names.add("Rick");

       names.add("Austin");

       modMap.put("names",names);

      

        modMap.put("message", "hello guys");

        modMap.put("comment", "hello guys");

       

        UserBean user = newUserBean();

        user.setName("Rick");

        user.setMobile("18938900256");

        user.setTelephone(request.getParameter("userPhone"));

        user.setNumber(request.getParameter("userNumber"));

        modMap.put("currentUser", user);

       

        return modMap;

    }  

//初次請求

http://localhost:8088/framework-web/springmvc/modelMap2

spring mvc & reverse ajax

@ResponseBody

    @RequestMapping(params = "m=method7",method = RequestMethod.GET)

    publicString method7(String name,String pwd,int delay,HttpServletRequest req){

       req.startAsync();

      

       Date startTime = newDate();

       try {

           Thread.currentThread().sleep(delay);

       } catch (InterruptedException e) {

           e.printStackTrace();

       }

       Date entTime = newDate();

      

       return"name:"+name+","+"pwd:"+pwd+","+"delay:"+delay+",startTime:"+

              DateUtils.formatDate(startTime, "yyyy-MM-dd HH:mm:ss:SSS")+",endTime:"+

              DateUtils.formatDate(entTime, "yyyy-MM-dd HH:mm:ss:SSS");

    }

 

http://localhost:8088/framework-web/login.do?m=method7&name=rick&pwd=1234566&delay=10000

 

RestFull

@Controller

@RequestMapping(value = "/rest")

publicclassRestWithController {}

 

@ResponseBody

    @RequestMapping(value = "/{msg}", method = RequestMethod.GET)

    publicString restString(@PathVariableString msg) {

       return msg;

    }

 

http://localhost:8088/framework-web/rest/messageone

 

    @ResponseBody

    @RequestMapping(value = "/{path}/{value}", method = RequestMethod.GET)

    publicString restXml(@PathVariableString path,@PathVariableString value) {

       return"path:"+path+",value:"+value;

    }

http://localhost:8088/framework-web/rest/xmlresources/assestlist

 

    @ResponseBody

    @RequestMapping(value = "/xml/{filename}", method = RequestMethod.GET)

    publicString restFile(@PathVariableString filename) {

       if (filename!=null) {

           ProjectInits init = ProjectInits.getInstance();

           String dir = init.get("resource.dir", "C:/Projects/VoyagerWeb/resources");

           FileUtility fUtil = newFileUtility();

           String content = fUtil.readFile(dir+"/"+filename+".xml");

           return content;

       }

       else

           return"Invalid xmlfile name ["+filename+"]";

    }

 

http://localhost:8088/framework-web/rest/xml/AddOnSelection

 

 

驗證 是否支持Overload

方式一

//驗證是否支持Overload

    @ResponseBody

    @RequestMapping(value = "/validate/overload1", method = RequestMethod.GET)

    publicString overloadMethod(String name){

       return name;

    }

    http://localhost:8088/framework-web/validate/overload1?name=rick

 

    @ResponseBody

    @RequestMapping(value = "/validate/overload2", method = RequestMethod.GET)

    publicString overloadMethod(String name,DnTest test){

       return"DnTest:"+test.toString();

    }

 

http://localhost:8088/framework-web/validate/overload2?name=rick

 

方式二

/驗證是否支持Overload

        @ResponseBody

         @RequestMapping(params = "m=method11")

       publicString method11(String name){

           return name;

       }

       

        @ResponseBody

         @RequestMapping(params = "m=method11")

       publicString method11(int age,DnTest test){

           return"DnTest:"+test.toString();

       }

 

http://localhost:8088/framework-web/login.do?m=method11&name=rick

 

 

 

 

 

 

 

參考資料

http://www.ibm.com/developerworks/cn/java/j-lo-spring25-mvc/

 

http://blog.springsource.org/2009/03/08/rest-in-spring-3-mvc/

 

http://www.congci.com/item/spring,mvc,restful,url

 

http://static.springsource.org/spring/docs/2.0.x/reference/mvc.html

 

http://hi.baidu.com/sunnysunshien/blog/item/6d5cbd536e18a5521138c27b.html

 

http://www.ibm.com/developerworks/cn/java/j-lo-spring25-mvc/

相關文章
相關標籤/搜索