[セットトップ]Spring MVC 3.0の詳細と注釈の詳細
コア原理
1.ユーザがサーバに要求を送信する.url:user.do
2.サーバが要求を受信しました.Dispatchservletが処理できることがわかりました.そこでDispatchServeretを呼び出します.
3.DispatchServicelet内部で、HandleMappingでこのurlに対応するControllerがあるかどうかをチェックします.ある場合はControllerを呼び出します.
4、Control実行開始
5.Controllerの実行後、文字列を返すと、ViewResolverは文字列を対応するビューオブジェクトに変換します.ModelAndViewオブジェクトを返すと、そのオブジェクト自体にビューオブジェクト情報が含まれます.
6.DispatchServiceletは、ビューオブジェクトのデータをサーバに出力します.
7.サーバはクライアントにデータを出力します.
spring3.0の関連jarパッケージの意味
org.springframework.aop-3.0.3.RELEASE.jar
Springのaop面向けプログラミング
org.springframework.asm-3.0.3.RELEASE.jar
Spring独立asmバイトコード生成プログラム
org.springframework.beans-3.0.3.RELEASE.jar
IOCの基礎実現
org.springframework.context-3.0.3.RELEASE.jar
IOCベースの拡張サービス
org.springframework.core-3.0.3.RELEASE.jar
スプリングのコアパッケージ
org.springframework.expression-3.0.3.RELEASE.jar
Springの式言語
org.springframework.web-3.0.3.RELEASE.jar
Webツールパッケージ
org.springframework.web.servlet-3.0.3.RELEASE.jar
mvcキット
@コントローラ定義
Struts 1と同様にSpringのControllerはSingletonです.これは、複数のリクエストスレッドによって共有されることを意味する.そこで,コントローラを無状態クラスに設計した.
spring 3.0では、@controller寸法でclassをcontrollerクラスとして定義します.springがcontrollerとして定義されたbeanを見つけるには、spring-contextプロファイルに次の定義を追加する必要があります.
注意:実際には、@componentを使用しても、@Controllerと同様の役割を果たすことができます.
@RequestMapping
クラスの前に定義するとurlとクラスがバインドされます.
メソッドの前に定義するとurlとクラスのメソッドがバインドされます
@RequestParam
一般的に、指定した要求パラメータをメソッドのパラメータに割り当てるために使用されます.サンプルコードは次のとおりです.
@RequestMapping(params="method=reg5") public String reg5(@RequestParam("name")String uname,ModelMap map) { System.out.println("HelloController.handleRequest()"); System.out.println(uname); return"index"; }
これにより、nameパラメータの値がunameに支払われます.もちろん、要求パラメータ名とパラメータ名が一致している場合は、このような書き方は必要ありません.
@SessionAttributes
ModelMapで指定した属性をセッションに配置します.サンプルコードは次のとおりです.
@Controller@RequestMapping("/user.do")@SessionAttributes({"u","a"})/ModelMapの属性名u,aをセッションに追加します.これでrequestもsessionもあります.publicclass UserController{@RequestMapping(params="method=reg 4")public String reg 4(ModelMap map){System.out.println("HelloController.handleRequest());map.addAttribute("u","uuuuuu");//requestドメインにuを入れることで、転送ページもこのデータを取得できます.return"index"; } }
**********${requestScope.u.uname}
1.ユーザがサーバに要求を送信する.url:user.do
2.サーバが要求を受信しました.Dispatchservletが処理できることがわかりました.そこでDispatchServeretを呼び出します.
3.DispatchServicelet内部で、HandleMappingでこのurlに対応するControllerがあるかどうかをチェックします.ある場合はControllerを呼び出します.
4、Control実行開始
5.Controllerの実行後、文字列を返すと、ViewResolverは文字列を対応するビューオブジェクトに変換します.ModelAndViewオブジェクトを返すと、そのオブジェクト自体にビューオブジェクト情報が含まれます.
6.DispatchServiceletは、ビューオブジェクトのデータをサーバに出力します.
7.サーバはクライアントにデータを出力します.
spring3.0の関連jarパッケージの意味
org.springframework.aop-3.0.3.RELEASE.jar
Springのaop面向けプログラミング
org.springframework.asm-3.0.3.RELEASE.jar
Spring独立asmバイトコード生成プログラム
org.springframework.beans-3.0.3.RELEASE.jar
IOCの基礎実現
org.springframework.context-3.0.3.RELEASE.jar
IOCベースの拡張サービス
org.springframework.core-3.0.3.RELEASE.jar
スプリングのコアパッケージ
org.springframework.expression-3.0.3.RELEASE.jar
Springの式言語
org.springframework.web-3.0.3.RELEASE.jar
Webツールパッケージ
org.springframework.web.servlet-3.0.3.RELEASE.jar
mvcキット
@コントローラ定義
Struts 1と同様にSpringのControllerはSingletonです.これは、複数のリクエストスレッドによって共有されることを意味する.そこで,コントローラを無状態クラスに設計した.
spring 3.0では、@controller寸法でclassをcontrollerクラスとして定義します.springがcontrollerとして定義されたbeanを見つけるには、spring-contextプロファイルに次の定義を追加する必要があります.
注意:実際には、@componentを使用しても、@Controllerと同様の役割を果たすことができます.
@RequestMapping
クラスの前に定義するとurlとクラスがバインドされます.
メソッドの前に定義するとurlとクラスのメソッドがバインドされます
@RequestParam
一般的に、指定した要求パラメータをメソッドのパラメータに割り当てるために使用されます.サンプルコードは次のとおりです.
@RequestMapping(params="method=reg5") public String reg5(@RequestParam("name")String uname,ModelMap map) { System.out.println("HelloController.handleRequest()"); System.out.println(uname); return"index"; }
これにより、nameパラメータの値がunameに支払われます.もちろん、要求パラメータ名とパラメータ名が一致している場合は、このような書き方は必要ありません.
@SessionAttributes
ModelMapで指定した属性をセッションに配置します.サンプルコードは次のとおりです.
@Controller@RequestMapping("/user.do")@SessionAttributes({"u","a"})/ModelMapの属性名u,aをセッションに追加します.これでrequestもsessionもあります.publicclass UserController{@RequestMapping(params="method=reg 4")public String reg 4(ModelMap map){System.out.println("HelloController.handleRequest());map.addAttribute("u","uuuuuu");//requestドメインにuを入れることで、転送ページもこのデータを取得できます.return"index"; } }
**********${requestScope.u.uname} **********${sessionScope.u.uname}
注意:「user」という名前のプロパティを組み合わせて注記@SessionAttributesを使用すると、エラーが発生する可能性があります.
@ModelAttribute
この注記は@SessionAttributesと組み合わせて使用できます.ModelMapのプロパティの値は、この注記で指定した変数に自動的に割り当てられます.
サンプルコードは次のとおりです.
package com.sxt.web; import javax.annotation.Resource; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.SessionAttributes; @Controller@RequestMapping("/user.do")@ SessionAttributes({"u","a"})publicclass UserController{@RequestMapping(params="method=reg 4")public String reg 4(ModelMapmap){System.out.println("HelloController.handleRequest());map.map.addAttribute("u","尚学堂高淇"); return"index";;;;;return"index";;;;;; } @RequestMapping(params="method=reg5") public String reg5(@ModelAttribute("u")String uname ,ModelMap map) { System.out.println("HelloController.handleRequest()"); System.out.println(uname); return"index"; } }
reg 4メソッドを呼び出してからreg 5メソッドを呼び出します.
Controllerクラスにおけるメソッドパラメータの処理
Controllerクラスにおけるメソッド戻り値の処理
1.stringに戻る(推奨)
a)戻り値に応じて対応する表示ページを探す.パスルールは、prefix接頭辞+戻り値+suffix接尾辞で構成されます.
b)コードは以下の通りである.
@RequestMapping(params="method=reg4") public String reg4(ModelMap map) { System.out.println("HelloController.handleRequest()"); return"index"; }
接頭辞:/WEB-INF/jsp/接尾辞は:.jspは:/WEB-INF/jsp/indexに転送する.jsp
2.ModelMap、ModelAndView、map、List、Set、Object、戻り値なしを返すこともできます.一般的には文字列を返すことをお勧めします.
リクエスト転送とリダイレクト
コードの例:
package com.sxt.web; import javax.annotation.Resource; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.SessionAttributes; @Controller @RequestMapping("/user.do") publicclass UserController { @RequestMapping(params="method=reg4") public String reg4(ModelMap map) { System.out.println("HelloController.handleRequest()");// return "forward:index.jsp";// return "forward:user.do?method=reg5";//転送//return「redirect:user.do?method=reg 5」;//return「redirect:http://www.baidu.com";//リダイレクト}@RequestMapping(params="method=reg 5")public String reg 5(String uname,ModelMap){System.out.println("HelloController.handleRequest()");System.out.println(uname);return"index"; } }
reg 4メソッドにアクセスすると、効果も表示されます.
requestオブジェクト、sessionオブジェクトの取得
通常のControllerクラスのサンプルコードは次のとおりです.
@Controller @RequestMapping("/user.do") publicclass UserController { @RequestMapping(params="method=reg2") public String reg2(String uname,HttpServletRequest req,ModelMap map){ req.setAttribute("a", "aa"); req.getSession().setAttribute("b", "bb"); return"index"; } }
ModelMap
mapの実装であり、属性を格納することができ、役割ドメインはrequestと同じである.次の例では、modelMapにデータを入れ、forwardのページに表示できます.el式、JSTL、javaコードで構いません.コードは次のとおりです.
package com.sxt.web; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.mvc.multiaction.MultiActionController; @Controller @RequestMapping("/user.do") publicclass UserController extends MultiActionController { @RequestMapping(params="method=reg") public String reg(String uname,ModelMap map){ map.put("a", "aaa"); return"index"; } }
<%@ page language="java"import="java.util.*"pageEncoding="gbk"%> <%@ taglib prefix="c"uri="http://java.sun.com/jsp/jstl/core"%> ${requestScope.a}
属性uの値をパラメータunameに割り当てる
ModelAndViewモデルビュークラス
名前を見て、名前からModelAndViewのModelがモデルを表し、Viewがビューを表すことがわかります.すなわち,このクラスは表示するデータをModel属性に格納し,ジャンプするビュー情報をview属性に格納する.ModelAndViewのソースコードの一部を見てみましょう.つまり、その関係がわかります.public class ModelAndView {
/** View instance or view name String */
private Object view;
/** Model Map */
private ModelMap model;
/**
* Indicates whether or not this instance has been cleared with a call to {@link #clear()}.
*/
private boolean cleared = false;
/**
* Default constructor for bean-style usage: populating bean
* properties instead of passing in constructor arguments.
* @see #setView(View)
* @see #setViewName(String)
*/
public ModelAndView() {
}
/**
* Convenient constructor when there is no model data to expose.
* Can also be used in conjunction with <code>addObject</code>.
* @param viewName name of the View to render, to be resolved
* by the DispatcherServlet's ViewResolver
* @see #addObject
*/
public ModelAndView(String viewName) {
this.view = viewName;
}
/**
* Convenient constructor when there is no model data to expose.
* Can also be used in conjunction with <code>addObject</code>.
* @param view View object to render
* @see #addObject
*/
public ModelAndView(View view) {
this.view = view;
}
/**
* Creates new ModelAndView given a view name and a model.
* @param viewName name of the View to render, to be resolved
* by the DispatcherServlet's ViewResolver
* @param model Map of model names (Strings) to model objects
* (Objects). Model entries may not be <code>null</code>, but the
* model Map may be <code>null</code> if there is no model data.
*/
public ModelAndView(String viewName, Map<String, ?> model) {
this.view = viewName;
if (model != null) {
getModelMap().addAllAttributes(model);
}
}
/**
* Creates new ModelAndView given a View object and a model.
* <emphasis>Note: the supplied model data is copied into the internal
* storage of this class. You should not consider to modify the supplied
* Map after supplying it to this class</emphasis>
* @param view View object to render
* @param model Map of model names (Strings) to model objects
* (Objects). Model entries may not be <code>null</code>, but the
* model Map may be <code>null</code> if there is no model data.
*/
public ModelAndView(View view, Map<String, ?> model) {
this.view = view;
if (model != null) {
getModelMap().addAllAttributes(model);
}
}
/**
* Convenient constructor to take a single model object.
* @param viewName name of the View to render, to be resolved
* by the DispatcherServlet's ViewResolver
* @param modelName name of the single entry in the model
* @param modelObject the single model object
*/
public ModelAndView(String viewName, String modelName, Object modelObject) {
this.view = viewName;
addObject(modelName, modelObject);
}
/**
* Convenient constructor to take a single model object.
* @param view View object to render
* @param modelName name of the single entry in the model
* @param modelObject the single model object
*/
public ModelAndView(View view, String modelName, Object modelObject) {
this.view = view;
addObject(modelName, modelObject);
}
/**
* Set a view name for this ModelAndView, to be resolved by the
* DispatcherServlet via a ViewResolver. Will override any
* pre-existing view name or View.
*/
public void setViewName(String viewName) {
this.view = viewName;
}
/**
* Return the view name to be resolved by the DispatcherServlet
* via a ViewResolver, or <code>null</code> if we are using a View object.
*/
public String getViewName() {
return (this.view instanceof String ? (String) this.view : null);
}
/**
* Set a View object for this ModelAndView. Will override any
* pre-existing view name or View.
*/
public void setView(View view) {
this.view = view;
}
/**
* Return the View object, or <code>null</code> if we are using a view name
* to be resolved by the DispatcherServlet via a ViewResolver.
*/
public View getView() {
return (this.view instanceof View ? (View) this.view : null);
}
/**
* Indicate whether or not this <code>ModelAndView</code> has a view, either
* as a view name or as a direct {@link View} instance.
*/
public boolean hasView() {
return (this.view != null);
}
/**
* Return whether we use a view reference, i.e. <code>true</code>
* if the view has been specified via a name to be resolved by the
* DispatcherServlet via a ViewResolver.
*/
public boolean isReference() {
return (this.view instanceof String);
}
/**
* Return the model map. May return <code>null</code>.
* Called by DispatcherServlet for evaluation of the model.
*/
protected Map<String, Object> getModelInternal() {
return this.model;
}
/**
* Return the underlying <code>ModelMap</code> instance (never <code>null</code>).
*/
public ModelMap getModelMap() {
if (this.model == null) {
this.model = new ModelMap();
}
return this.model;
}
/**
* Return the model map. Never returns <code>null</code>.
* To be called by application code for modifying the model.
*/
public Map<String, Object> getModel() {
return getModelMap();
}
/**
* Add an attribute to the model.
* @param attributeName name of the object to add to the model
* @param attributeValue object to add to the model (never <code>null</code>)
* @see ModelMap#addAttribute(String, Object)
* @see #getModelMap()
*/
public ModelAndView addObject(String attributeName, Object attributeValue) {
getModelMap().addAttribute(attributeName, attributeValue);
return this;
}
/**
* Add an attribute to the model using parameter name generation.
* @param attributeValue the object to add to the model (never <code>null</code>)
* @see ModelMap#addAttribute(Object)
* @see #getModelMap()
*/
public ModelAndView addObject(Object attributeValue) {
getModelMap().addAttribute(attributeValue);
return this;
}
/**
* Add all attributes contained in the provided Map to the model.
* @param modelMap a Map of attributeName -> attributeValue pairs
* @see ModelMap#addAllAttributes(Map)
* @see #getModelMap()
*/
public ModelAndView addAllObjects(Map<String, ?> modelMap) {
getModelMap().addAllAttributes(modelMap);
return this;
}
/**
* Clear the state of this ModelAndView object.
* The object will be empty afterwards.
* <p>Can be used to suppress rendering of a given ModelAndView object
* in the <code>postHandle</code> method of a HandlerInterceptor.
* @see #isEmpty()
* @see HandlerInterceptor#postHandle
*/
public void clear() {
this.view = null;
this.model = null;
this.cleared = true;
}
/**
* Return whether this ModelAndView object is empty,
* i.e. whether it does not hold any view and does not contain a model.
*/
public boolean isEmpty() {
return (this.view == null && CollectionUtils.isEmpty(this.model));
}
/**
* Return whether this ModelAndView object is empty as a result of a call to {@link #clear}
* i.e. whether it does not hold any view and does not contain a model.
* <p>Returns <code>false</code> if any additional state was added to the instance
* <strong>after</strong> the call to {@link #clear}.
* @see #clear()
*/
public boolean wasCleared() {
return (this.cleared && isEmpty());
}
/**
* Return diagnostic information about this model and view.
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder("ModelAndView: ");
if (isReference()) {
sb.append("reference to view with name '").append(this.view).append("'");
}
else {
sb.append("materialized View is [").append(this.view).append(']');
}
sb.append("; model is ").append(this.model);
return sb.toString();
}
}
:
package com.sxt.web;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;
import com.sxt.po.User;
@Controller
@RequestMapping("/user.do")
public class UserController extends MultiActionController {
@RequestMapping(params="method=reg")
public ModelAndView reg(String uname){
ModelAndView mv = new ModelAndView();
mv.setViewName("index");
// mv.setView(new RedirectView("index"));
User u = new User();
u.setUname(" ");
mv.addObject(u); // , , 。 ” ”。 。
mv.addObject("a", "aaaa");
return mv;
}
}
<%@ page language="java" import="java.util.*" pageEncoding="gbk"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
</head>
<body>
<h1>${requestScope.a}</h1>
<h1>${requestScope.user.uname}</h1>
</body>
</html>
:http://localhost:8080/springmvc03/user.do?method=reg
:
注意:「user」という名前のプロパティを組み合わせて注記@SessionAttributesを使用すると、エラーが発生する可能性があります.
@ModelAttribute
この注記は@SessionAttributesと組み合わせて使用できます.ModelMapのプロパティの値は、この注記で指定した変数に自動的に割り当てられます.
サンプルコードは次のとおりです.
package com.sxt.web; import javax.annotation.Resource; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.SessionAttributes; @Controller@RequestMapping("/user.do")@ SessionAttributes({"u","a"})publicclass UserController{@RequestMapping(params="method=reg 4")public String reg 4(ModelMapmap){System.out.println("HelloController.handleRequest());map.map.addAttribute("u","尚学堂高淇"); return"index";;;;;return"index";;;;;; } @RequestMapping(params="method=reg5") public String reg5(@ModelAttribute("u")String uname ,ModelMap map) { System.out.println("HelloController.handleRequest()"); System.out.println(uname); return"index"; } }
reg 4メソッドを呼び出してからreg 5メソッドを呼び出します.
Controllerクラスにおけるメソッドパラメータの処理
Controllerクラスにおけるメソッド戻り値の処理
1.stringに戻る(推奨)
a)戻り値に応じて対応する表示ページを探す.パスルールは、prefix接頭辞+戻り値+suffix接尾辞で構成されます.
b)コードは以下の通りである.
@RequestMapping(params="method=reg4") public String reg4(ModelMap map) { System.out.println("HelloController.handleRequest()"); return"index"; }
接頭辞:/WEB-INF/jsp/接尾辞は:.jspは:/WEB-INF/jsp/indexに転送する.jsp
2.ModelMap、ModelAndView、map、List、Set、Object、戻り値なしを返すこともできます.一般的には文字列を返すことをお勧めします.
リクエスト転送とリダイレクト
コードの例:
package com.sxt.web; import javax.annotation.Resource; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.SessionAttributes; @Controller @RequestMapping("/user.do") publicclass UserController { @RequestMapping(params="method=reg4") public String reg4(ModelMap map) { System.out.println("HelloController.handleRequest()");// return "forward:index.jsp";// return "forward:user.do?method=reg5";//転送//return「redirect:user.do?method=reg 5」;//return「redirect:http://www.baidu.com";//リダイレクト}@RequestMapping(params="method=reg 5")public String reg 5(String uname,ModelMap){System.out.println("HelloController.handleRequest()");System.out.println(uname);return"index"; } }
reg 4メソッドにアクセスすると、効果も表示されます.
requestオブジェクト、sessionオブジェクトの取得
通常のControllerクラスのサンプルコードは次のとおりです.
@Controller @RequestMapping("/user.do") publicclass UserController { @RequestMapping(params="method=reg2") public String reg2(String uname,HttpServletRequest req,ModelMap map){ req.setAttribute("a", "aa"); req.getSession().setAttribute("b", "bb"); return"index"; } }
ModelMap
mapの実装であり、属性を格納することができ、役割ドメインはrequestと同じである.次の例では、modelMapにデータを入れ、forwardのページに表示できます.el式、JSTL、javaコードで構いません.コードは次のとおりです.
package com.sxt.web; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.mvc.multiaction.MultiActionController; @Controller @RequestMapping("/user.do") publicclass UserController extends MultiActionController { @RequestMapping(params="method=reg") public String reg(String uname,ModelMap map){ map.put("a", "aaa"); return"index"; } }
<%@ page language="java"import="java.util.*"pageEncoding="gbk"%> <%@ taglib prefix="c"uri="http://java.sun.com/jsp/jstl/core"%>
${requestScope.a}
属性uの値をパラメータunameに割り当てる
ModelAndViewモデルビュークラス
名前を見て、名前からModelAndViewのModelがモデルを表し、Viewがビューを表すことがわかります.すなわち,このクラスは表示するデータをModel属性に格納し,ジャンプするビュー情報をview属性に格納する.ModelAndViewのソースコードの一部を見てみましょう.つまり、その関係がわかります.public class ModelAndView {
/** View instance or view name String */
private Object view;
/** Model Map */
private ModelMap model;
/**
* Indicates whether or not this instance has been cleared with a call to {@link #clear()}.
*/
private boolean cleared = false;
/**
* Default constructor for bean-style usage: populating bean
* properties instead of passing in constructor arguments.
* @see #setView(View)
* @see #setViewName(String)
*/
public ModelAndView() {
}
/**
* Convenient constructor when there is no model data to expose.
* Can also be used in conjunction with <code>addObject</code>.
* @param viewName name of the View to render, to be resolved
* by the DispatcherServlet's ViewResolver
* @see #addObject
*/
public ModelAndView(String viewName) {
this.view = viewName;
}
/**
* Convenient constructor when there is no model data to expose.
* Can also be used in conjunction with <code>addObject</code>.
* @param view View object to render
* @see #addObject
*/
public ModelAndView(View view) {
this.view = view;
}
/**
* Creates new ModelAndView given a view name and a model.
* @param viewName name of the View to render, to be resolved
* by the DispatcherServlet's ViewResolver
* @param model Map of model names (Strings) to model objects
* (Objects). Model entries may not be <code>null</code>, but the
* model Map may be <code>null</code> if there is no model data.
*/
public ModelAndView(String viewName, Map<String, ?> model) {
this.view = viewName;
if (model != null) {
getModelMap().addAllAttributes(model);
}
}
/**
* Creates new ModelAndView given a View object and a model.
* <emphasis>Note: the supplied model data is copied into the internal
* storage of this class. You should not consider to modify the supplied
* Map after supplying it to this class</emphasis>
* @param view View object to render
* @param model Map of model names (Strings) to model objects
* (Objects). Model entries may not be <code>null</code>, but the
* model Map may be <code>null</code> if there is no model data.
*/
public ModelAndView(View view, Map<String, ?> model) {
this.view = view;
if (model != null) {
getModelMap().addAllAttributes(model);
}
}
/**
* Convenient constructor to take a single model object.
* @param viewName name of the View to render, to be resolved
* by the DispatcherServlet's ViewResolver
* @param modelName name of the single entry in the model
* @param modelObject the single model object
*/
public ModelAndView(String viewName, String modelName, Object modelObject) {
this.view = viewName;
addObject(modelName, modelObject);
}
/**
* Convenient constructor to take a single model object.
* @param view View object to render
* @param modelName name of the single entry in the model
* @param modelObject the single model object
*/
public ModelAndView(View view, String modelName, Object modelObject) {
this.view = view;
addObject(modelName, modelObject);
}
/**
* Set a view name for this ModelAndView, to be resolved by the
* DispatcherServlet via a ViewResolver. Will override any
* pre-existing view name or View.
*/
public void setViewName(String viewName) {
this.view = viewName;
}
/**
* Return the view name to be resolved by the DispatcherServlet
* via a ViewResolver, or <code>null</code> if we are using a View object.
*/
public String getViewName() {
return (this.view instanceof String ? (String) this.view : null);
}
/**
* Set a View object for this ModelAndView. Will override any
* pre-existing view name or View.
*/
public void setView(View view) {
this.view = view;
}
/**
* Return the View object, or <code>null</code> if we are using a view name
* to be resolved by the DispatcherServlet via a ViewResolver.
*/
public View getView() {
return (this.view instanceof View ? (View) this.view : null);
}
/**
* Indicate whether or not this <code>ModelAndView</code> has a view, either
* as a view name or as a direct {@link View} instance.
*/
public boolean hasView() {
return (this.view != null);
}
/**
* Return whether we use a view reference, i.e. <code>true</code>
* if the view has been specified via a name to be resolved by the
* DispatcherServlet via a ViewResolver.
*/
public boolean isReference() {
return (this.view instanceof String);
}
/**
* Return the model map. May return <code>null</code>.
* Called by DispatcherServlet for evaluation of the model.
*/
protected Map<String, Object> getModelInternal() {
return this.model;
}
/**
* Return the underlying <code>ModelMap</code> instance (never <code>null</code>).
*/
public ModelMap getModelMap() {
if (this.model == null) {
this.model = new ModelMap();
}
return this.model;
}
/**
* Return the model map. Never returns <code>null</code>.
* To be called by application code for modifying the model.
*/
public Map<String, Object> getModel() {
return getModelMap();
}
/**
* Add an attribute to the model.
* @param attributeName name of the object to add to the model
* @param attributeValue object to add to the model (never <code>null</code>)
* @see ModelMap#addAttribute(String, Object)
* @see #getModelMap()
*/
public ModelAndView addObject(String attributeName, Object attributeValue) {
getModelMap().addAttribute(attributeName, attributeValue);
return this;
}
/**
* Add an attribute to the model using parameter name generation.
* @param attributeValue the object to add to the model (never <code>null</code>)
* @see ModelMap#addAttribute(Object)
* @see #getModelMap()
*/
public ModelAndView addObject(Object attributeValue) {
getModelMap().addAttribute(attributeValue);
return this;
}
/**
* Add all attributes contained in the provided Map to the model.
* @param modelMap a Map of attributeName -> attributeValue pairs
* @see ModelMap#addAllAttributes(Map)
* @see #getModelMap()
*/
public ModelAndView addAllObjects(Map<String, ?> modelMap) {
getModelMap().addAllAttributes(modelMap);
return this;
}
/**
* Clear the state of this ModelAndView object.
* The object will be empty afterwards.
* <p>Can be used to suppress rendering of a given ModelAndView object
* in the <code>postHandle</code> method of a HandlerInterceptor.
* @see #isEmpty()
* @see HandlerInterceptor#postHandle
*/
public void clear() {
this.view = null;
this.model = null;
this.cleared = true;
}
/**
* Return whether this ModelAndView object is empty,
* i.e. whether it does not hold any view and does not contain a model.
*/
public boolean isEmpty() {
return (this.view == null && CollectionUtils.isEmpty(this.model));
}
/**
* Return whether this ModelAndView object is empty as a result of a call to {@link #clear}
* i.e. whether it does not hold any view and does not contain a model.
* <p>Returns <code>false</code> if any additional state was added to the instance
* <strong>after</strong> the call to {@link #clear}.
* @see #clear()
*/
public boolean wasCleared() {
return (this.cleared && isEmpty());
}
/**
* Return diagnostic information about this model and view.
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder("ModelAndView: ");
if (isReference()) {
sb.append("reference to view with name '").append(this.view).append("'");
}
else {
sb.append("materialized View is [").append(this.view).append(']');
}
sb.append("; model is ").append(this.model);
return sb.toString();
}
}
:
package com.sxt.web;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;
import com.sxt.po.User;
@Controller
@RequestMapping("/user.do")
public class UserController extends MultiActionController {
@RequestMapping(params="method=reg")
public ModelAndView reg(String uname){
ModelAndView mv = new ModelAndView();
mv.setViewName("index");
// mv.setView(new RedirectView("index"));
User u = new User();
u.setUname(" ");
mv.addObject(u); // , , 。 ” ”。 。
mv.addObject("a", "aaaa");
return mv;
}
}
<%@ page language="java" import="java.util.*" pageEncoding="gbk"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
</head>
<body>
<h1>${requestScope.a}</h1>
<h1>${requestScope.user.uname}</h1>
</body>
</html>
:http://localhost:8080/springmvc03/user.do?method=reg
:
public class ModelAndView {
/** View instance or view name String */
private Object view;
/** Model Map */
private ModelMap model;
/**
* Indicates whether or not this instance has been cleared with a call to {@link #clear()}.
*/
private boolean cleared = false;
/**
* Default constructor for bean-style usage: populating bean
* properties instead of passing in constructor arguments.
* @see #setView(View)
* @see #setViewName(String)
*/
public ModelAndView() {
}
/**
* Convenient constructor when there is no model data to expose.
* Can also be used in conjunction with <code>addObject</code>.
* @param viewName name of the View to render, to be resolved
* by the DispatcherServlet's ViewResolver
* @see #addObject
*/
public ModelAndView(String viewName) {
this.view = viewName;
}
/**
* Convenient constructor when there is no model data to expose.
* Can also be used in conjunction with <code>addObject</code>.
* @param view View object to render
* @see #addObject
*/
public ModelAndView(View view) {
this.view = view;
}
/**
* Creates new ModelAndView given a view name and a model.
* @param viewName name of the View to render, to be resolved
* by the DispatcherServlet's ViewResolver
* @param model Map of model names (Strings) to model objects
* (Objects). Model entries may not be <code>null</code>, but the
* model Map may be <code>null</code> if there is no model data.
*/
public ModelAndView(String viewName, Map<String, ?> model) {
this.view = viewName;
if (model != null) {
getModelMap().addAllAttributes(model);
}
}
/**
* Creates new ModelAndView given a View object and a model.
* <emphasis>Note: the supplied model data is copied into the internal
* storage of this class. You should not consider to modify the supplied
* Map after supplying it to this class</emphasis>
* @param view View object to render
* @param model Map of model names (Strings) to model objects
* (Objects). Model entries may not be <code>null</code>, but the
* model Map may be <code>null</code> if there is no model data.
*/
public ModelAndView(View view, Map<String, ?> model) {
this.view = view;
if (model != null) {
getModelMap().addAllAttributes(model);
}
}
/**
* Convenient constructor to take a single model object.
* @param viewName name of the View to render, to be resolved
* by the DispatcherServlet's ViewResolver
* @param modelName name of the single entry in the model
* @param modelObject the single model object
*/
public ModelAndView(String viewName, String modelName, Object modelObject) {
this.view = viewName;
addObject(modelName, modelObject);
}
/**
* Convenient constructor to take a single model object.
* @param view View object to render
* @param modelName name of the single entry in the model
* @param modelObject the single model object
*/
public ModelAndView(View view, String modelName, Object modelObject) {
this.view = view;
addObject(modelName, modelObject);
}
/**
* Set a view name for this ModelAndView, to be resolved by the
* DispatcherServlet via a ViewResolver. Will override any
* pre-existing view name or View.
*/
public void setViewName(String viewName) {
this.view = viewName;
}
/**
* Return the view name to be resolved by the DispatcherServlet
* via a ViewResolver, or <code>null</code> if we are using a View object.
*/
public String getViewName() {
return (this.view instanceof String ? (String) this.view : null);
}
/**
* Set a View object for this ModelAndView. Will override any
* pre-existing view name or View.
*/
public void setView(View view) {
this.view = view;
}
/**
* Return the View object, or <code>null</code> if we are using a view name
* to be resolved by the DispatcherServlet via a ViewResolver.
*/
public View getView() {
return (this.view instanceof View ? (View) this.view : null);
}
/**
* Indicate whether or not this <code>ModelAndView</code> has a view, either
* as a view name or as a direct {@link View} instance.
*/
public boolean hasView() {
return (this.view != null);
}
/**
* Return whether we use a view reference, i.e. <code>true</code>
* if the view has been specified via a name to be resolved by the
* DispatcherServlet via a ViewResolver.
*/
public boolean isReference() {
return (this.view instanceof String);
}
/**
* Return the model map. May return <code>null</code>.
* Called by DispatcherServlet for evaluation of the model.
*/
protected Map<String, Object> getModelInternal() {
return this.model;
}
/**
* Return the underlying <code>ModelMap</code> instance (never <code>null</code>).
*/
public ModelMap getModelMap() {
if (this.model == null) {
this.model = new ModelMap();
}
return this.model;
}
/**
* Return the model map. Never returns <code>null</code>.
* To be called by application code for modifying the model.
*/
public Map<String, Object> getModel() {
return getModelMap();
}
/**
* Add an attribute to the model.
* @param attributeName name of the object to add to the model
* @param attributeValue object to add to the model (never <code>null</code>)
* @see ModelMap#addAttribute(String, Object)
* @see #getModelMap()
*/
public ModelAndView addObject(String attributeName, Object attributeValue) {
getModelMap().addAttribute(attributeName, attributeValue);
return this;
}
/**
* Add an attribute to the model using parameter name generation.
* @param attributeValue the object to add to the model (never <code>null</code>)
* @see ModelMap#addAttribute(Object)
* @see #getModelMap()
*/
public ModelAndView addObject(Object attributeValue) {
getModelMap().addAttribute(attributeValue);
return this;
}
/**
* Add all attributes contained in the provided Map to the model.
* @param modelMap a Map of attributeName -> attributeValue pairs
* @see ModelMap#addAllAttributes(Map)
* @see #getModelMap()
*/
public ModelAndView addAllObjects(Map<String, ?> modelMap) {
getModelMap().addAllAttributes(modelMap);
return this;
}
/**
* Clear the state of this ModelAndView object.
* The object will be empty afterwards.
* <p>Can be used to suppress rendering of a given ModelAndView object
* in the <code>postHandle</code> method of a HandlerInterceptor.
* @see #isEmpty()
* @see HandlerInterceptor#postHandle
*/
public void clear() {
this.view = null;
this.model = null;
this.cleared = true;
}
/**
* Return whether this ModelAndView object is empty,
* i.e. whether it does not hold any view and does not contain a model.
*/
public boolean isEmpty() {
return (this.view == null && CollectionUtils.isEmpty(this.model));
}
/**
* Return whether this ModelAndView object is empty as a result of a call to {@link #clear}
* i.e. whether it does not hold any view and does not contain a model.
* <p>Returns <code>false</code> if any additional state was added to the instance
* <strong>after</strong> the call to {@link #clear}.
* @see #clear()
*/
public boolean wasCleared() {
return (this.cleared && isEmpty());
}
/**
* Return diagnostic information about this model and view.
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder("ModelAndView: ");
if (isReference()) {
sb.append("reference to view with name '").append(this.view).append("'");
}
else {
sb.append("materialized View is [").append(this.view).append(']');
}
sb.append("; model is ").append(this.model);
return sb.toString();
}
}
:
package com.sxt.web;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;
import com.sxt.po.User;
@Controller
@RequestMapping("/user.do")
public class UserController extends MultiActionController {
@RequestMapping(params="method=reg")
public ModelAndView reg(String uname){
ModelAndView mv = new ModelAndView();
mv.setViewName("index");
// mv.setView(new RedirectView("index"));
User u = new User();
u.setUname(" ");
mv.addObject(u); // , , 。 ” ”。 。
mv.addObject("a", "aaaa");
return mv;
}
}
<%@ page language="java" import="java.util.*" pageEncoding="gbk"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
</head>
<body>
<h1>${requestScope.a}</h1>
<h1>${requestScope.user.uname}</h1>
</body>
</html>
:http://localhost:8080/springmvc03/user.do?method=reg
: