我试图从控制器返回一个简单的字符串“ HelloSpring”到jsp。控制器是
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。:)
org.springframework.web.servlet.ModelAndView
org.springframework.web.portlet.ModelAndView
另外,就像Sumit Desai提到的那样,从Spring 3开始,大多数人都这样编写控制器方法:
@RequestMapping("/hello") public String helloSpring(Model m) { m.addAttribute("message", "HelloSpring"); return "hello"; }
这只是样式,您所做的也行得通。希望能有所帮助。