SpingMVC ModelAndView, Model,Control以及參數傳遞

1.web.xml 配置:

<servlet>
    <servlet-name>dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <description>加載/WEB-INF/spring-mvc/目錄下的全部XML做爲Spring MVC的配置文件</description>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/spring-mvc/*.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
    <servlet-name>dispatcher</servlet-name>
    <url-pattern>*.htm</url-pattern>
</servlet-mapping>

這樣,全部的.htm的請求,都會被DispatcherServlet處理;前端

初始化 DispatcherServlet 時,該框架在 web 應用程序WEB-INF 目錄中尋找一個名爲[servlet-名稱]-servlet.xml的文件,並在那裏定義相關的Beans,重寫在全局中定義的任何Beans,像上面的web.xml中的代碼,對應的是dispatcher-servlet.xml;固然也可使用<init-param>元素,手動指定配置文件的路徑;dispatcher-servlet.xml 配置:java

<?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:mvc="http://www.springframework.org/schema/mvc"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
            http://www.springframework.org/schema/context 
            http://www.springframework.org/schema/context/spring-context-3.0.xsd
            http://www.springframework.org/schema/aop 
            http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
            http://www.springframework.org/schema/tx 
            http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
            http://www.springframework.org/schema/mvc 
            http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
            http://www.springframework.org/schema/context 
            http://www.springframework.org/schema/context/spring-context-3.0.xsd">
    <!--
        使Spring支持自動檢測組件,如註解的Controller
    -->
    <context:component-scan base-package="com.minx.crm.web.controller"/>
   
    <bean id="viewResolver"
          class="org.springframework.web.servlet.view.InternalResourceViewResolver"
          p:prefix="/WEB-INF/jsp/"
          p:suffix=".jsp" />
</beans>

2.spring mvc處理方法支持以下的返回方式:ModelAndView, Model, ModelMap, Map,View, String, void

 

ModelAndView

@RequestMapping("/show1") 
public ModelAndView show1(HttpServletRequest request, 
           HttpServletResponse response) throws Exception { 
       ModelAndView mav = new ModelAndView("/demo2/show"); 
       mav.addObject("account", "account -1"); 
       return mav; 
   } 

經過ModelAndView構造方法能夠指定返回的頁面名稱,也能夠經過setViewName()方法跳轉到指定的頁面 , 使用addObject()設置須要返回的值,addObject()有幾個不一樣參數的方法,能夠默認和指定返回對象的名字。 調用addObject()方法將值設置到一個名爲ModelMap的類屬性,ModelMap是LinkedHashMap的子類, 具體請看類。web

 

 

Model 是一個接口, 其實現類爲ExtendedModelMap,繼承了ModelMap類。

model.addAttribute("pojo", pojo);spring

Map 

@RequestMapping("/demo2/show") 
    public Map<String, String> getMap() { 
        Map<String, String> map = new HashMap<String, String>(); 
        map.put("key1", "value-1"); 
        map.put("key2", "value-2"); 
        return map; 
    } 

在jsp頁面中可直經過${key1}得到到值, map.put()至關於request.setAttribute方法。 寫例子時發現,key值包括 - . 時會有問題.spring-mvc

View 能夠返回pdf excel等,暫時沒詳細瞭解。

 

 

String 指定返回的視圖頁面名稱,結合設置的返回地址路徑加上頁面名稱後綴便可訪問到。

 

注意:若是方法聲明瞭註解@ResponseBody ,則會直接將返回值輸出到頁面。 例如:session

@RequestMapping(value = "/something", method = RequestMethod.GET) 
@ResponseBody 
public String helloWorld()  { 
return"Hello World"; 
} 

上面的結果會將文本"Hello World "直接寫到http響應流。mvc

@RequestMapping("/welcome") 
public String welcomeHandler() { 
  return"center"; 
} 

對應的邏輯視圖名爲「center」,URL= prefix前綴+視圖名稱 +suffix後綴組成。
void  若是返回值爲空,則響應的視圖頁面對應爲訪問地址app

@RequestMapping("/welcome") 
publicvoid welcomeHandler() {} 

此例對應的邏輯視圖名爲"welcome"。框架

小結:

1.使用 String 做爲請求處理方法的返回值類型是比較通用的方法,這樣返回的邏輯視圖名不會和請求 URL 綁定,具備很大的靈活性,而模型數據又能夠經過 ModelMap 控制。 2.使用void,map,Model 時,返回對應的邏輯視圖名稱真實url爲:prefix前綴+視圖名稱 +suffix後綴組成。 3.使用String,ModelAndView返回視圖名稱能夠不受請求的url綁定,ModelAndView能夠設置返回的視圖名稱。jsp

 

 

 

Model model,HttpServletRequest request, ModelMap map聲明變量

 

request.getSession().setAttribute("test", "haiwei2Session"); request.setAttribute("test", "haiwei1request"); map.addAttribute("test", "haiweiModelMap"); model.addAttribute("test", "haiweiModel");
我經過${test}這個方式取值,優先取Model和ModelMap的,Model和ModelMap是同一個東西,誰最後賦值的就取誰的,而後是request,最後是從session中獲取

 

 第一個Controller

package com.minx.crm.web.controller;  
  
import org.springframework.stereotype.Controller;  
import org.springframework.web.bind.annotation.RequestMapping;  
@Controller  
public class IndexController {  
    @RequestMapping("/index")  
    public String index() {  
        return "index";  
    }  
}  
package com.minx.crm.web.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class IndexController {
    @RequestMapping("/index")
    public String index() {
        return "index";
    }
}

@Controller註解標識一個控制器,@RequestMapping註解標記一個訪問的路徑(/index.htm),return "index"標記返回視圖(index.jsp);

注:若是@RequestMapping註解在類級別上,則表示一相對路徑,在方法級別上,則標記訪問的路徑;

從@RequestMapping註解標記的訪問路徑中獲取參數:

Spring MVC 支持RESTful風格的URL參數,如:

@Controller  
public class IndexController {  
  
    @RequestMapping("/index/{username}")  
    public String index(<span style="color: rgb(255, 0, 0);">@PathVariable</span>("username") String username) {  
        System.out.print(username);  
        return "index";  
    }  
}  
@Controller
public class IndexController {

    @RequestMapping("/index/{username}")
    public String index(@PathVariable("username") String username) {
        System.out.print(username);
        return "index";
    }
}

@RequestMapping中定義訪問頁面的URL模版,使用{}傳入頁面參數,使用@PathVariable 獲取傳入參數,便可經過地址:http://localhost:8080/crm/index/tanqimin.htm 訪問;

根據不一樣的Web請求方法,映射到不一樣的處理方法:

使用登錄頁面做示例,定義兩個方法分辨對使用GET請求和使用POST請求訪問login.htm時的響應。可使用處理GET請求的方法顯示視圖,使用POST請求的方法處理業務邏輯;

@Controller  
public class LoginController {  
    @RequestMapping(value = "/login", method = RequestMethod.GET)  
    public String login() {  
        return "login";  
    }  
    @RequestMapping(value = "/login", method = RequestMethod.POST)  
    public String login2(HttpServletRequest request) {  
            String username = request.getParameter("username").trim();  
            System.out.println(username);  
        return "login2";  
    }  
}  
@Controller
public class LoginController {
    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String login() {
        return "login";
    }
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public String login2(HttpServletRequest request) {
            String username = request.getParameter("username").trim();
            System.out.println(username);
        return "login2";
    }
}

在視圖頁面,經過地址欄訪問login.htm,是經過GET請求訪問頁面,所以,返回登錄表單視圖login.jsp;當在登錄表單中使用POST請求提交數據時,則訪問login2方法,處理登錄業務邏輯;

防止重複提交數據,可使用重定向視圖:

return "redirect:/login2"  
return "redirect:/login2"

能夠傳入方法的參數類型:

 

<strong>@RequestMapping(value = "login", method = RequestMethod.POST)  
public String testParam(HttpServletRequest request, HttpServletResponse response, HttpSession session) {  
    String username = request.getParameter("username");  
    System.out.println(username);  
    return null;  
}</strong>  
@RequestMapping(value = "login", method = RequestMethod.POST)
public String testParam(HttpServletRequest request, HttpServletResponse response, HttpSession session) {
	String username = request.getParameter("username");
	System.out.println(username);
	return null;
}

 

能夠傳入HttpServletRequestHttpServletResponseHttpSession,值得注意的是,若是第一次訪問頁面,HttpSession沒被建立,可能會出錯;

其中,String username = request.getParameter("username");能夠轉換爲傳入的參數:

@RequestMapping(value = "login", method = RequestMethod.POST)  
public String testParam(HttpServletRequest request, HttpServletResponse response, HttpSession session,@RequestParam("username") String username) {  
    String username = request.getParameter("username");  
    System.out.println(username);  
    return null;  
}  
@RequestMapping(value = "login", method = RequestMethod.POST)
public String testParam(HttpServletRequest request, HttpServletResponse response, HttpSession session,@RequestParam("username") String username) {
    String username = request.getParameter("username");
    System.out.println(username);
    return null;
}
 

使用@RequestParam 註解獲取GET請求或POST請求提交的參數;

獲取Cookie的值:使用@CookieValue :
獲取printwriter:
能夠直接在Controller的方法中傳入PrintWriter對象,就能夠在方法中使用:
@RequestMapping(value = "login", method = RequestMethod.POST)  
public String testParam(PrintWriter out, <span style="color: rgb(255, 0, 0);">@RequestParam</span>("username") String username) {  
    out.println(username);  
    return null;  
}  
@RequestMapping(value = "login", method = RequestMethod.POST)
public String testParam(PrintWriter out, @RequestParam("username") String username) {
	out.println(username);
	return null;
}

 

 

獲取表單中提交的值,並封裝到POJO中,傳入Controller的方法裏:

POJO以下(User.java):

 

public class User{  
    private long id;  
    private String username;  
    private String password;  
  
    …此處省略getter,setter...  
}  
public class User{
	private long id;
	private String username;
	private String password;

	…此處省略getter,setter...
}

 

 

經過表單提交,直接能夠把表單值封裝到User對象中:

@RequestMapping(value = "login", method = RequestMethod.POST)  
public String testParam(PrintWriter out, User user) {  
    out.println(user.getUsername());  
    return null;  
}  

 

@RequestMapping(value = "login", method = RequestMethod.POST)
public String testParam(PrintWriter out, User user) {
	out.println(user.getUsername());
	return null;
}

 

 

能夠把對象,put 入獲取的Map對象中,傳到對應的視圖:

<strong>@RequestMapping(value = "login", method = RequestMethod.POST)  
public String testParam(User user, Map model) {  
    model.put("user",user);  
    return "view";  
}</strong>  
@RequestMapping(value = "login", method = RequestMethod.POST)
public String testParam(User user, Map model) {
	model.put("user",user);
	return "view";
}

 

在返回的view.jsp中,就能夠根據key來獲取user的值(經過EL表達式,${user }便可);

Controller中方法的返回值:

void:多數用於使用PrintWriter輸出響應數據;

String 類型:返回該String對應的View Name

任意類型對象:

返回ModelAndView

自定義視圖(JstlView,ExcelView):

 攔截器(Inteceptors):

 

<strong>public class MyInteceptor implements HandlerInterceptor {  
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o)   
        throws Exception {  
        return false;  
    }  
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object o, ModelAndView mav)   
        throws Exception {  
    }  
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object o, Exception excptn)   
        throws Exception {  
    }  
}</strong>  
public class MyInteceptor implements HandlerInterceptor {
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) 
		throws Exception {
		return false;
	}
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object o, ModelAndView mav) 
		throws Exception {
	}
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object o, Exception excptn) 
		throws Exception {
	}
}

 

攔截器須要實現HandleInterceptor接口,並實現其三個方法:

preHandle:攔截器的前端,執行控制器以前所要處理的方法,一般用於權限控制、日誌,其中,Object o表示下一個攔截器;

postHandle:控制器的方法已經執行完畢,轉換成視圖以前的處理;

afterCompletion:視圖已處理完後執行的方法,一般用於釋放資源;

MVC的配置文件中,配置攔截器與須要攔截的URL

<mvc:interceptors>  
    <mvc:interceptor>  
        <mvc:mapping path="/index.htm" />  
        <bean class="com.minx.crm.web.interceptor.MyInterceptor" />  
    </mvc:interceptor>  
</mvc:interceptors> 
<mvc:interceptors>
	<mvc:interceptor>
		<mvc:mapping path="/index.htm" />
		<bean class="com.minx.crm.web.interceptor.MyInterceptor" />
	</mvc:interceptor>
</mvc:interceptors>

 

國際化:

MVC配置文件中,配置國際化屬性文件:

 

<bean id="messageSource"  
    class="org.springframework.context.support.ResourceBundleMessageSource"  
    p:basename="message">  
</bean>  
<bean id="messageSource"
	class="org.springframework.context.support.ResourceBundleMessageSource"
	p:basename="message">
</bean>

 

那麼,Spring就會在項目中搜索相關的國際化屬性文件,如:message.propertiesmessage_zh_CN.properties

VIEW中,引入Spring標籤:<%@taglib uri="http://www.springframework.org/tags" prefix="spring" %>,使用<spring:message code="key" />調用,便可;

若是一種語言,有多個語言文件,能夠更改MVC配置文件爲:

 

<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">  
    <property name="basenames">  
        <list>  
            <value>message01</value>  
            <value>message02</value>  
            <value>message03</value>  
        </list>  
    </property>  
</bean>  
相關文章
相關標籤/搜索