I have the following code in my SampleController;
@Controller
public class SampleController {
@RequestMapping("home")
public String loadHomePage(Model m) {
m.addAttribute("name", "CodeTutr");
return "home";
}
@RequestMapping(value="/test", method=RequestMethod.GET)
public String handlePost(@RequestParam String action, Model m) {
if( action.equals("save") ){
//handle save
}
else if( action.equals("renew") ){
//handle renew
}
m.addAttribute("name", "change");
return "home";
}
}
on page load the attribute I set it successful shown on the web page. I am trying to get my head around button clicks on spring mvc below is my jsp code;
<!DOCTYPE HTML>
<html>
<head>
<title>Sample Application</title>
</head>
<body>
<h1>Hello, ${name}!</h1>
<input type="submit" name="action" value="save" />
</body>
</html>
My input does not do anything, the method handlePost is never hit. I was trying to change the attribute "name" to the word "change", I am not sure what I am doing incorrectly.
Your issue isn't with Spring, it's with HTML. You cannot submit a button. You can only submit a <form>
.
Wrap your <input>
element in a <form>
<form action="<c:url value="/test" />" method="GET">
<input type="submit" name="action" value="save" />
</form>
Where <c:url>
is the url
tag of the core
taglib. Now, when you click the button, the browser will serialize your <input>
elements as url-encoded form parameters and send them. They will appear as request parameters to your server/web application. Spring will deserialize them by name and inject them as arguments where you have a @RequestParam
method parameter.
There needs to be a form encapsulating your input.
General FYI: Your "save" and "renew" use cases should be separate controller actions.
Also consider removing "POST" from your action name. Seeing as the action is decorated with GET, and the html is saying its GET
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With