ModelAndView对象未返回到jsp [英] ModelAndView object not returned to jsp

查看:197
本文介绍了ModelAndView对象未返回到jsp的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从控制器向jsp返回一个简单的字符串"HelloSpring".控制器是

I am trying to return a simple String "HelloSpring" from controller to jsp. Controller is

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是

When I execute this on Tomcat 7 I get "null" string on page's body. My web.xml is

<?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. :)

Try importing org.springframework.web.servlet.ModelAndView instead of org.springframework.web.portlet.ModelAndView. :)

而且,正如Sumit Desai提到的那样,自春季3以来,大多数人都这样编写控制器方法:

Also, as Sumit Desai mentioned, since Spring 3, most people write their controller methods like this:

@RequestMapping("/hello")
public String helloSpring(Model m)
{
    m.addAttribute("message", "HelloSpring");
    return "hello";
}

这只是样式,您所做的也行得通.希望有帮助.

It's just style, and what you've done works too. Hope that helps.

这篇关于ModelAndView对象未返回到jsp的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