I recently started learning java EE (jsp, servlets and some patterns for working with database like a DAO) and I dont understand where I should initialize my bussines logic? I think that create instances of it in body of do*** servlet methods is a bad practice. P.S. my app use DataSource and ConnectionPool for connection with db.
You need to specify your requirement somehow, what initialization you are looking for. Is it a EJB solution? Pure Servlet/JSP solution? etc.
Normally when deploying your application, after an invocation the application will load the required logic.
Of course you can do initialize to speed up the load, to make required code run before users enter the application etc.
In EJB we are talking about #Singleton and #Startup annotations.
For servlet you can use the annotation #WebServlet(name="startup", loadOnStartup="0"). Or put it in your web.xml. Depends how you code.
A more recommended way is to create you own listener, and override the contextInitialized and contextDestoryed methods. E.g. create db connection etc in initialized method and deregister the driver in contextdestory method. Use annotation #WebServletContextListener or add the listener to your web.xml
Also Java web server specific solutions exists, you need to check your vendor.
Related
I am working on a Tomcat application which populates a HashMap on startup. I set it in the ServletContext using ServletContext.setAttribute. However, I have some non Java EE classes also in this application (basically my webservice calls call those methods). I want to access this HashMap in those Methods. What is the best way to do it?
Your web service should have access to HTTP Request and Response where you can get ServletContext. When web services call these non J2EE methods, you can pass the map as a argument parameter.
Fetch the HashMap in your web service class and pass on the same as method argument to your non Java EE classes.
You can make your map available to all classes of your application:
Using a Singleton
See What is an efficient way to implement a singleton pattern in Java?
Using Tomcat global JNDI tree (not recommended, but you can do it).
See How do you save name-value pairs in Tomcat environment? and Apache Tomcat 7 - JNDI Resources HOW-TO
Thank you all for the suggestions. However what I was trying to achieve was achieved by the following example:
http://www.xinotes.net/notes/note/1772/
It gave me a method to retrieve the context in non-Tomcat handled classes.
Is it possible to inject a bean from a web application that deploy in another server!
I declare a scenario to myself, I have two web application that use spring framework and deploy separately in different application servers (one is TOMCAT and another one is WEBLOGIC),the first application has ServiceA and the second one has ServiceB, now I want to inject ServiceB in ServieA?
I try to do this with RMI once an another one with JMS, now I am wondering that:
Is it possible with another thing?
Is there any active project about this scenario exist?
How can share application context in spring framework, is it possible?
Thanks.
Bean is just an object in JVM. You certainly cannot use an object from one JVM in another JVM straightforward.
But you can do 2 things:
Use proxies - some objects that will have the same interface but invoke somehow to the proper server as implementation.
Use service-oriented architecture (SOA). Each server should have some limited set of beans that are responsible for their functionality. And all beans can interact with each other.
Maybe OSGI is suitable for this.
Web services, JAX-RS is the simplest. But JAX-WS provides you with the tools to automatically generate the client code.
I need to execute some code after the start of the application server (JBoss).
I googled the annotations #startup and #create that might prove useful, but in this situation seems impossibile to operate with EntityManager or Hibernate current session (if using Hibernate).
Is there any chance to perform Hibernate operation immediately after JBoss is started?
Are you using a framework? If not, you could use a startup servlet. In your web.xml, simply mark the servlet to have a <load-on-startup> value and it will run when the webapp is started. If you want it to load after other servlets, just set the load order.
If you are using a framework, it will have its own methodologies, such as Spring's InitializingBean interface.
You could deploy a custom JBoss service or just use plain old portable ServletListener in a war.
I have a service where I want to maintain data persistence in a mysql db using jdbc. While i have experience building jdbc apps and jax-rs apps in isolation, I've never combined the two. The question is, where does the build up and tear down required for the jdbc-type stuff go? Ordinarily i'd put the build up in a static block, or in a constructor, and id have have a cleanup method that gets called in a finally. this doesnt seem to work in the jax-rs framework- the constructor gets called at every invocation, and there is no place to my knowledge to put any clean up methods. unfortunately, there are sparse examples for combining the two technologies online, something i find surprising. Can you guys help me out?
As a general rule, to do things at the startup and shutdown of your web application, you should create custom ServletContextListeners and list them in your web.xml.
With JDBC resources in a WAR, often times you have your container (e.g. Tomcat, Websphere, etc.) create and manage a connection pool which can be shared with a number of web applications. You would define a resource-ref for a javax.sql.DataSource in your web.xml. Then there is a container specific method for defining and binding the JDBC DataSource to the resource-ref of your application.
I'm not familiar with Memchached and what is needed on startup/shutdown so this is only a guess. If you need to register/unregister with a Memcache server you might try having one or more env-entry tags defined in your web.xml which could be used by a custom ServletContextListener to do your bidding.
Correct me if anything is wrong.
As I understand, all Spring functionality, namely DI works when beans are got thru
Spring Context, ie getBean() method.
Otherwise, none can work, even if my method is marked #Transactional and I will
create the owning class with a new operator, no transaction management will be provided.
I use Tomcat 6 as a servlet container.
So, my question is: how to make Servlet methods managed by Spring framework.
The issue here is that I use a framework, and its servlets extend the functionality of
basic java Servlets, so they have more methods. Still, web.xml is present in an app as usual.
The thing is that I do not control the servlets creation flow, I can only override a few methods
of each servlet, the flow is basically written down in some xml file, but I control this process
using a graphical gui.
So, basically, I only add some code to a few methods of each Servlet.
How to make those methods managed by Spring framework? The basic thing I need to do is
making these methods transactional (#Transactional).
comment to Bozho:
#Bozho Let's see. In these servlets' methods I work with framework capabilities, let's say special variables that are got and saved in the current session. And what is needed, is looping through those framework-based collections while saving some values in a database. What you suggest is introducing a new very complex object, so that it could be passed to a service layer. (Service layer will not know anything about framework, its classes and objects kept in current Session! First, we "wrap" framework based collections to such a object, so copy everything into it. Then, again, the Service layer method should either save changes in a database or, worse case, return a new complex object so that Servlet framework method could update framework variables depending on the result of Service layer method execution. It is a workaround but do you think it is a good idea?
You can also define your servlets directly in the Spring application context. You'll need a "proxy" servlet registered in web.xml and delegating to the servlet instance which is configured as bean in the applicationContext.xml. Proxy servlet is configured with the name of the target servlet bean, it discovers this bean via WebApplicationContextUtils.getRequiredWebApplicationContext().getBean(...) and delegates all the processing to the target servlet. In this case an instance of your servlet is completely managed by Spring.
I'd suggest restructuring your code - making servlet methods transactional is not a good thing to do. Put the transactional logic in a separate, service class, and either
obtain these spring-managed classes by WebApplicationContextUtils.getRequiredWebApplicationContext().getBean(..) or
in your servlet init() method obtain the ApplicationContext with the above method and call appCtx.getAutowireCapableBeanFactory().autowireBean(this). This way you can inject the transactional classes in your servlet as if it was spring-managed.
Now, you can do all this, but it is definitely not a beautiful way to go. I'd suggest using Spring MVC or any other MVC framework (which support spring integration of its components)
If this is all not possible, as a last resort I think you can use #Configurable (on your servlets) with a <context:load-time-weaver/>.
You should take a look how Spring proxy filters:
http://grepcode.com/file/repository.springsource.com/org.springframework/org.springframework.web/3.0.2/org/springframework/web/filter/DelegatingFilterProxy.java
In theory you could easily make the same sort of proxy for servlets and DispatcherServlet is sort of a proxy.