Quantcast
Channel: Active questions tagged servlets - Stack Overflow
Viewing all articles
Browse latest Browse all 720

How to forward request from catch all Servlet filter to Java Servlet? [duplicate]

$
0
0

I am using Tomcat 10. I have set up a catch-all servlet filter in a Java Web Project. The web.xml looks like this:

<filter><display-name>UrlFilter</display-name><filter-name>UrlFilter</filter-name><filter-class>com.example.UrlFilter</filter-class></filter><filter-mapping><filter-name>UrlFilter</filter-name><url-pattern>/*</url-pattern></filter-mapping><welcome-file-list><welcome-file>index.jsp</welcome-file></welcome-file-list>

Requests are getting passed to filter but I want to forward these requests to a Servlet and from the servlet pass data to JSP.

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {        HttpServletRequest req = (HttpServletRequest) request;        String path = req.getRequestURI().substring(req.getContextPath().length());        String pathInfo = req.getPathInfo();        if (path.startsWith("/resources"))         {            chain.doFilter(request, response); // Goes to default servlet.        }        else         {            //TODO: forward all non-static requests to Servlet        }    }

My Servlet

public class MainController extends HttpServlet {    private static final long serialVersionUID = 1L;    /**     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)     */    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {        String path = request.getRequestURI().substring(request.getContextPath().length());        String pathInfo = request.getPathInfo();        System.out.println("path: " + path);         System.out.println("pathinfo: " + pathInfo);         if (path != null && path.equals("/"))         {            request.getRequestDispatcher("/pages/home.jsp").forward(request, response);            //response.flushBuffer();        }        else         {            request.setAttribute("keyword", path);            request.getRequestDispatcher("/pages/results.jsp").forward(request, response);            //response.flushBuffer();        }}}

I have two questions:

  1. How can I forward all requests from the doFilter method to Servlet?
  2. How can the servlet then process different JSP templates for two URLs / and /*

I don't have the option to use a Java framework to do this and I am new to Java web development. Please correct me if I approaching this in a wrong way. Thanks in advance for your guidance.


Viewing all articles
Browse latest Browse all 720

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>