简体   繁体   中英

Url Shortener redirects to index.html

Yes, yet another url shortener written in java, because I wanted my own, and because why not. Currently everything works, just not they way I want to to. In short, there is only one servlet mapped to "/" in the entire project. There are no frameworks involved, or anything fancy, this is just a basic Servlet "project". on doPost a new shortUrl is created, and you get a JSON response. On doGet, if the URL is "/*{any_valid_short_url}" then a redirect is sent (below).

response.sendRedirect("longUrlString")

The issue I am having is with the index page, when the same doGet is called, I check the requested path, if it is "/" then currently, I use a FileInputStream and stream the index.html page out via response.getOutputStream(), which is pretty hacky in my opinion. I would like to use a requestDispatcher instead, however when I do try to implement that (below) I get into a re-direct loop, and the servlet container (jetty or tomcat) stack overflow's.

getServletContext().getRequestDispatcher("/index.html").forward(req, res);

Is there something that I am mis-understanding about how this is being done? The project is currently hosted on my github page. https://github.com/justinmburrous/ShortUrl

You need to make this check more narrower, because for all requests this condition is true and hence for all requests are forwarded to 'index.html' again and again

    if(requestedPath.equals("/")){

    //tried with multiple variations of /index.html, renamed to jsp, etc...
RequestDispatcher dispatcher = request.getRequestDispatcher("index.html");
dispatcher.forward(request, response);    
    }

Edit: Since your servlet is mapped as default servlet , all forwards or request will be handled by this Servlet. You should map the url to more specific range.

RequestDispatcher - forward - produces infinite loop

Okay, I have figured this one out with thanks to How to access static resources when mapping a global front controller servlet on /*

My github page has the working code along with the Filter, modified servlet and web.xml for.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM