Reputation: 277
As I know the urls in MVC model is based on the controllers. But I'm facing this problem that I can't wrap my head around it :
What if I'm designing a beverage website, and I have to use different URL for each brand. For example : beverage.com/pepsi, beverage.com/cocacola, beverage.com/sprit, beverage.com/7up
. These URLs will all lead to a same page called productdescription, the only difference is the description (image, ingredients, price etc)
So is there any efficent way for this task? I don't want to create new controlers for each product!
Upvotes: 0
Views: 2294
Reputation: 10122
Assuming that your common controller name is ProductController
and Method name is Description
.
Now in RouteConfig.cs you can add route as mentioned below:
routes.MapRoute(
"PepsiRoute",
"Pepsi/{id}",
new { controller = "Product", action = "Description", id = UrlParameter.Optional });
routes.MapRoute(
"CockRoute",
"Cock/{id}",
new { controller = "Product", action = "Description", id = UrlParameter.Optional });
Note: Above routes should be placed before default route. Otherwise you will face run-time exception The controller for path '{PATH}' could not be found.
Update:
For multiple brands if you don't want to register route for specific brand then you can map route as mentioned below:
routes.MapRoute(
"AllBrand",
"Product/{name}/{id}",
new { controller = "Home", action = "About", id = UrlParameter.Optional });
Then your URL will be :
{domain}/Product/Cock
etc...
Upvotes: 1
Reputation: 1428
You are looking for a Rest Controller. Here are the steps:
1-Declare your rest servlet en web.xml (Websphere example):
<servlet>
<servlet-name>MyRestServlet</servlet-name>
<servlet-class>com.ibm.websphere.jaxrs.server.IBMRestServlet</servlet-class>
<init-param>
<param-name>javax.ws.rs.Application</param-name>
<param-value>mipackage.MyRestServlet</param-value>
</init-param>
<init-param>
<param-name>requestProcessorAttribute</param-name>
<param-value>2</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>MyRestServlet</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
2-Implement the RestServlet
import java.util.HashSet;
import java.util.Set;
import javax.ws.rs.core.Application;
public class RestServlet extends Application {
@Override
public Set<Class<?>> getClasses() {
Set<Class<?>> classes = new HashSet<Class<?>>();
classes.add(BeverageController.class);
return classes;
}
}
3-Implement your Rest Controller:
import javax.enterprise.context.ApplicationScoped;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
@Path("/{beverage}")
@ApplicationScoped
public class BeverageController {
{
@GET
public String getBeverage(@PathParam("beverage") String beverage){
//fetch order
}
}
}
Upvotes: 0