【问题标题】:Accessing Spring beans from jsp从 jsp 访问 Spring bean
【发布时间】:2013-04-05 09:44:22
【问题描述】:

我正在学习 Spring 课程,我的 Spring MVC 程序在 jsp 页面上打印标准的“Hello World”消息。我正在使用 eclipse 3.6 和 GlassFish 3.1 从 IDE 中运行应用程序。以下是相关文件:

controller.HelloWorldController.java

package controller;

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


@Controller
public class HelloWorldController {

      @RequestMapping("/helloworld")
      protected ModelAndView HelloWorld() throws Exception {
        String hello = "Hello World! My First Web App Using Spring MVC.";
        return new ModelAndView("helloworld","hello",hello);

      }

}

Dispatcher servlet 配置文件:dispatcher-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">

   <context:component-scan
        base-package="controller" />        

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

</beans>

应用程序的入口点:index.jsp

<%@page contentType="text/html" 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>My First Web Application Using Spring MVC</title>
  </head>
  <body>
    <h3><a href="helloworld.htm">Greet the World!</a></h3>
  </body>
</html>

helloworld.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!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=ISO-8859-1">
<title>My First Web Application Using Spring MVC</title>
</head>
<body>
     ${hello}
</body>
</html>

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" id="WebApp_ID" version="3.0">

  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/dispatcher-servlet.xml</param-value>
  </context-param>
  <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
  <display-name>FirstWebAppUsingSpringMVC</display-name>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>

  <servlet>
    <servlet-name>dispatcher</servlet-name>
     <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>

  <servlet-mapping>
    <servlet-name>dispatcher</servlet-name>
      <url-pattern>*.htm</url-pattern>
  </servlet-mapping>
  <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
</web-app>

并在http://localhost:8080/FirstWebAppUsingSpringMVC/helloworld.htm.上成功输出

我很好奇 Spring bean 是否可以从 jsp 访问(谷歌搜索并在网络上做了一些这方面的研究)并且很惊讶它们确实可以做到(由 Spring 设计师以exposedContextBeanNames 的形式提供和exposeContextBeansAsAttributesInternalResourceViewResolver 的属性)。

[侧边栏] 我知道这个网站已经有很多关于这个主题的问题。我已经经历了一些我认为可以帮助我解决问题的方法,但没有。所以,请原谅我问的很明显!
[/sidebar]

所以,为了实现exposedContextBeanNames 属性,我修改了

controller.HelloWorldController.java

package controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;
import service.HelloWorldService;

    public class HelloWorldController extends AbstractController {
            //property helloWorldService that  references Service bean HelloWorldService
        private HelloWorldService helloWorldService;

            //defined handleRequestInternal method of the AbstractController class
            //that returns a new ModelAndView object
            //Instance of ModelAndView adds logical viewName and model data as arguments
        @Override
        protected ModelAndView handleRequestInternal(HttpServletRequest request,
        HttpServletResponse response) throws Exception {
        // TODO Auto-generated method stub
        //view passed as string to new ModelAndView object
        ModelAndView mv = new ModelAndView("helloworld");
            //instance of Service class accessing its object dispMessage()
            mv.addObject("helloworld", helloWorldService.dispMessage());
            return mv;
        }

            //generate setter and getter for the property
            //implicitly injecting business component within Controller
        public void setHelloWorldService(HelloWorldService helloWorldService) {
            this.helloWorldService = helloWorldService;
        }

        /**
         * @return the helloWorldService
         */
        public HelloWorldService getHelloWorldService() {
            return helloWorldService;
        }        
    }

Dispatcher servlet 配置文件:dispatcher-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">

<!-- defined handler to map url pattern to Controller bean on the basis of controller class -->
<bean id="controllerclasshandlermapping"
    class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping">
</bean>

<!-- defined view resolver to resolve Controller class HelloWorldController to helloworld.jsp -->
   <bean id="viewResolver"
          class="org.springframework.web.servlet.view.InternalResourceViewResolver"
          p:prefix="/WEB-INF/jsp/"
          p:suffix=".jsp">
<!-- exposing Controller bean helloWorldController to the view  -->
          <property name="exposedContextBeanNames">
            <list>
             <value>helloWorldController</value>
            </list>
          </property>    
    </bean> 

<!-- Explicit mapping to Controller bean helloWorldController which references Service bean thru its property
       from the applicationContext.xml -->
    <bean id= "helloWorldController"
      class="controller.HelloWorldController" p:helloWorldService-ref="helloWorldService"/>
</beans>

helloworld.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!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=ISO-8859-1">
<title>My First Web Application Using Spring MVC</title>
</head>
<body>
     <!--${beanName.beanProperty}-->
     ${helloWorldController.helloWorldService}
</body>
</html>

web.xml

<context-param>
    <param-name>contextConfigLocation</param-name>
    //changed path to applicationContext.xml to reference Service class
    <param-value>/WEB-INF/applicationContext.xml</param-value>
  </context-param>

并介绍

service.HelloWorldService.java(服务 bean)

package service;

public class HelloWorldService {

    public String dispMessage() {
        String msg = "Hello World! My First Web App Using Spring MVC.";
        return msg;
    }
}

applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans  
       http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
       http://www.springframework.org/schema/aop http://www.springframework.org/schema
       /aop/spring-aop-3.0.xsd
       http://www.springframework.org/schema/tx http://www.springframework.org/schema
       /tx/spring-tx-3.0.xsd">

    <!--Service bean defined-->
    <bean name="helloWorldService" class="service.HelloWorldService"/>
</beans>

但是,在运行项目时,http://localhost:8080/FirstWebAppUsingSpringMVC/helloworld.htm 上的输出是

service.HelloWorldService@bf12af34

为什么没有显示“Hello World”消息?我哪里出错了??........一直在尝试解决这个问题,但无法找到解决方案。

非常感谢论坛成员/专家能帮助解决这个问题。

谢谢 用户1586954

【问题讨论】:

  • 看起来 toString() 正在你的 helloWorldService 上被调用,所以你只是得到了对象表示,因为你还没有实现 toString。但你实际上是在访问它看起来的 bean。这是否是一个好主意是另一回事....

标签: spring model-view-controller


【解决方案1】:

编辑评论为时已晚,所以这里有一个答案。

看起来 toString() 正在你的 helloWorldService 上被调用,所以你只是得到了对象表示,因为你还没有实现 toString。但你实际上是在访问它看起来的 bean。

这是否是一个好主意是另一回事。

最好只使用模型将数据返回到视图(您已经在这样做)所以这在您的 JSP 中就足够了:${helloworld}

【讨论】:

  • 感谢您的回复!我在哪里实现 toString?使用 ${helloworld} 对我有用。我知道将业务组件暴露给视图是值得商榷的,但尝试实现相同的只是为了学习目的。谢谢
  • 很公平。我要说的是 ${helloWorldController.helloWorldService} 将调用 HelloWorldService.toString();如果您想直接调用 HelloWorldService 上的方法,您有几个选项,具体取决于您使用的 Spring、JEE 和 Web 服务器的版本。看看 jspx 或 Spring el(或者干脆不做!):-)
猜你喜欢
  • 1970-01-01
  • 2014-10-17
  • 1970-01-01
  • 2011-02-20
  • 1970-01-01
  • 1970-01-01
  • 2017-03-01
  • 2016-11-24
  • 1970-01-01
相关资源
最近更新 更多