我试图从 Controller 返回一个简单的字符串“HelloSpring”到jsp。 Controller 是
package it.polito.ai.e4;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.portlet.ModelAndView;
@Controller
public class HelloSpringController
{
@RequestMapping("/hello")
public ModelAndView helloSpring(HttpServletRequest request,
HttpServletResponse response)
{
String message = "HelloSpring";
return new ModelAndView("hello", "message", message);
}
}
jsp是
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Hello page</title>
</head>
<body>
<%=(String)request.getAttribute("message")%>
</body>
</html>
当我在 Tomcat 7 上执行此操作时,我在页面主体上得到“null”字符串。我的 web.xml 是
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
<display-name>ai4</display-name>
<servlet>
<servlet-name>ai4</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>ai4</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
最佳答案
尝试导入org.springframework.web.servlet.ModelAndView
而不是org.springframework.web.portlet.ModelAndView
。 :)
此外,正如 Sumit Desai 提到的,自 Spring 3 以来,大多数人都这样编写 Controller 方法:
@RequestMapping("/hello")
public String helloSpring(Model m)
{
m.addAttribute("message", "HelloSpring");
return "hello";
}
这只是风格,而且你所做的也很有效。希望有帮助。
关于java - ModelAndView对象未返回到jsp,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10621717/