0

I'm building a small webapp with some global variables (some are application-scoped, some are session-scoped). There are multiple JSPs, servlets and HTML files, all of which need access.

  1. How do I initialize such a variable from my class myObject? I would need to use the appropriate constructor from the class definition. According to an answer here, I shouldn't/can't use <%! %> in a JSP page. Is it possible to use <c:set > from JSTL?
  2. One possible way to use the global variable in a servlet is to use request.getSession().getAttribute("myObjectName"). But since this always returns an Object, I'll have to cast it every time before I can use myObject's methods. Is it possible to do this in a simpler fashion?
Community
  • 1
  • 1
typesanitizer
  • 2,505
  • 1
  • 20
  • 44

2 Answers2

1

You can use a JavaBeans component using either one of the following formats:

<jsp:useBean id="beanName" class="fully_qualified_classname" scope="scope"/> 

or

<jsp:useBean id="beanName"
  class="fully_qualified_classname" scope="scope">
  <jsp:setProperty .../>
</jsp:useBean> 

and use c:set to set the properties of the bean.

Use JavaServer Pages Standard Tag Library or Expression Language to call any method of the bean.

It's better to move the business logic inside the Servlet and call it from JSP as simple as it is. Don't perform any calculation other than UI in jsp.

Braj
  • 46,415
  • 5
  • 60
  • 76
  • I looked at beans earlier but I didn't think they would serve my purpose. Using a bean will allow me to only use `get` and `set` operations, but what if I want more functionality? For e.g., I might want to perform an arbitrary method `foo` on some `myObject`. Or even `Foo` on fields of `myObject`. – typesanitizer Aug 23 '14 at 11:53
  • Also, in this [answer](http://stackoverflow.com/a/3295540) describing what a bean does, it clearly states that a bean's fields must be primitive types or serializable, which is certainly not the case with `myObject` class in general. So I would end up making beans for all subclasses which are not primitive types, correct? That would be a very time-consuming approach, even if I managed to do it. – typesanitizer Aug 23 '14 at 12:11
  • use `Expression language` to call the method of the bean. `${beanObj.xyzMethod()}` – Braj Aug 23 '14 at 13:16
  • Okay. Expression language is a good idea, so I've marked answer as approved. But won't I still need to make beans for non-primitive fields? If not, please explain. – typesanitizer Aug 23 '14 at 13:21
1

If I correctly understand, there are different questions :

  • how to access the variables from JSP : user3218114 has allready answered this part, but if you create the variable outside of the JSP, you simply access them with ${bean.property}. Methods are harder to call (again see referenced answer), but if you use servlets, JSP should only be views and you should think twice before calling methods in a JSP.
  • how to access the variables from other beans : you can use Dependancy Injection if you use a true Java EE container (not Tomcat ...) or Spring, and unfortunately there will be slightly difference in the way to use it. But it is really a question on its own and I will not develop this further even if it is to considere for any serious developpement
  • how to access variables from servlets : I only know one way scope.getAttribute("name"), with scope in Request, Session, ServletContext, that return an Object that need to be casted before use ... but you can always use private methods or static utility methods to hide the details, for example :

    public class MyUtil {
        public MyObject getMyObject(ServletRequest request) {
            return (MyObject) request.getAttribute("my_object");
        }
    }
    

    and later in your serlvets or filters you simply call MyUtil.getMyObject(request)

  • how to initialize those scoped variables : Requests and Session scoped variables are generally created in servlets or filters and are simply put as attribute in their scope either directly or through an utility methode like above. Application level beans (ServletContext scope) are generally created outside any request and should be initialized in a ServletContextListener. For special use cases, you can also use a HttpSessionListener to put beans in session context outside of a Servlet.

Edit : just a point about serialization

Request scoped bean do not need to be serializable. For Session or ServletContext scoped beans, the answer is more subtle : if you want your application to be distributable (ie be deployed on a cluster of servers) all attributes put in Session or ServletContext should be Serializable. Nothing forces you to to so, and you will have no errors if you do not, but a container is allowed to serialize a session and all non Serializable attributes are simply thrown away (with a warning for Tomcat). An even in non distributed environments, I noticed that Tomcat serializes sessions when stopping and undeploying a web application, and restores them on next deploy.

So my advice is : all Session or ServletContext scoped beans should be Serializable (and I wrote should not must ...)

Arjan Tijms
  • 37,782
  • 12
  • 108
  • 140
Serge Ballesta
  • 143,923
  • 11
  • 122
  • 252
  • Well, I don't really have point 2 in mind (particularly because I'm not about to stop using Tomcat), 3 confirms my suspicions pointed out in second part of my question. But can you answer whether a bean's non-primitive information/fields will be managed correctly across pages if they are not serializable, i.e., will I have to write beans for them too? – typesanitizer Aug 23 '14 at 14:06
  • As you didn't speak of serialization in your original post, I didn't either in my answer :-) - just edited ... – Serge Ballesta Aug 23 '14 at 14:44
  • Thanks for the clarifying edit. I did not edit the question otherwise the accepted answer would seem incomplete so I asked the point in comments. – typesanitizer Aug 23 '14 at 15:19