Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use a URL like a parameter

Tags:

java

url

servlets

I want a simple servlet that can be used without parameters. Something like :

http://servername:8080/do/view/username/address

and use it like a parameter :

http://servername:8080/do?action=view&login=username&page=address

Both urls will have the same behaviour. I prefer don't use any framework, only servlets and filters.

How can I obtain the url name from the servlet? What's the best solution?


Response:


Based on the reply made by @BalusC i have created the following servlet that do all i want:

@WebServlet("/do/*")
public class ActionTestCasesServlet extends HttpServlet {

protected void doGet(HttpServletRequest request,
        HttpServletResponse response) throws ServletException, IOException  
{
  String pathInfo = request.getPathInfo();
  String[] parts = pathInfo.substring(1).split("/");
  RequestDispatcher destination = getServletContext()
            .getRequestDispatcher("/" + parts[0] + ".jsp");
  if (parts.length > 1) {
request.setAttribute("username", parts[1]);
  }
  if (parts.length > 2) {
    request.setAttribute("page", parts[2]);
  }
  destination.forward(request, response);

 }
}

This code call the "view.jsp" passing the attributes "username" and "page".

like image 590
Fernando Rosado Avatar asked Dec 05 '25 07:12

Fernando Rosado


2 Answers

Just map the servlet on /do/* instead of /do.

@WebServlet("/do/*")

This way you can obtain the path information using HttpServletRequest#getPathInfo().

String pathInfo = request.getPathInfo(); // /view/username/address

You can use the usual String methods like String#split() to split it in fragments.

String[] parts = pathInfo.substring(1).split("/"); // view, username, address

See also:

  • Design Patterns web based applications - for the case you intend to homegrow MVC (note: I don't recommend this, it's fun if it's for learning/hobby purposes, but if it's for real job, rather pick an existing MVC framework so that you can ensure that every pitfall is covered)
like image 127
BalusC Avatar answered Dec 06 '25 20:12

BalusC


You say you'd prefer not to use "any framework, only servlets and filters", but have you considered the tuckey.org UrlRewriteFilter? This is a single filter that you can register in web.xml and then declare rules such as

    <rule>
        <from>/do/(.+)/(.+)/(.+)</from>
        <to>/do?action=$1&amp;login=$2&amp;page=$3</to>
    </rule>

in an XML file. Then you just write your servlets to expect the query parameters as normal and let the filter deal with the "pretty" URLs.

like image 34
Ian Roberts Avatar answered Dec 06 '25 20:12

Ian Roberts