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

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.

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.

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

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();
}
...
}

use of initialization parameters in java servlet

What is the use of init parameters in servlet? I know that the name itself implies that initializes some thing, but what is my question?
Any other advantages of using init parameters in servlet web.xml?
I tried searching on web but couldn't find the exact usage of it.
I had a servlet filter that had to bypass the normal authorisation flow when a special URL parameter was given. Instead of hard-coding that parameter in java, declaring it in web.xml has the advantage of being able to change it from time to time.
In general the same holds for all settings, that are best suited being declarative: timeouts, max accepted image size, buffer size. The "almost eternal" constants.
In one case a servlet could be kept entirely generic, but the key name was business application (=human client) specific:
x.y.general.servlets.MyGenericServlet -> neutral library code
x.y.clients.abc -> ABC specific code
web.xml:
<servlet>
<servlet-name>My Servlet</servlet-name>
<servlet-class>x.y.general.servlets.MyGenericServlet</servlet-class>
<init-param>
<description>For ABC</description>
<param-name>keyName</param-name>
<param-value>ABC_ID</param-value>
</init-param>
</servlet>
The usage is to provide fixed paremeter values for servlets when they are initialized.
web.xml
<servlet>
<servlet-name>MySMSServlet</servlet-name>
<description>Send a sms</description>
<servlet-class>com.x.y.SendSMS</servlet-class>
<init-param>
<param-name>cellnumber</param-name>
<param-value>5555-0000</param-value>
<description>SMS target</description>
</init-param>
<init-param>
<param-name>text</param-name>
<param-value>server start</param-value>
<description>SMS text</description>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
Servlet class
import javax.servlet.http.HttpServlet;
public class SendSMS extends HttpServlet {
private static final long serialVersionUID = 100L;
#Override
public void init() {
String cellNumber = getServletConfig().getInitParameter("cellnumber");
String text = getServletConfig().getInitParameter("text");
new SMSProvider().sendSMS(cellNumber, text);
}
}

should I make two different servlet entry for rest and normal html in web.xml

I am writing spring mvc application.
In my application I have web pages as well as rest web services to handle ajax call.
I have done below entry in web.xml
<servlet>
<servlet-name>myapp</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring_myapp-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>myapp</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
Should I map my rest url with same servlet like
<servlet-mapping>
<servlet-name>myapp</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
Or should I make new servlet entry for rest.
I have done required entries in pom.xml for "org.codehaus.jackson" and also I have made required entries in my spring_myapp-servlet.xml.
For html page I am using below code in my controller
#RequestMapping(value = "/htmlUrl")
public ModelAndView ModifyValiodation(HttpServletRequest request) {
// my code
}
For rest service I am using
#RequestMapping(value = "/restUrl")
public #ResponseBody Map<String, String> restUrl(HttpServletRequest request) {
// my code
}
If I am using only one servlet for two url mapping, then total 4 url will be made.
myapp/htmlUrl.html
myapp/restUrl.html
myapp/rest/htmlUrl
myapp/rest/restUrl
If I am using two different servlet with individual dispacherServlet then will i have to make entry of every component and service of spring in both the servlet.xml?
Please point out the solution for exposing rest web service.
Thanks!
use
<servlet-mapping>
<servlet-name>myapp</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
If you use two DispatcherServlet entries , it will load two ApplicationContext Objects in your application. Since you are using spring mvc to handle all the requests to your app, you should be fine with this configuration. Any request url that ends with .html or any urls that contains /rest/ will be handled by spring.
It is up to you to design the server side of the infrastructure.
Neither the RESTful specifications have any instructions for doing this nor the Servlet specifications enforce anything on this.
On the Applications design I think it is better idea to keep two different servlets to handle different URLs because over time the classes will become complex and long. These to may be used as front controllers and may have common logic class in the backend.

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.

Categories