unable to connect to server (error-404) [duplicate] - java

This question already has answers here:
Servlet returns "HTTP Status 404 The requested resource (/servlet) is not available"
(19 answers)
Closed 6 years ago.
I created a sample Dynamic Web Project in Eclipse, but when I am running my project with Tomcat 5.5 i am getting this error:
HTTP Status 404 - /greetingservlet/
type Status report
message /greetingservlet/
description The requested resource (/greetingservlet/) is not available.
My HTML/JSP source code is:
<!DOCTYPE greeting SYSTEM "hello.dtd">
<html>
<title>Insert title here</title>
<body BGCOLOR="YELLOW">
<center>
<h1>USER NAME ENTRY SREEN</h1>
<form action="./greet">
user name<input type="text" name="t1">
<br><br>
<input type="submit" value="get message">
</form>
</center>
</body>
</html>
My servlet source code is:
import java.io.*;
import javax.servlet.*;
/**
* Servlet implementation class Greetingservlt
*/
public class Greetingservlt extends GenericServlet {
/**
*
*/
private static final long serialVersionUID = 1L;
public void service(ServletRequest request,ServletResponse response) throws ServletException,
IOException
{
String name=request.getParameter("t1");
response.setContentType("text");
PrintWriter pw=response.getWriter();
pw.println("<html>");
pw.println("<body bgcolor=wheat>");
pw.println("<h1>HELLO " + name + " WELCOME</h1>");
pw.println("</html>");
pw.close();
}
}
My web.xml is:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE web-app SYSTEM "Web-app.dtd">
<web-app>
<servlet>
<servlet-name>one</servlet-name>
<servlet-class>Greetingapplication</servlet-class>
</servlet>
<servlet-mapping id="ServletMapping_1283534546609">
<servlet-name>one</servlet-name>
<url-pattern>/greet</url-pattern>
</servlet-mapping>
</web-app>

The servlet is mapped on an url-pattern of /greet, not /greetingservlet as you seem to expect as per the error message. So, change the URL in browser address bar accordingly. Also, the servlet class is declared to be Greetingapplication, but it has the actual name Greetingservlt. So, you need to align out the one or the other, otherwise Tomcat is unable to locate/load the servlet. Also, packageless servlet classes used to fail on some specific Tomcat + JVM combinations. To be on the safe side, you'd like to place the servlet class (as every other Java class) in a package (don't forget to update the web.xml accordingly).
There are more problems in the code posted as far, but they are as far not relevant to this particular question. Maybe in a new question.

The 404 or Not Found HTTP response code indicates that the client was able to communicate with the server, but the server could not find the resource that was requested. And indeed...
First, according to your web.xml, your Servlet is mapped on /greet, and not /greetingservlet. So why are you trying to access /greetingservlet? Is this the name of your JSP? If yes, it's missing the .jsp extension. If no, then you should probably use /greet instead.
Second, your web.xml doesn't look correct, the servlet-class doesn't match the actual name of your servlet. It should be:
<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
version="2.4">
<display-name>My First Web Application</display-name>
<servlet>
<servlet-name>one</servlet-name>
<servlet-class>com.acme.Greetingservlt</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>one</servlet-name>
<url-pattern>/greet</url-pattern>
</servlet-mapping>
</web-app>
Replace com.acme with the real package of your servlet, if any(!). And redeploy the whole.
As a reminder, the URL to access the servlet is constructed like this:
http://localhost:8080/mywebapp/greet
A B C D
Where:
A is the hostname where Tomcat is running (the local machine here)
B is the port Tomcat is listening to (8080 is the default)
C is the context path of your webapp (the name of the war by default)
D is the pattern declared in the web.xml to invoke the servlet

Related

"404: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists" with Tomcat

