How can I Load a class while startup tomcat Server [duplicate] - java

This question already has an answer here:
Using special auto start servlet to initialize on startup and share application data
(1 answer)
Closed 1 year ago.
I would like to load java class file that contain db related function. How can I load that java file while starting the tomcat server

you can use servlet for that as below, define into web.xml
<servlet>
<servlet-name>YourServletName</servlet-name>
<servlet-class>com.abc.xyz.YourServletClassName</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
in YourServletClassName.java file you can write your code.
Hope it helps you.

The answer by Psabuwala is correct but not complete.
Code that will run on startup should be placed in the init method of the servlet.
Web.xml:
...
<servlet>
<servlet-name>mainServlet</servlet-name>
<servlet-class>example.com.MainServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
...
MainServlet.java:
public class MainServlet extends HttpServlet
{
public void init() throws ServletException
{
DataLoader dataLoader = new DataLoader();
dataLoader.load();
}
...
}

Related

In Spring MVC, what is even the purpose of web.xml?

In Spring MVC, people typically build a Dispatcher Servlet that controls the other Servlets. The pipeline includes a request to web.xml which is then routed to a dispatcher of class org.springframework.web.servlet.DispatcherServlet. The URL pattern can be / or *.htm* to ensure that all requests go there.
The question is: in this pattern, what is even the purpose of web.xml? One would think that it is just useless overhead. I mean, if you're not going to use another dispatcher... or are you?
Basically in a regular Java app context will be fetched in some self-created main method, means main method is your starting point. Application will run from the main and will go other methods after.
public class FooClass{
public static void main(String[] args) {
//some code
}
But in the Spring web app,
the starting point is actually web.xml. It start from here, then flow goes to the other defined classes and methods
For example, when you write these codes, you basically give the order to the web application that you should start from here
Kind of you define your starting point. Think that it is main method in normal Java
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring-mvc-validation-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
And in second part you give order to dispatcher that start from here. It means you give a url-pattern -starting point. You can give anything in here but "/" this is the common use
<!-- Step 2: Set up URL mapping for Spring MVC Dispatcher Servlet -->
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
I hope it is clear. Else ask for more explanations.

Java Servlet Web XML URL Mapping

I've been struggling with this web xml file for Tomcat for a while.
<context-param>
<param-name>name</param-name>
<param-value>Bob</param-value>
</context-param>
<servlet>
<servlet-name>test</servlet-name>
<servlet-class>TestServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>test</servlet-name>
<url-pattern>/servlet/*</url-pattern>
</servlet-mapping>
I know that this file is being read because when i test using
public class TestServlet extends HttpServlet{
public void doGet(HttpServletRequest req, HttpServletResponse res){
res.setContentType("text/html");
String name = getServletContext().getInitParameter("name");
PrintWriter out = null;
try{
out = res.getWriter();
}catch(Exception e){}
out.println("<html><head></head><body><img src=\"/twitter.png\"><p>Hi my name is " + name + "</p></body></html>");
}
}
I am able to read the name I put into the context-param. My question for you guys is how do I create a URL mapping such that I do not have to go through /servlet/ to access my servlets in the URL? When I try to make a url-pattern such as
/test/*, i cannot access the servlet even if i say website/test/TestServlet. I get a 404 Not Found error from the browser
Put the servlet class in a package and do not rely on InvokerServlet. It's disabled since Tomcat 5.5 and removed in Tomcat 7.0.
Please do not read 10~15 year old tutorials/books. Technology changes every year.
See also:
How to invoke a servlet without mapping in web.xml?

How to initialize Java EE 5 JAX-WS 2.0 Web Service with Parameters

Application configuration:
Web application using java first method of creating JAX-WS 2.0 Web Services with annotations.
WebLogic 10.3
My Requirements
The requirements I have are to deploy a single web service implementation class, but change logic based on the URL from which the service was accessed.
Question:
I'm assuming a good way to do this is to deploy different mappings in web.xml and initialize them with different parameters. Is there a better way?
What is the best way to switch logic off the URL from which the web service was accessed? Should I try to configure two servlet mappings in web.xml with initialization parameters (tried, but couldn't get it to work), or should I parse the URL in the service impl? Any other alternatives?
What I've Tried (but didn't work)
I have tried adding the <init-param> in the <servlet> element in web.xml. However, can't get to the ServletConfig object inside the web service to retrieve the param. The web service does not have all the functionality of a standard Servlet (even if I implement Servlet or ServletContextListener). I only have access to the WebServiceContext (it seems) and from there I can only get <context-param> elements--but I would need <init-param> elements instead.
In web.xml, I enter two <servlet> elements using the same Java class, but which map to two different URLs as follows. Notice how the "source" param is different in each Servlet mapping.
<servlet>
<servlet-name>Foo</servlet-name>
<servlet-class>com.Foo</servlet-class>
<init-param>
<param-name>source</param-name>
<param-value>1</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>Foo</servlet-name>
<url-pattern>/Foo</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>Bar</servlet-name>
<servlet-class>com.Foo</servlet-class>
<init-param>
<param-name>source</param-name>
<param-value>2</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>Bar</servlet-name>
<url-pattern>/Bar</url-pattern>
</servlet-mapping>
You very well may have, but did you try using MessageContext at runtime to determine what the source is?
#WebService
public class CalculatorService implements Calculator
{
#Resource
private WebServiceContext context;
#WebMethod
public void getCounter()
{
MessageContext mc = wsContext.getMessageContext();
// you can grab the HttpSession
HttpSession session = (HttpServletRequest)mc.get(MessageContext.SERVLET_REQUEST)).getSession();
// ...or maybe the path info is enough
String path = mc.get(MessageContext.PATH_INFO);
// the query itself should almost definitely be enough
String query = (String) mc.get(MessageContext.QUERY_STRING);
}
}
I got the idea from http://sirinsevinc.wordpress.com/category/jaxws/. Haven't tried it, though.

GWT + GAE Servlet URL and Servlet Mapping

http://127.0.0.1:8888/socialnetwork/contactsService
That's the current URL for one of my servlets. My question is, how do I change it?
In my web.xml file, altering
<servlet-mapping>
<servlet-name>contactsServiceServlet</servlet-name>
<url-pattern>/socialnetwork/contactsService</url-pattern>
</servlet-mapping>
to
<servlet-mapping>
<servlet-name>contactsServiceServlet</servlet-name>
<url-pattern>/a/contactsService</url-pattern>
</servlet-mapping>
Makes absolutely NO difference to the URL it requests when I make an RPC-call to the servlet.
Once you have done the above you need to change where you invoke (Which is described in the Annotation below) as in...
// The RemoteServiceRelativePath annotation automatically calls setServiceEntryPoint()
#RemoteServiceRelativePath("email")
public interface MyEmailService extends RemoteService {
void emptyMyInbox(String username, String password);
}
See http://google-web-toolkit.googlecode.com/svn/javadoc/1.6/com/google/gwt/user/client/rpc/RemoteServiceRelativePath.html

Calling a default servlet first in Java web application [duplicate]

This question already has answers here:
Change default homepage in root path to servlet with doGet
(2 answers)
Closed 7 years ago.
I want my SampleServlet to be called first whenever my java web application is accessed in this manner :
http://server:8080/appname/
Is there any way to implement this?
Use a Servlet filter to call your Servlet.
If you want to make a servlet your homepage then this worked for me on http://feelitlive.com/
<welcome-file-list>
<welcome-file>homepage</welcome-file>
</welcome-file-list>
...
<servlet>
<description>Shows stuff on the homepage</description>
<display-name>Homepage Servlet</display-name>
<servlet-name>HomepageServlet</servlet-name>
<servlet-class>com.cantorva.gigcalendar.servlets.HomepageServlet</servlet-class>
</servlet>
...
<servlet-mapping>
<servlet-name>HomepageServlet</servlet-name>
<url-pattern>/homepage</url-pattern>
</servlet-mapping>
That means that that users arriving at your application via the URL you specified will be welcomed by your servlet. It also creates an alias for the homepage at "/homepage" but you don't have to use that.
If you want to run some code on start-up then asalamon74's answer looks right.
Not sure what you mean but you need to map your servlet to "/"
<servlet-mapping>
<servlet-name>SampleServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
Not sure what is your aim, but web application initialization can be achieved by ServletContextListener:
public class AppListener implements ServletContextListener {
public void contextInitialized(ServletContextEvent event) {
// place your code here
}
public void contextDestroyed(ServletContextEvent event) {
}
}
and later in web.xml:
<web-app>
<listener>
<listener-class>
package.AppListener
</listener-class>
</listener>
...
</web-app>
If you want to run code on start-up indeed asalamon74's answer should be fine. If you have a legacy situation and you must use a servlet, the parameter load-on-startup can do the trick for you:
<servlet>
<servlet-name>SampleServlet</servlet-name>
<display-name>SampleServlet</display-name>
<description>Sample Servlet</description>
<servlet-class>...</servlet-class>
<init-param>...</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
The load-on-startup tag specifies that the servlet should be loaded automatically when the web application is started; the number value just gives a loading order to those loading on startup. If no value is specified, the servlet will be loaded when the container decides it needs to be loaded - typically on it's first access.

Categories