tomasz-mer
tomasz-mer

Reputation: 3910

How to use simple html form to get value from rest service?

I have simle controller like this:

@Controller
@RequestMapping("/raport")
public class SiteController {

    @RequestMapping(value = "/{url}", method = RequestMethod.GET)
    public String getMovie(@PathVariable String url, ModelMap model) {

        model.addAttribute("url", url);
        return "raport";

    }

    @RequestMapping(value = "/", method = RequestMethod.GET)
    public String getDefaultMovie(ModelMap model) {

        model.addAttribute("url", "this is default movie url");
        return "raport";

    }

} 

if I call http://localhost:8090/movieraport/raport/testMovie i got a correct response from server

Movie url : testMovie

but I want to have a little form on page like this (.jsp):

<body>
<form action="raport/" method="get">
    <input name="url" />
    <input type="submit" value="Update Record">
</form>

<h3>Movie url : ${url}</h3>

When I clicked to submit I got url like this

http://localhost:8090/movieraport/raport/raport?url=testMovie

and server is not working with {testMovie} :(

I got:

Movie url : raport

Can you help me?

Upvotes: 0

Views: 1710

Answers (1)

MattSenter
MattSenter

Reputation: 3120

If you want to pass "url" as a parameter, you need to do this:

@RequestMapping(value = "/", method = RequestMethod.GET)
public String getMovie(@RequestParam String url, ...) {
    ...
}

You are incorrectly assuming that "url=" should be passed to your "/{url}" mapping, I imagine. Simply use @RequestParam instead of @PathVariable OR create yet another method to allow support for both if that's what you need.

EDIT

After your comments, I should emphasize that I have no way of knowing what your use case is or all of the endpoints you may need, but from the exception you gave, it sounds like you did nothing more than replace your getMovie() with my getMovie() and now the signature conflicts with your getDefaultMovie(). You can easily vary the signatures as follows:

@RequestMapping(value = "/", params = "url", method = RequestMethod.GET)
public String getMovie(@RequestParam String url, ...) {
    ...
}

@RequestMapping(value = "/", method = RequestMethod.GET)
public String getDefaultMovie(...) {
    ...
}

As you can see, I have added params = "url" to the getMovie() signature. This will make sure getMovie() is used to process any requests that include a url parameter. The rest will go to getDefaultMovie().

Upvotes: 2

Related Questions