instantiate model object in jsp web project - java

Im writing an web application using the MVC design pattern.. the application should connect to a RMI server providing the business part (Model)
my problem is, I dont know where i should instantiate the model class and connect to the RMI, providing access to all servlets.. i added a ServletContextListener and shared the reference on the servlet context, but i dont think that is the right way to do it
thanks in advance

You can instantiate your Model/Business classes from your Controller. Better still make a single instance (Just Create One) of each in the start of the application. You can also go lazy-loading about it.
Instantiating Model/Business classes from your JSPs means, instantiating them from View. That, of course, violates the MVC pattern.
Either you can make your Model/Business classes as Singleton, or keep the reference in Servlet Context. Both are fine and the latter is more test friendly. The former can be made test friendly too, if you don't specify the constructor as private but just have a common understanding that it's not there for instantiating it everywhere.

Related

Is there a way to get the name of web application without using Servlet features?

I'm using Tomcat as the application server, and have 4 web applications running on it. Due to some common requirements across the web applications, I have developed a library which is put in Tomcat's lib folder for sharing the implementation to the web applications. However, I want to implement some resource management features on the library, such as to create and manage singleton resources to each of the web applications (that is, one web application gets one singleton resource). What I suppose to do so is to manage a ConcurrentHashMap and stores each of the singleton resources in it. However, when a web application calls the library for accessing its resource, I need to get the name of the web application which the caller belongs to so I can return the right resource to the caller. Is there a good way to implement things like this (ways that the application don't need to pass parameters or identifications while calling the library to get resource is preferred)? Or it's just a wrong way to think like this, and there is a better solution?
Many thanks!
IMHO, what you describe is not a java singleton pattern, since you want one object per web application. In fact, I think you need one of those objects per ServletContext. I cannot understand why you do not want to use Servlet features, because the right way to do that is to use a ServletContextListener in each web app (it can be the same class) that creates your singleton resources (can also be common classes) and put them as attributes in the ServletContext (exactly one per web application).
The ServletContext attributes are then easy to use from any servlet (request.getSession().getServletContext().getAttribute("attribute_name") or jsp (<jsp:useBean id="attribute_name" scope="application" type="..."/> and then ${attribute_name})

How to design utility webservices consumer class(es)

In a java project i need to call (lets say generic, utility) web services. For instance giving a city code as parameter and getting details about that city. Web services are already implemented and i can only consume them.
I had the same situation before in another project and created a class for that kind of webservices. That class had several web service call methods and all were static methods.
Now, i dont really want to do same thing again because i dont think thats the right way to do it (hard to debug etc). I also dont want to make a different class for all these methods and make an instance for each call because they are too generic and instantiation seems like an overhead for that situation.
So, alternatives comes to my mind is
Using old method. One static class, several methods.
Singleton class. Most probably will have syncronisation problems, so will have overhead using locking mechanisms.
Both are not the best solutions what would you suggest?
Thanks in advance.

Troubles with HTTP-MMO game in Java

I'm about to write a MMO, using HTTP-requests that are responsed with JSON.
I was writing it all in Java EE-style, hoping it won't be hard to port to Java EE than. But then I've found out that my static instance variables for a couple of sinletons weren't created properly - classloader made a bunch of them when calling SingletonClass.getInstance() from servlets.
I was totally desperate and thought adding #Singleton descriptions would help. But things weren't so easy. My classes simply not working while adding them with #EJB ClassName var. Context lookup doesn't work either.
I was trying developing in Eclipse, NetBeans, used Glassfish, tried to set it up, but nothing really helped. I do not know what to do and really desperate now.
All I need is just few classes, that work all the time application is loaded to handle game events and hold logged users data (which is distributed in non-EJB objects that hold user data, monsters and so on), some timed events for each logged user and ability to respond to HTTP POST requests with JSON. I even do not need the ORM, I wrote all queries by myself, but still... Something that had to work simply doesn't work out.
I'm aware that all that sounds messy and non-informative, but I do not know what to do - where is my problem? Maybe, I should fill web.xml, or use different port, or fly to the moon? Or just change programming language? Sorry for your time spent reading this.
UPD. Some application scheme parts. First two from package "server".
#Startup
#Singleton
public class DbWrapper
handles all database connections, DbConnectionPool is non-singleton class, which handles pool of java.sql.Conneciton.
#Startup
#Singleton
#DependsOn("DbWrapper")
public class World
is yet another class to handle all the in-game events, that holds HashMap of logged users. User and Monster classes are from package "entities" (User holds a list of monsters).
Package "servlets" hold HttpServlet descendants, annotated #WebServlet("/pathname"), that try to use
#EJB World world
for example. But such things as world.getUser(id_user) simply won't work.
As for JDBC - postgres jar is included in GlassFish domain's /lib.
As for JSON - I use org.json found here: https://github.com/douglascrockford/JSON-java
I've found out that my static instance variables for a couple of singletons weren't created properly - classloader made a bunch of them when calling SingletonClass.getInstance() from servlets.
First, you should show us the code for one of these singleton classes. You may have made a mistake in the implementation that causes this problem.
It is true that you can get what appear to be multiple instances of a (properly implemented) singleton class in a servlet framework. But in fact they are not what they appear to be. What is actually going on is that you have loaded the class from multiple classloaders, either because you have multiple webapps each loading the class, or because you are redeploying your webapp and the previous deployment is not clearing up properly.
So what can / could you do about this?
You could use a dependency injection framework to configure your webapp, and hence avoid the need for singleton classes.
You could continue using singletons, but track down why you are getting multiple instances, and fix that problem.
You should use singletons really rarely (best would be not to use them). As an alternative use application scoped beans (#Singleton beans should normally work - they should use instance variables though, not static ones).
With Java EE 6 you also can use CDI and thus you don't have to use EJBs if you don't need the additional features they provide (like automatic transaction demarcation, security etc.) or can live with adding those features yourself.
Additionally, you can use CDI in a SE application. Keep in mind though, that you need to define the scope for CDI beans (e.g. #Application, #Request etc.) otherwise the default scope (#Dependant) is used which causes the beans to be copied on every access.

Spring framework best practices: deploying a non-bean compliant component

I want to build an MVC app using Spring (first timer here).
As such I want to embed Jetty as the servlet engine. Jetty however doesn't stricly follow the java beans pattern, so I can't launch some classes from Spring (they use overloaded setters or non setter init methods like addXYZ).
What is the accepted/recommended practice for structuring this project? Obviously all my code fits nicely in the MVC model, but for Jetty:
Do I encapsulate all of Jetty (or any
other non-bean friendly component) in
my own Spring-friendly bean?
Do I try to instantiate as much of it as
possible in spring and just extend
classes that aren't bean con-formant
to make them act like proper beans?
Is there
another option?
Generally speaking, I'm for the 2nd point - i.e. try to use spring utilities like factory-method, init-method, <constructor-arg> and things like that to overcome the fact that something is not entirely spring-friendly. It is rarely the case that it's impossible to configure beans with spring. And for the cases when it is impossible, create wrappers
You can also instantiate the 3rd party beans programatically:
via a FactoryBean
via JavaConfig

How should each class in an application retrieve the Spring application context?

How should each class in an application retrieve the Spring application context? Or, stated another way, how many times should an application invoke new ClassPathXmlApplicationContext("applicationContext.xml")?
Usually a class does not need the application context, but it needs some of the objects Spring injects. And this is configured in that applicationContext.
As such an application typically calls new ClassPathXmlApplicationContext("applicationContext.xml") only once.
With dependency injection, you shouldn't have to, in general. But if your class really needs to be aware of the application context, implement the ApplicationContextAware interface. Spring will automatically call the setApplicationContext method defined in that interface to provide your class with the application context.
Note that if you're trying to gain access to filesystem resources, you should use ResourceLoaderAware. If you want access to the message source, then don't implement an interface; instead, inject a reference to the MessageSource bean.
I think you should take the advice from the answer to your other question here. Implementing ApplicationContextAware or ServletContextAware (if you are in a servlet container) is the best way to get the context.
Look up how spring handles Dependency Injection or Inversion of Control.
Once.
Actually you should let Spring do the heavy lifting and build/configure the classes rather than the other way around.
The whole idea is that all classes can be built without having to call the outside world for dependencies, which are 'magically' provided by the Spring framework.
This approach was invented to get away from the ServiceLocator pattern to which you are alluding, i.e. get a reference to an object to get the dependencies you need, ala JNDI.

Categories

Resources