f855a864
f855a864

Reputation: 277

MVC dynamic URL

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 :

Upvotes: 0

Views: 2294

Answers (2)

SpiderCode
SpiderCode

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/Pepsi
  • {domain}/Product/Pepsi/2
  • {domain}/Product/Cock/14
  • {domain}/Product/Cock

    etc...

Upvotes: 1

Andrés Oviedo
Andrés Oviedo

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

Related Questions