Question

I have a web application which includes few jsp pages. And my home page is welcome.jsp And the Application url is like www.test.com

So, whenever a user hit the url (www.test.com) it redirects to www.test.com/welcome.jsp

now i want if a user directly wants to access any other page like www.test.com/*.jsp it should always redirect to my home page that is www.test.com/welcome.jsp

Kindly give any suggestion on how to do it.

Was it helpful?

Solution

You can add the following mapping to your web.xml:

<servlet>
    <servlet-name>welcome</servlet-name>
    <jsp-file>welcome.jsp</jsp-file>
</servlet>

<servlet-mapping>
    <servlet-name>welcome</servlet-name>
    <url-pattern>*.jsp</url-pattern>
</servlet-mapping>

This will map all requests for a .jsp file to welcome.jsp.

Edit:

If you want to only redirect the users if they haven't already been to the welcome jsp, don't use the code above in your web.xml file. Instead in your jsp set a flag on the user's session in welcome.jsp:

<c:set scope="session" var="sessionStarted" value="true"/>

Then add create Filter to redirect them like this one RedirectFilter.java:

@WebFilter("*.jsp")
public class RedirectFilter implements Filter {

public void destroy() {}
public void init(FilterConfig fConfig) throws ServletException {}

/**
 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
 */
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

    Object sessionStarted = ((HttpServletRequest)request).getSession(true).getAttribute("sessionStarted");
    if(sessionStarted==null){
        request.getServletContext().getRequestDispatcher("welcome.jsp").forward(request, response);
    }else{
        chain.doFilter(request, response);
    }
}
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top