When I try to run my web app project on Tomcat server I'm getting the following error.
Description The origin server did not find a current representation for the target resource or is not willing to disclose that one exists.
I have really no idea what is wrong with my code below. I've read similar questions on StackOverflow but I can't find any answer that I could implement into my project. I appreciate any help.
index.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%# taglib prefix = "c" uri = "http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>$Title$</title>
</head>
<body>
<h1>Hello</h1>
<ul>
<li>Register</li>
<li>Login</li>
<li>Panel </li>
<li>Logout </li>
</ul>
<c:forEach items="${posts}" var="post">
<p>
<h4><c:out value="${post.title} ${post.author}"/><br /></h4>
<c:out value="${post.text}"/>
Read more
</p>
</c:forEach>
</body>
</html>
HomePage.java
import Database.DBAdminConnector; import Database.DBUserConnector;
import javax.servlet.*; import javax.servlet.annotation.WebServlet; import javax.servlet.http.*; import java.io.IOException; import java.sql.*; import java.util.ArrayList; import java.util.List;
#WebServlet(name = "HomePage", urlPatterns = "/") public class HomePage extends HttpServlet {
Statement statement = null;
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
DBUserConnector dbConnector = DBUserConnector.INSTANCE;
Connection connection = dbConnector.getConnection();
resp.setContentType("text/html");
try {
statement = connection.createStatement();
String getPosts = "SELECT * FROM latest LIMIT 10";
ResultSet posts = statement.executeQuery(getPosts);
List<Post> postList = new ArrayList<>();
while(posts.next()) {
int id = posts.getInt("id");
String title = posts.getString("title");
String author = posts.getString("nickname");
Date date = posts.getDate("time_created");
String text = posts.getString("text");
Post p = new Post(id, title, author, date, text);
//System.out.println(p);
postList.add(p);
}
req.setAttribute("posts", postList);
RequestDispatcher view = req.getRequestDispatcher("index.jsp");
view.forward(req,resp);
} catch (SQLException e) {
e.printStackTrace();
}
} }
web.xml
<web-app version="3.1"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
metadata-complete="false">
<servlet-mapping>
<servlet-name>HomePage</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>PostPage</servlet-name>
<url-pattern>/post/*</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>RegisterPage</servlet-name>
<url-pattern>/register</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>LoginPage</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>PanelPage</servlet-name>
<url-pattern>/panel</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>Logout</servlet-name>
<url-pattern>/logout</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>BackupRestoreDB</servlet-name>
<url-pattern>/backup</url-pattern>
</servlet-mapping>
</web-app>
This is a common problem with application servers across the full spectrum. If you are encountering 404s or other issues, the way to debug the issue is to incrementally step backwards and forwards. The first thing you should do is look at your server logs to make sure the server has started right. If it has, you should try creating a index.html file and testing that. And so on and so on. On a failed test, you step back to see what's wrong in the previous steps. On a successful test, you step forward to see if the next thing works
I faced the same issue, I was on eclipse version 4.25.0 which was using JDK 17.
I was using Tomcat 8. The server was starting fine (as shown in Eclipse) but when url was hit, it gave this error. Then I checked the server log.
Checked the server log following this- Where can I view Tomcat log files in Eclipse?
Found the following error in server log -
java.lang.ClassNotFoundException: jakarta.servlet.Filter at
org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1420)
See - How to properly configure Jakarta EE libraries in Maven pom.xml for Tomcat
Tomcat 10.x was the first version to be Jakartified, not Tomcat 9.x.
So I installed Tomcat 10.x, used that server to run my application, got no error in the server log-- and application ran fine!
Good luck.
After creating a new dynamic web project on Eclipse and try to run it, I encountered the same error message. I couldn't find the solution on similar questions of StackOverflow. Projects I have created two years ago using an older version of Eclipse were imported to the newest version of Eclipse I'm using nowadays and they did not present the error message. That gave the hint that the problem were related to the project itself rather than the IDE. After comparing an older project with the new one, I changed the build class path order of the build path (on "Order and Export" tab) moving the src/main/java up to the first place. It worked.

The requested resource is not available in Tomcat 8.0.2 [duplicate]

This question already has answers here:
Servlet returns "HTTP Status 404 The requested resource (/servlet) is not available"
(19 answers)
Closed 6 years ago.
wel.html file
<html>
<head><title>Welcome Page</title></head>
<body>
Welcome HTML Page
<form action="Welcome" method="post">
<input type="submit" value="submit"/>
</form>
</body>
</html>
web.xml file
<?xml version="1.0" encoding="UTF-8"?>
<web-app>
<servlet>
<servlet-name>S1</servlet-name>
<servlet-class>Welcome</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>S1</servlet-name>
<url-pattern>/Welcome</url-pattern>
</servlet-mapping>
</web-app>
Welcome.java Servlet file
import java.io.*;
import javax.servlet.*;
public class Welcome implements Servlet
{
ServletConfig config;
public void init(javax.servlet.ServletConfig config) throws javax.servlet.ServletException
{
System.out.println("...init...");
this.config=config;
}
public javax.servlet.ServletConfig getServletConfig()
{
System.out.println("...getServletConfig...");
return config;
}
public void service(javax.servlet.ServletRequest req,javax.servlet.ServletResponse res) throws javax.servlet.ServletException,java.io.IOException
{
System.out.println("...service...");
res.setContentType("text/html");
PrintWriter out=res.getWriter();
out.println("<html>");
out.println("<body>");
out.println("<h1>Welcome</h1>");
out.println("</body>");
out.println("</html>");
}
public java.lang.String getServletInfo()
{
System.out.println("...getServletInfo...");
return "";
}
public void destroy()
{
System.out.println("...destroy...");
}
}
Directory Structure
C:\apache-tomcat-8.0.22\webapps\MyApp\WEB-INF\classes
web.xml in WEB-INF
compiled java class in classes folder
wel.html in MyApp folder
When I deploy the project,its working upto wel.html.But after clicking submit button,the following error page is getting displayed
HTTP Status 404 - /MyApp/Welcome
type Status report
message /MyApp/Welcome
description The requested resource is not available.
Apache Tomcat/8.0.22
I am at a loss as to what is causing this problem.Please help me.
Thanks in advance.
I also copied and pasted to a new WebApp Project in Netbeans and everything works fine. Make sure that you made no typos:
do you have web.xml and not, e.g. web.xml.xml file?
do you have Welcome.class file in WEB-INF\classes folder?
Except for that, you don't use your imports consistently. When you invoke import at the beginning, just use ServletConfig config instead javax.servlet.ServletConfig config over and over again.
It appears to work just fine for me, Tomcat 8.0.23 and Oracle JDK 1.8.0_45, using copied and pasted code from your post. Guesses at your problem would be your class is not being deployed or that it is someplace other than the default package. Try adding it to a package and modify your servlet mapping to reflect the qualified class name.

Why my servlet doesn't run? [duplicate]

This question already has answers here:
Servlet returns "HTTP Status 404 The requested resource (/servlet) is not available"
(19 answers)
Closed 6 years ago.
Here is my html:
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Beer Selection Page</title>
</head>
<body >
<form method = "post"
action = "SelectBeer.do">
Select beer Characteristics<br/>
Color:
<select name="color" size="1">
<option>light
<option>amber
<option>brown
<option>dark
</select>
<br/><br/>
<center><input type="SUBMIT"></center>
</form>
</body>
</html>
Here is my xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID" version="3.0">
<display-name>Test2</display-name>
<servlet>
<servlet-name>Ch3 beer</servlet-name>
<servlet-class>BeerSelect</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Ch3 beer</servlet-name>
<url-pattern>/SelectBeer.do</url-pattern>
</servlet-mapping>
</web-app>
And here, is my servlet:
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
/**
* Servlet implementation class BeerSelect
*/
public class BeerSelect extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* Default constructor.
*/
public BeerSelect() {
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.setContentType("text.html");
PrintWriter out = response.getWriter();
out.println("Beer Selection Advice");
String c= request.getParameter("color");
out.println("Got beer color " + c);
}
}
And when I run it on the server, the response is
HTTP Status 404 - /Test2/
type Status report
message /Test2/
description The requested resource is not available.
Test2
.....Java Resources
...................src
......................default package
.....................................BeerSelect.java
.....WebContent
...............META-INF
...............WEB-INF
......................lib
......................web.xml
...............Beer.html
Also, does anybody know why the returned String "c" in the servlet is null??
The message: The requested resource is not available. is telling you that the resource (file) you tried to get via the URL /Test2/ is not available, that is, the server can't give it to you. Most probably it wasn't mapped.
In the context of your web application Test2 your servlet is mapped to:
/SelectBeer.do
That means, that outside the context of your web application your access URL should be something like:
http://server:port/Test2/SelectBeer.do
Assuming your HTML file is located in the root of your application context, you should be able to reference the servlet like this:
<form method = "post" action = "SelectBeer.do"> ...
since it is mapped relatively to the root, or using an absolute path like this:
<form method = "post" action = "/Test2/SelectBeer.do"> ...
Since you don't seem to have an index.html (or any welcome file configured in your web.xml), if you try accessing the root of your webapp Test2/ without explicitly including the file name, you will get a 404 error. To open the file correctly you will need to use:
http://server:port/Test2/Beer.html
Just change to url patter to <url-pattern>/Test2/*</url-pattern>
You create another pattern and you request a diffrent request.. You also can use wildcard *. Not.
Once you create a call the url pattern is searched over the pattern.. For this example above you need to put the url pattern in your request
localhost:8080/Test2/
Something like that will be match to the url pattern

Adding default servlet and forwarding to an HTML creates stackoverflowerror

I am using Jetty. My default servlet is making a simple forward to an HTML file in my WEB-INF folder that is causing a java.lang.StackOverFlowError error. The error is fixed if I rename the file I am forwarding from a .html to .jsp
DefaultServlet.java
public class DefaultServlet extends HttpServlet{
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException{
req.getRequestDispatcher("WEB-INF/home.html").forward(req, resp);
}
}
web.xml
<web-app>
<display-name>Archetype Created Web Application</display-name>
<servlet>
<servlet-name>Default</servlet-name>
<servlet-class>DefaultServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Default</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
My guess is that instead of inserting the html content in the response body, the forward is sending the browser a redirect to /WEB-INF/home.html. This again calls the DefaultServlet and gets into an infinity loop. How can I prevent this?
Thanks.
The "default servlet", which is mapped on a special URL pattern of /, is a very special servlet which is invoked when there's a request which does not match any of the servlets mapped on a more specific URL pattern such as *.jsp, /foo/*, etc.
When you forward to home.html, for which apparently no one servlet is registered, then the default servlet is invoked once again. However, the default servlet is ignorantly forwarding to the very same HTML file once again instead of actually serving the requested HTML file. It'll on the forward still find no one servlet matching the forward URL and it'll still invoke the default servlet once again. And again. Etc. When this is performed so many times that the stack cannot keep track anymore of all those in sequence invoked doGet() methods (usually around 1000), then you'll get a StackOverflowError.
That it works with a JSP file has actually a very simple reason: there's already a JspServlet registered on an URL pattern of *.jsp. So the badly designed default servlet isn't invoked.
Your default servlet should instead be obtaining the HTML file's contents via ServletContext#getResourceAsStream() and write it to the HttpServletResponse#getOutputStream().
However, it's also quite possible that you completely misunderstood the whole meaning of "default servlet" and/or the special meaning of the URL pattern / and actually merely want a servlet acting as home page. In that case, you should be mapping the servlet on a more specific URL pattern (and please rename the currently obviously quite confusing class name DefaultServlet to something else):
<servlet>
<servlet-name>home</servlet-name>
<servlet-class>com.example.HomeServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>home</servlet-name>
<url-pattern>/home</url-pattern>
</servlet-mapping>
And then register exactly that URL as welcome file:
<welcome-file-list>
<welcome-file>home</welcome-file>
</welcome-file-list>
You need kind of exclude urls ends with "html".
See for example this link explaining similar problem solution Can I exclude some concrete urls from <url-pattern> inside <filter-mapping>?

How can I set the welcome page to a struts action?

I have a struts-based webapp, and I would like the default "welcome" page to be an action. The only solutions I have found to this seem to be variations on making the welcome page a JSP that contains a redirect to the action. For example, in web.xml:
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
and in index.jsp:
<%
response.sendRedirect("/myproject/MyAction.action");
%>
Surely there's a better way!
Personally, I'd keep the same setup you have now, but change the redirect for a forward. That avoids sending a header back to the client and having them make another request.
So, in particular, I'd replace the
<%
response.sendRedirect("/myproject/MyAction.action");
%>
in index.jsp with
<jsp:forward page="/MyAction.action" />
The other effect of this change is that the user won't see the URL in the address bar change from "http://server/myproject" to "http://server/myproject/index.jsp", as the forward happens internally on the server.
This is a pretty old thread but the topic discussed, i think, is still relevant. I use a struts tag - s:action to achieve this. I created an index.jsp in which i wrote this...
<s:action name="loadHomePage" namespace="/load" executeResult="true" />
As of the 2.4 version of the Servlet specification you are allowed to have a servlet in the welcome file list. Note that this may not be a URL (such as /myproject/MyAction.action). It must be a named servlet and you cannot pass a query string to the servlet. Your controller servlet would need to have a default action.
<servlet>
<servlet-name>MyController</servlet-name>
<servlet-class>com.example.MyControllerServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>MyController</servlet-name>
<url-pattern>*.action</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>MyController</welcome-file>
</welcome-file-list>
"Surely there's a better way!"
There isn't. Servlet specifications (Java Servlet Specification 2.4, "SRV.9.10 Welcome Files" for instance) state:
The purpose of this mechanism is to allow the deployer to specify an ordered
list of partial URIs for the container to use for appending to URIs when there is a
request for a URI that corresponds to a directory entry in the WAR not mapped to
a Web component.
You can't map Struts on '/', because Struts kind of require to work with a file extension. So you're left to use an implicitely mapped component, such as a JSP or a static file. All the other solutions are just hacks. So keep your solution, it's perfectly readable and maintainable, don't bother looking further.
Something that I do is to put an empty file of the same name as your struts action and trick the container to call the struts action.
Ex. If your struts action is welcome.do, create an empty file named welcome.do. That should trick the container to call the Struts action.
It appears that a popular solution will not work in all containers... http://www.theserverside.com/discussions/thread.tss?thread_id=30190
I would create a filter and bounce all requests to root back with forward responce. Hacks with creating home.do page looks ugly to me (One more thing to remember for you and investigate for someone who will support your code).
Here two blogs with same technique:
http://technologicaloddity.com/2010/03/25/spring-welcome-file-without-redirect/
http://wiki.metawerx.net/wiki/HowToUseAServletAsYourMainWebPage
It require Servlet API >= v2.4:
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
<url-pattern>/index.htm</url-pattern> <<== *1*
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.htm</welcome-file> <<== *2*
</welcome-file-list>
so you no longer need redirect.jsp in non-WEB-INF directory!!
there are this answer above but it is not clear about web app context
so
i do this:
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>TilesDispatchServlet</servlet-name>
<servlet-class>org.apache.tiles.web.util.TilesDispatchServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>TilesDispatchServlet</servlet-name>
<url-pattern>*.tiles</url-pattern>
</servlet-mapping>
And in index.jsp i just write:
<jsp:forward page="index.tiles" />
And i have index definition, named index and it all togather work fine and not depends on webapp context path.
I have configured like following. it worked perfect and no URL change also...
Create a dummy action like following in struts2.xml file. so whenever we access application like http://localhost:8080/myapp, it will forward that to dummy action and then it redirects to index.jsp / index.tiles...
<action name="">
<result type="tiles">/index.tiles</result>
</action>
w/o tiles
<action name="">
<result>/index.jsp</result>
</action>
may be we configure some action index.action in web.xml as <welcome-file>index.action</welcome-file>, and use that action to forward required page...
I am almost sure that the OP is the best solution(not sure about best practice, but it works perfectly, and actually is the solution my project leader and I prefer.)
Additionally, I find it can be combined with Spring security like this:
<%# page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%# taglib prefix="sec" uri="http://www.springframework.org/security/tags" %>
<sec:authorize access="isAnonymous()">
<% response.sendRedirect("/myApp/login/login.action?error=false"); %>
</sec:authorize>
<sec:authorize access="isAuthenticated() and (hasRole('ADMIN') or hasRole('USER'))">
<% response.sendRedirect("/myApp/principal/principal.action"); %>
</sec:authorize>
<sec:authorize access="isAuthenticated() and hasRole('USER')">
<% response.sendRedirect("/myApp/user/userDetails.action"); %>
</sec:authorize>
By this, not only we have control over the first page to be the login form, but we control the flow AFTER user is login in, depending on his role. Works like a charm.
Below code can be used in struts.xml to load welcome page.
Execute some Action before loading a welcome page.
<!-- welcome page configuration -begin -->
<action name="" class="com.LoginAction">
<result name="success">login.jsp</result>
</action>
<!-- welcome page configuration -end -->
Return directly some JSP without execution of an Action.
<!-- welcome page configuration -begin -->
<action name="">
<result name="success">login.jsp</result>
</action>
<!-- welcome page configuration -end -->
No <welcome-file-list> is not needed in web.xml
Just add a filter above Strut's filter in web.xml like this:
<filter>
<filter-name>customfilter</filter-name>
<filter-class>com.example.CustomFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>customfilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
And add the following code in doFilter method of that CustomFilter class
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest httpRequest = (HttpServletRequest)servletRequest;
HttpServletResponse httpResponse = (HttpServletResponse)servletResponse;
if (! httpResponse.isCommitted()) {
if ((httpRequest.getContextPath() + "/").equals(httpRequest.getRequestURI())) {
httpResponse.sendRedirect(httpRequest.getContextPath() + "/MyAction");
}
else {
filterChain.doFilter(servletRequest, servletResponse);
}
}
}
So that Filter will redirect to the action. You dont need any JSP to be placed outside WEB-INF as well.
This works as well reducing the need of a new servlet or jsp
<welcome-file-list>
<welcome-file>/MyAction.action</welcome-file>
</welcome-file-list>
This worked fine for me, too:
<welcome-file-list>
<welcome-file>MyAction.action</welcome-file>
</welcome-file-list>
I was not able to get the default action to execute when the user enters the webapp using the root of the web app (mywebapp/). There is a bug in struts 2.3.12 that won't go to the default action or use the welcome page when you use the root url. This will be a common occurrence. Once I changed back to struts 2.1.8 it worked fine.

Categories

Resources