使用Spring @Controller ModelAndView将java变量传递给jsp

时间:2015-06-30 15:21:50

标签: java spring jsp spring-mvc modelandview

控制器类看起来像这样,

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.bind.annotation.RequestMethod;


@Controller
public class MainController {
    @RequestMapping(value = "/chart", method = RequestMethod.GET)
    public ModelAndView helloWorld() {
        System.out.println("Controller accessed...");
        String message = "<br><div style='text-align:center;'> CONTROLLER ACCESSED</div><br><br>";
        return new ModelAndView("chart", "hello", message);
    }
}

我的jsp文件,名为&#34; chart.jsp&#34;看起来像

<html>
<head>
<title>Spring MVC - Chart
    Example</title>
</head>
<body>${hello}

    <br>
    <br>
    <div style="font-family: verdana; padding: 10px; border-radius: 10px; font-size: 12px; text-align:center;">

        Insert Chart here. ${hello}<br>
    </div>
</body>
</html>

我现在的问题是&#34; $ {hello}&#34;在.jsp文件中保持为&#34; $ {hello}&#34;而不是我在index.jsp中提供的字符串。

此外,访问控制器是因为println在控制台上成功打印。

增加: web.xml看起来像这样,因为它可能是问题的原因。

<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
    <display-name>Web Application</display-name>
    <!-- Processes application requests -->
    <!-- <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/spring-context.xml</param-value>
    </context-param> -->

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <servlet>
        <servlet-name>appServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>

        <load-on-startup>1</load-on-startup>
    </servlet>        

    <servlet-mapping>
        <servlet-name>appServlet</servlet-name>
        <url-pattern>/chart.jsp</url-pattern>
    </servlet-mapping>  

    <servlet-mapping>
        <servlet-name>appServlet</servlet-name>
        <url-pattern>/chart.html</url-pattern>
    </servlet-mapping>

    <servlet-mapping>
        <servlet-name>appServlet</servlet-name>
        <url-pattern>*.html</url-pattern>
    </servlet-mapping>
</web-app>

1 个答案:

答案 0 :(得分:2)

将此行添加到顶部的jsp,这样就可以了。 (为看起来相似的人添加答案)

<%@taglib uri="springframework.org/tags/form"; prefix="form"%>