I'm using persistence API and want to load jdbc URL from web.xml. URL should be a context parameter of servlet. I can't find how to construct EntityManagerFactory not using persistence.xml. May be I should create PersistenceUnit in servlet and set some parameters? Can you give me some short example?
Thank you
you can use method createEntityManagerFactory(String persistenceUnitName, Map properties) of class javax.persistence.Persistence . and insert all your parameters in the map
I personally find it the cleanest way to define a datasource in the servlet container usng JNDI and refer to that from the persistence.xml.
This also solves one configuration issue when migrating from test-uat-prod as I can use the same datasource name on the machines.
Yeah, I know JNDI is not popular, but this works nice and it avoids having to manipulate hte web.xml which is also wrapped in the war.
Whether you use a datasource or not, the JPA configuration goes in the persistence.xml, not in the web.xml. If you want to use JPA, provide a persistence.xml.
Define an init-param in your web.xml that points to your database url. For example, for MySQL, it would be something like this:
<init-param>
<param-name>DB_URL</param-name>
<param-value>jdbc:mysql:///MY_DB</param-value>
</init-param>
Then get this value inside your Web app (in a Servlet) using something like this:
String myDbUrl = getServletConfig().getInitParameter("DB_URL");
In JSP files you can get the value in this way:
String myDbUrl = config.getInitParameter("DB_URL");
You can retrieve any value from the web.xml by using env-entry
<env-entry>
<env-entry-name>dbUrl</env-entry-name>
<env-entry-type>java.lang.String</env-entry-type>
<env-entry-value>jdbc:url:goes:here</env-entry-value>
</env-entry>
And in java
try {
Context ctx = new InitialContext();
String dbUrl= (String) ctx.lookup("java:comp/env/dbUrl");
//... create your connection
} catch (Exception e ) {
}
Related
I recently saw a post that explained in JAVA EE, instead of using a .properites file, a better way to specify Configuration Properties is in a web.xml file and then injecting them inside the Class where the properties are needed.
This is my Web.xml
<env-entry>
<env-entry-name>pacakageName.ClassName/number</env-entry-name>
<env-entry-type>java.lang.Integer</env-entry-type>
<env-entry-value>123</env-entry-value>
</env-entry>
<env-entry>
<env-entry-name>country</env-entry-name>
<env-entry-type>java.lang.String</env-entry-type>
<env-entry-value>Spain</env-entry-value>
</env-entry>
And in my Java class, when I use the JNDI way I am able to get the value
InitialContext initialContext = new javax.naming.InitialContext();
String countryName = (String) initialContext.lookup("java:comp/env/country");
This works, but when I try to use the new way of using #Resources and injecting the value, the value is not read from the web.xml
#Path("loginService")
public class LoginService{
#Resource() int number;
//constructor and other methods
}
I am using Tomcat 7...Could anyone help me out what I am doing wrong.
I referred this doc:
http://www.oracle.com/webfolder/technetwork/tutorials/obe/java/env_entry/env_entry.html
Your class is not the kind that supports the #Resource annotation. It needs to be a Java EE component, like an EJB for example.
This is because the container is the one that injects the resources, and it only considers components as valid injection targets. Also for this reason the resource must be defined before the container starts, so you can't inject resources that you put into JNDI during runtime.
Make sure you have beans.xml file in WEB-INF folder (this enables CDI) and then change your variable to java.lang.Integer like this:
#Resource(name="pacakageName.ClassName/number")
Integer number;
#Resource(name="country")
String country;
It works fine in Java EE 6 container that supports CDI for example WebSphere Liberty profile
I have a web-app in Java/Java EE deployed on any application server/web server. I would like to get all the datasources configured on this server in my application.
Does anyone have any ideas to achieve it? I can get those through WLST ant tasks. But I need to get them programatically.
If your datasources are configured with JNDI then you can list the context and can get all the names (more from here) with Context.list() method and from those name you can find all the datasources
the Context.list() returns an enumeration of NameClassPair. Each NameClassPair consists of the object's name and its class name. So just iterate it and check the class name for java.sql.DataSource and then get the object name to retrieve it.
With JBoss you can do the following (assuming JMX is available):
Context ctx = new InitialContext();
MBeanServerConnection mconn = (MBeanServerConnection)ctx.lookup("jmx/invoker/RMIAdaptor");
ObjectName name = new ObjectName("jboss.jca:service=DataSourceBinding,*");
Set s = mconn.queryMBeans(name, null);
Where s is an mbeans collection.
I have a project with a few old HTTPServlets, I would like a way to manage the creation/life-cycle of the Servlet in Spring so I can do a few things like DI and pass in database objects through Spring/Hibernate integration.
First I have setup the Spring application context in web.xml as follows;
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
Next I have my servlet definition in web.xml;
<servlet>
<servlet-name>oldHttpServlet</servlet-name>
<display-name>oldHttpServlet</display-name>
<servlet-class>com.package.MyServlet</servlet-class>
</servlet>
In my Spring application-context.xml I would like to make some bean def as follows;
<bean id="oldHttpServlet" class="com.package.MyServlet"></bean>
I think the above I need to implement some interface within my servlet, keep the bean definition as above in the Spring app-context.xml and then make a change to the servlet definition in the web.xml... I'm not sure what is the simplest change to make as there is some inheritance to worry about on the MyServelet.java side, which looks like this;
class MyServlet extends MyAbstractServlet{
void doStuff(){
//YOu know...
}
}
And MyAbstractServlet;
class MyAbstractServlet extends HttpServlet{
doPost(){
//Some post implementation here...
}
}
What is the best way to wrap MyServlet in Spring and have it loaded from there rather than being instantiated via web.xml?
I'm assuming the best way would be to use Springs HttpRequestHandler and then use the HttpRequestHandlerServlet in the web.xml in place of the current servlet. However I'm not sure how I go about implementing the HttpRequestHandler interface to work with the existing doPost() stuff in the myAbstractServlet...
If you need to inject dependencies into a servlet than I would go with Spring's HttpRequestHandlerServlet. You create an implementation of HttpRequestHandler (it has a method:
public void handleRequest(HttpServletRequest request, HttpServletResponse httpServletResponse) throws ServletException, IOException;
that you need to implement - it is the equivalent of what you'd have in a doGet / doPost.
The instance of all your HttpRequestHandler implementatins should be handled by spring (set up an annotation driven config and annotate it with, say, #Component) or use an XML config to set up those beans.
In your web.xml create the mapping for HttpRequestHandlerServlet. If you name the servlet the same as you did your HttpRequestHandler then Spring will make HttpRequestHandlerServlet automatically handle the request with the matching HttpRequestHandler.
Since HttpRequestHandler is a Spring bean, you can make Spring inject all the services you need into it.
If you still do not want to use HttpRequestHandler in lieu of Servlets than all that is left is some "programming judo", like retrieving WebApplicationContext with Spring utils and getting beans from there by a "per name" basis. Servlets are not instantiated by Spring so it cannot manage them. You would have to create a base class for your servlets and manage the DI as an initialization step yourself.
The code would look like this (inside a servlet):
WebApplicationContext webContext = WebApplicationContextUtils.getWebApplicationContext(getServletContext());
CertainBeanClass bean = (CertainBeanClass) webContext.getBean("certainBean");
[EDIT]
Indeed, as one of the commenters suggested, there IS one more option. It still requires you to do a manual setup in your servlets init method though. Here is how this would look like:
public void init(ServletConfig config) {
super.init(config);
SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);
}
You may also try your luck with #Configurable annotation on Servlet with weaving, but this might or might not work (I think Servlet might get initialized before Spring context is set up, so it still won't have the possibility to do its magic).
The ideal use of Servlet should be as Controller and underlying container manages its life cycle so we don't need Spring to manage its instance
so I can do a few things like DI and pass in database objects through Spring/Hibernate integration.
You should never have dependency of Servlet in your dao/services, Your servlet should be calling services which is perfectly suitable to manage with Spring DI context
regarding SpringBeanAutowiringSupport, note from the javadoc:
NOTE: If there is an explicit way to access the ServletContext, prefer such a way over using this class. The WebApplicationContextUtils class allows for easy access to the Spring root web application context based on the ServletContext.
I am writing an application in Java and I have some REST web services there. My application has following structure: http://cl.ly/L7Pv/o
REST web service classes are Stateless session beans. It works like charm. But Classes in red on the picture want to use that REST resources too.
As fas as I know I cannot use dependency injection and annotation #EJB there. I believe I have to use JNDI lookup. Documentation: http://docs.oracle.com/javaee/6/tutorial/doc/gipjf.html
But now I dont know how to write this JNDI lookup. I have tried these two:
context.lookup("java:global/diplomka/ListResource");
context.lookup("java:global/Diplomka_maven/ListResource");
What am I doing wrong? Is this a correct approach in the first place?
Thank you
If these classes (ListResource etc.) are Stateless session beans, you can put attribute name or mappedName in #Stateless annotation, e.g.:
#Stateless(mappedName="ejb/myRestService")
public class ListResource { ..
Once you have specified JNDI name of your stateless bean, it's easy to fetch the bean through JNDI lookup:
InitialContext ic = new InitialContext();
ListResource lr = (ListResource) ic.lookup("ejb/myRestService");
lr.doWhateverNeeded(..);
I have a stateless Bean with following heirarchy and present
accountserver , accountserverBean implements accountserver.
with there corresponding ejb-jar.xml and weblogicjar.xml
Then I have my spring Bean with the following
payload.java with corressponding spring.xml
So Inside the spring libs folder I have added account.jar
So how can I call method present in accountserverBean from payload class????
Also I have used the below Code in payload.java
Context ctx=new InitialContext();
accountserver as=(accountserver)ctx.lookup("java:com/accountserver");
But this doesnt work.
Since both are in same context I can call the EJB method
Please provide me with solution
I guess you want to integrate EJB and Spring applications. Did you try this: http://static.springsource.org/spring/docs/2.5.x/reference/ejb.html ?