📅  最后修改于: 2020-12-04 08:27:19             🧑  作者: Mango
在Spring MVC中,模型工作的容器包含应用程序的数据。在这里,数据可以采用任何形式,例如对象,字符串,数据库中的信息等。
需要将Model接口放置在应用程序的控制器部分中。 HttpServletRequest对象读取用户提供的信息,并将其传递给Model接口。现在,视图页面可轻松访问模型零件中的数据。
Method | Description |
---|---|
Model addAllAttributes(Collection> arg) | It adds all the attributes in the provided Collection into this Map. |
Model addAllAttributes(Map |
It adds all the attributes in the provided Map into this Map. |
Model addAllAttribute(Object arg) | It adds the provided attribute to this Map using a generated name. |
Model addAllAttribute(String arg0, Object arg1) | It binds the attribute with the provided name. |
Map |
It return the current set of model attributes as a Map. |
Model mergeAttributes(Map< String,?> arg) | It adds all attributes in the provided Map into this Map, with existing objects of the same name taking precedence. |
boolean containsAttribute(String arg) | It indicates whether this model contains an attribute of the given name |
让我们创建一个包含用户名和密码的登录页面。在这里,我们使用特定的值来验证密码。
org.springframework
spring-webmvc
5.1.1.RELEASE
javax.servlet
servlet-api
3.0-alpha-1
在这里,我们创建登录页面以接收用户的名称和密码。
index.jsp
在控制器类中:
HelloController.java
package com.javatpoint;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class HelloController {
@RequestMapping("/hello")
public String display(HttpServletRequest req,Model m)
{
//read the provided form data
String name=req.getParameter("name");
String pass=req.getParameter("pass");
if(pass.equals("admin"))
{
String msg="Hello "+ name;
//add a message to the model
m.addAttribute("message", msg);
return "viewpage";
}
else
{
String msg="Sorry "+ name+". You entered an incorrect password";
m.addAttribute("message", msg);
return "errorpage";
}
}
}
web.xml
SpringMVC
spring
org.springframework.web.servlet.DispatcherServlet
1
spring
/
spring-servlet.xml
要运行此示例,以下视图组件必须位于WEB-INF / jsp目录中。
viewpage.jsp
${message}
errorpage.jsp
${message}
输出: