简体   繁体   中英

Passing java variables to jsp with Spring @Controller ModelAndView

The controller class looks like this,

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);
    }
}

My jsp file, named "chart.jsp" looks like

<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>

My problem now is that both "${hello}" in .jsp file stays as "${hello}" rather than the string I gave in index.jsp.

Also, the controller is accessed because the println printed successfully on the console.

ADDED: The web.xml looks like this as it could be the cause of the problem.

<!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>

add this line to jsp on top this will do the trick. (adding as an answer for someone looking similar)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM