Spring MVC - Model对象无法从controller-JSP返回视图

时间:2016-09-28 08:27:03

标签: java spring jsp spring-mvc

我正在spring mvc中编写一个简单的hello world程序,我将一个对象传递给视图。 JSP页面正常打开,但它没有获得在控制器中设置的值,并且eclipse控制台中没有错误。这是我的代码

@Controller
public class CncController {
String message = "Welcome to Spring MVC!";

@RequestMapping("/hello")
public ModelAndView showMessage(
        @RequestParam(value = "name", required = false, defaultValue = "World") String name) {
    System.out.println("in controller");

    ModelAndView mv = new ModelAndView("helloworld");
    mv.addObject("welcomeMessage", "Welcome to first page");
    System.out.println(mv);
    return mv;
}
}

CNC-调度-servlet.xml中

   <beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/mvc        http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
                http://www.springframework.org/schema/tx    http://www.springframework.org/schema/tx/spring-tx-3.1.xsd     
                http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
                http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd">


<mvc:annotation-driven />

<bean id="HandlerMapping" class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"></bean>
<context:component-scan base-package="com.cnc.cnccontroller" />

<bean id="viewResolver"
    class="org.springframework.web.servlet.view.InternalResourceViewResolver" >
    <property name="prefix">
        <value>/WEB-INF/</value>
    </property>
    <property name="suffix">
        <value>.jsp</value>
    </property>
</bean>

</beans>

JSP页面正确放在web-inf文件夹下。

它只是显示

Hello {welcomeMessage}

流程中是否有任何遗漏?

1 个答案:

答案 0 :(得分:0)

您对Model对象的JSP引用应该在${}之内。在您的情况下,它应该是“Hello ${welcomeMessage}