gpt4 book ai didi

java - ModelAndView 对象未返回到 jsp

转载 作者:行者123 更新时间:2023-11-30 07:25:56 28 4
gpt4 key购买 nike

我正在尝试从 Controller 向 jsp 返回一个简单的字符串“HelloSpring”。 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 上执行此操作时,我在页面正文中得到“空”字符串。我的 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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com