How to Implement Url Rewriting Similar to So

how to implement url rewriting similar to SO

This is called a slug route. One way to achieve this is to define a route with an optional slug parameter, and in the controller method check if the parameter has been provided

routes.MapRoute(
name: "Question",
url: "Question/{id}/{slug}",
defaults: new { controller = "Question", action = "Details", slug = UrlParameter.Optional }
);

Then in QuestionController (assumes an id will always be provided)

public ActionResult Details (int id, string slug)
{
if (string.IsNullOrEmpty(slug))
{
// Look up the slug in the database based on the id, but for testing
slug = "this-is-a-slug";
return RedirectToAction("Details", new { id = id, slug = slug });
}
var model = db.Questions.Find(id);
return View(model);
}

An alternative approach to URL Rewriting and Postbacks with Global.asax?

If you are unable to change the rewrite method then I can think of two approaches which may be better than what you have.

1) Create a base page and rewrite the action in it - all pages should then inherit from the new base page. This keeps the code in one place and you do not have to write in every page.

2) Inherit from the default form control and stop it rendering the action property altogether, it will then postback to the rewritten URL instead. Then replace all your form instances with your new control. You can see what I mean about half way down this article http://msdn.microsoft.com/library/ms972974

Edit

3) Scott Gu posted a solution to this problem (in this article http://weblogs.asp.net/scottgu/archive/2007/02/26/tip-trick-url-rewriting-with-asp-net.aspx) which is much cleaner and does not involve changing any code by using Control Adapters.

Url Rewrite in a different way

Use placeholders ([^/]+) like in your original example.

      RewriteRule ^category/([^/]+)/$ category.php?id=$1 [L]
^ ^
corresponds to | |
| |
http://example.com/category/banking-jobs

So for an URL like:

 http://example.com/year/month/day/post-name

You would use:

 RewriteRule ^([^/]+)/([^/]+)/([^/]+)/([^/]+)/$ category.php?$1,$2,$3

And anything that's in ( parenthesis ) will add another enumerated $4 which you then use in the rewriten filename as ¶m=$2 placeholder.

How to do dynamic URL Rewriting in J2EE

Have you investigated Servlet Filters? I have not attempted to modify the URL directly and I believe the parameters would be pre-parsed into the request object, but we use the filters extensively for parsing URLs and putting path info into the DB for other Servlet and JSP use.

You could very easily wrap the request object as it chains through to the target Servlets.

Url Rewriting vs. Routing

I would make a strong argument for using routing. It keeps the request-resource resolution logic within your application, so it's very easy to add application-dependent logic when you need, and it eliminates the need to maintain synchronization between your application and a separate configuration resource.

Routing works great with traditional webforms.

URL rewriting is often (though not always) a compensation for a problem, rather than a solution - server software and frameworks still built around the older notion of web pages, which represent physical resources. However, web applications should react to requests as commands; but only relatively recent, modern web frameworks have begun to support that model natively. Routing is one of those developments.

In the context of Java Servlet what is the difference between URL Rewriting and Forwarding?

The term "forwarding" is ambiguous in this question. In JSP/Servlet world, "forwarding" is more known from the MVC concept that the request URL (as visible in browser address bar) effectively calls the servlet (as matched by its URL pattern in web.xml or @WebServlet) which acts as a controller to prepare the model and uses a JSP as view to present the model. That JSP in turn is been called by "forwarding". This is done by RequestDispatcher#forward():

request.getRequestDispatcher("/WEB-INF/foo.jsp").forward(request, response);

This does indeed not reflect the JSP's URL in the browser address bar. This takes place entirely server side. Basically, the servlet "loads" the JSP and passes the request/response to it so that it can do its job of generating the HTML stuff. Note that the JSP in the above example is hidden in /WEB-INF folder which makes it inaccessible for endusers trying to enter its full path in browser address bar.

In general web development world, the term "forwarding" is also known from "URL forwarding" which is essentially the same as URL redirection. This in turn indeed causes a change in the browser address bar. This is in JSP/Servlet world more formally known as "redirecting" (although most starters initially confuse it with "forwarding"). This is done by HttpServletResponse#sendRedirect():

response.sendRedirect("another-servlet-url");

Basically, the server tells the client by a HTTP 3nn response with a Location header that the client should make a new GET request on the given Location. The above is effectively the same as the following:

response.setStatus(302);
response.setHeader("Location", "another-servlet-url");

As it's the client (the webbrowser) who is been instructed to do that job, you see this URL change being reflected back in the browser address bar.


The term "URL rewriting" is also ambiguous. In JSP/Servlet world, "URL rewriting" is the form of appending the session ID to the URL so that cookieless browsers can still maintain a session with the server. You'll probably ever have seen a ;jsessionid=somehexvalue attribute in the URL. This is by default not done automatically, but most Servlet based MVC frameworks will do it automatically. This is done by HttpServletResponse#encodeURL() or encodeRedirectURL():

String encodedURL = response.encodeURL(url); // or response.encodeRedirectURL(url)
// Then use this URL in links in JSP or response.sendRedirect().

(Which in turn is -again- an ambiguous term. With "URL encoding" you'd normally think of percent encoding. There's no Servlet API provided facility for this, this is normally to be done by URLEncoder#encode() or, MVC-technically more correct, in the JSP by JSTL's <c:url> and <c:param> or any UI component provided by the servlet-based MVC framework, such as JSF's <h:outputLink>)

In general web development world (especially with Apache HTTPD / PHP folks), "URL rewriting" is more known as whatever Apache HTTPD's mod_rewrite is doing: mapping incoming URLs to the concrete resources without reflecting the URL change in the client side. In JSP/Servlet world this is also possible and it's usually done by a Filter implementation which uses RequestDispatcher#forward(). A well known implementation is the Tuckey's URLRewriteFilter.


I admit that this has also confused me for long when I just started with JSP/Servlet, for sure while having my roots in the Apache HTTPD / PHP world.



Related Topics



Leave a reply



Submit