user1586954
user1586954

Reputation: 151

Accessing Spring beans from jsp

I'm doing a course in Spring and my Spring MVC program prints the standard 'Hello World' message on the jsp page. I'm using eclipse 3.6 and GlassFish 3.1 to run the app from within the IDE. Following are the files concerned:

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 config file: 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>

Entry point for application: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>

and gives successful output on http://localhost:8080/FirstWebAppUsingSpringMVC/helloworld.htm.

I was curious if Spring beans could be accessed from the jsp (googled and did some research on the web in this regard) and was surprised that they indeed could be done (as provided by Spring designers in the form of exposedContextBeanNames and exposeContextBeansAsAttributes properties of InternalResourceViewResolver).

[sidebar] I'm aware that this site already has many questions on this topic. I've gone thru a few that I thought would help me resolve my issue but did not. So, please excuse me for asking the obvious!
[/sidebar]

So, to implement the exposedContextBeanNames property, I modified

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 config file: 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>

and introduced

service.HelloWorldService.java (Service 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>

However, on running the project, the output on http://localhost:8080/FirstWebAppUsingSpringMVC/helloworld.htm is

service.HelloWorldService@bf12af34

Why is the 'Hello World' message not displayed? Where have I gone wrong??.......have been trying to work around this but unable to find solution.

Much appreciated if the forum members / experts could help in resolving the same.

Thanks user1586954

Upvotes: 1

Views: 16771

Answers (1)

Mark Chorley
Mark Chorley

Reputation: 2107

Too late to edit the comment so here is an answer of sorts.

It looks like toString() is being called on your helloWorldService so you are just getting the object representation as you haven't implemented toString. But you are actually accessing the bean it seems.

Whether that is a good idea is another matter.

It might be better just to use the Model to return data to the view (which you are already doing) so this should suffice in your JSP: ${helloworld}

Upvotes: 1

Related Questions