Sitansu Mishra
Sitansu Mishra

Reputation: 11

UrlMapping Wildcard for @Pathvariable

I am trying to Define @PathVariable with wildcard in Web.xml for url-mapping. Seems it does not work unless I give the full path in the mapping. Here is my code.

TrackingController .java - PSEUDO Code

@Controller
@RequestMapping(value = "/tracking")
public class JobController implements Runnable {


    @RequestMapping(value = "/{countrycode}/{urlID}", method = RequestMethod.GET)
    @ResponseBody

    public RedirectView refreshcache(@PathVariable("countrycode") String countrycode, @PathVariable("urlID") String urlID){

         String Oauthurl="";
         System.out.println(countrycode);
         System.out.println(urlID);
         if (countrycode.equals("India"))
         {
             Oauthurl ="https://www.google.co.in/";
         }
         else
         {
             Oauthurl ="https://www.google.com/";
         }
         RedirectView redirectView = new RedirectView();
            redirectView.setUrl(Oauthurl);
            return redirectView;


        }

What I have already Tried is putting the full path and the path with wildcard in the web.xml

Full path- Works

<servlet-name>appServlet</servlet-name>
        <url-pattern>/tracking/India/1</url-pattern>
</servlet-mapping>

Wildcard - Does not work

<servlet-name>appServlet</servlet-name>
        <url-pattern>/tracking/*</url-pattern>
</servlet-mapping>

Expected Result with wild card is it would redirect to the Url based on the @Pathvariable provided

However it throws 404 Error

Upvotes: 1

Views: 956

Answers (2)

Bohdan Petrenko
Bohdan Petrenko

Reputation: 1155

Don't use mapping via web.xml. It's already done by @RequestMapping.

Following code should work:

@Controller
@RequestMapping(value = "/tracking")
public class JobController {


    @GetMapping("/{countryCode}/{urlID}")//removed @ResponseBody
    public RedirectView refreshCache(@PathVariable String countryCode, @PathVariable String urlID) {
        String oauthUrl;

        System.out.println(countryCode);
        System.out.println(urlID);

        if ("India".equalsIgnoreCase(countryCode)) {//Avoid NPE
            oauthUrl = "https://www.google.co.in/";
        } else {
            oauthUrl = "https://www.google.com/";
        }
        return new RedirectView(oauthUrl);
    }
}

If don't - check configuration. Spring can't find your controllers. Take a look

Upvotes: 0

Usman Ali
Usman Ali

Reputation: 58

You need to specify double (*) in the path url to match any string. here is the example.


<servlet-name>appServlet</servlet-name>
        <url-pattern>/tracking/**</url-pattern>
</servlet-mapping>

Upvotes: 1

Related Questions