modelandview.addobject
时间: 2023-03-16 12:50:42 浏览: 139
ModelAndView.addObject() 方法是 Spring MVC 框架中用于向视图添加模型数据的方法。它接受两个参数:一个是模型属性的名称,另一个是模型属性的值。添加的数据可以在 JSP 页面中使用 EL 表达式访问。
相关问题
modelandview.addobject()
In Spring MVC, the `ModelAndView` class is used to pass data between the controller and the view. The `addObject()` method is used to add an object to the model, which can then be accessed by the view.
The `addObject()` method takes two parameters: a `String` key and an `Object` value. The key is used to identify the object in the model, and the value is the object that is added to the model.
For example, suppose we have a controller method that retrieves a list of products and adds it to the model:
```
@RequestMapping("/products")
public ModelAndView getProducts() {
List<Product> products = productService.getAllProducts();
ModelAndView modelAndView = new ModelAndView("products");
modelAndView.addObject("products", products);
return modelAndView;
}
```
In this example, we create a new `ModelAndView` object with the view name "products". We then add the list of products to the model using the key "products". This means that in the view, we can access the list of products using the key "products":
```
<c:forEach var="product" items="${products}">
<tr>
<td>${product.name}</td>
<td>${product.price}</td>
</tr>
</c:forEach>
```
Here, we use the `c:forEach` tag from the JSTL to loop through the list of products and display their names and prices in a table. We access the list of products using the key "products", which was added to the model in the controller method.
@RequestMapping("/toLogin") public ModelAndView toLogin(User user){ User u = userService.login(user.getUsername(),user.getPassword()); ModelAndView modelAndView = new ModelAndView(); System.out.println(u); //是否能得到一个u,决定是否登录成功 if (u!=null) { //将user存进session中 modelAndView.addObject("user",u); modelAndView.setViewName("index"); }else { modelAndView.addObject("error","账号或密码错误!"); modelAndView.setViewName("login"); } return modelAndView;将这段代码改成查看用户名错误还是密码错误
要将这段代码改成分别查看用户名错误和密码错误,可以在 `UserService` 中添加两个方法,分别用于根据用户名和密码查询用户信息。修改后的代码如下:
```
@RequestMapping("/toLogin")
public ModelAndView toLogin(User user){
User u = userService.getUserByUsername(user.getUsername());
ModelAndView modelAndView = new ModelAndView();
System.out.println(u);
//判断用户名是否存在
if (u == null) {
modelAndView.addObject("error","用户名不存在!");
modelAndView.setViewName("login");
return modelAndView;
}
//判断密码是否正确
u = userService.getUserByUsernameAndPassword(user.getUsername(), user.getPassword());
if (u!=null) {
//将user存进session中
modelAndView.addObject("user",u);
modelAndView.setViewName("index");
}else {
modelAndView.addObject("error","密码错误!");
modelAndView.setViewName("login");
}
return modelAndView;
}
```
其中,`getUserByUsername` 方法用于根据用户名查询用户信息,如果用户不存在,则返回 null;`getUserByUsernameAndPassword` 方法用于根据用户名和密码查询用户信息,如果用户不存在或密码不正确,则返回 null。