ModelAndView中的源码
时间: 2024-02-28 22:57:52 浏览: 140
wowmodelview 含源代码
以下是Spring Framework中ModelAndView类的源代码:
```java
public class ModelAndView {
@Nullable
private Object view;
private final Map<String, Object> model;
public ModelAndView() {
this.model = new LinkedHashMap<>();
}
public ModelAndView(@Nullable View view) {
this.view = view;
this.model = new LinkedHashMap<>();
}
public ModelAndView(@Nullable String viewName) {
this.view = viewName;
this.model = new LinkedHashMap<>();
}
public ModelAndView(@Nullable View view, @Nullable Map<String, ?> model) {
this.view = view;
this.model = (model != null ? new LinkedHashMap<>(model) : new LinkedHashMap<>());
}
public ModelAndView(@Nullable String viewName, @Nullable Map<String, ?> model) {
this.view = viewName;
this.model = (model != null ? new LinkedHashMap<>(model) : new LinkedHashMap<>());
}
public ModelAndView(@Nullable Object view, @Nullable String modelName, @Nullable Object modelObject) {
this.view = view;
this.model = new LinkedHashMap<>();
addObject(modelName, modelObject);
}
public ModelAndView(@Nullable String viewName, @Nullable String modelName, @Nullable Object modelObject) {
this.view = viewName;
this.model = new LinkedHashMap<>();
addObject(modelName, modelObject);
}
public void setViewName(@Nullable String viewName) {
this.view = viewName;
}
@Nullable
public String getViewName() {
return (this.view instanceof String ? (String) this.view : null);
}
public void setView(@Nullable View view) {
this.view = view;
}
@Nullable
public View getView() {
return (this.view instanceof View ? (View) this.view : null);
}
public void setModel(Map<String, ?> model) {
if (model != null) {
this.model.putAll(model);
}
}
public Map<String, Object> getModel() {
return this.model;
}
public ModelAndView addObject(String attributeName, @Nullable Object attributeValue) {
Assert.notNull(attributeName, "Model attribute name must not be null");
this.model.put(attributeName, attributeValue);
return this;
}
public ModelAndView addObject(Object attributeValue) {
Assert.notNull(attributeValue, "Model object must not be null");
return addObject(BindingResult.MODEL_KEY_PREFIX + this.model.size(), attributeValue);
}
public ModelAndView addAllObjects(@Nullable Map<String, ?> modelMap) {
if (modelMap != null) {
modelMap.forEach(this::addObject);
}
return this;
}
public boolean isEmpty() {
return this.model.isEmpty();
}
public int size() {
return this.model.size();
}
@Nullable
public Object get(String key) {
return this.model.get(key);
}
public boolean containsKey(String key) {
return this.model.containsKey(key);
}
public Set<String> keySet() {
return this.model.keySet();
}
public ModelAndView clear() {
this.view = null;
this.model.clear();
return this;
}
@Override
public String toString() {
return "ModelAndView [view=" + this.view + ", model=" + this.model + "]";
}
}
```
该类主要用于封装视图和模型,其中视图可以是View类型的对象或视图的名称,模型则是一个Map类型的对象,用于存储视图所需的数据。除此之外,该类还提供了一些方法来设置和获取视图和模型,以及添加、删除、清空模型数据等。
阅读全文