I'm trying to get my web controller methods to respond to gets and posts. It responds to a get, but I get an error when posting. I removed all but the basic code.
Here is my controller
@Controller
public class TestController {
@GetMapping(value = "/testForm")
public @ResponseBody String form1(
HttpSession session,
@RequestParam(name = "fName", required = false) String fName,
@RequestParam(name = "lName", required = false) String lName,
HttpServletResponse response
) {
response.addHeader("X-Frame-Options", "deny");
String html;
html = "<html><body>get form</body></html>";
return html;
}
@PostMapping(value = "/testForm")
public @ResponseBody String form2(
HttpSession session,
@RequestParam(name = "fName", required = false) String fName,
@RequestParam(name = "lName", required = false) String lName,
HttpServletResponse response
) {
response.addHeader("X-Frame-Options", "deny");
String html;
html = "<html><body>post form</body></html>";
return html;
}
Here is my HTML
<html><body>
<form action="http://localhost:8080/testForm" method="post">
<label for="fname">First name:</label>
<input type="text" id="fname" name="fname"><br><br>
<label for="lname">Last name:</label>
<input type="text" id="lname" name="lname"><br><br>
<input type="submit" value="Post">
</form>
<form action="http://localhost:8080/testForm" method="get">
<label for="fname">First name:</label>
<input type="text" id="fname" name="fname"><br><br>
<label for="lname">Last name:</label>
<input type="text" id="lname" name="lname"><br><br>
<input type="submit" value="Get">
</form>
</body></html>
As expected, when I press the Get button, my controller returns the page
get form
When I press the post button, Spring gives an error:
WARN 29588 --- [nio-8080-exec-7] o.s.w.s.r.ResourceHttpRequestHandler :
Path with "WEB-INF" or "META-INF": [WEB-INF/views/layouts/mainLayout.jsp]
I think there must be some error configured with this app - I'm taking over an existing app - so that might explain the error message. But why isn't my post method being called?
Here's something really odd. I admit, I'm new to Spring - I'm an old servlet guy. I put this same code in another Spring Boot app I maintain, and this time it worked - sort of.
This time, the get method output plaintext, so it showed on the browser as HTML tags. And the post method also was called, and the text came out as HTML tags.
So could someone explain what could be causing these differences? I suspect there are configs that are different. But both classes were @controller, and both have the exact same code.
Are there other files I could share that would give a clue? Thanks.
CodePudding user response:
if you just want return a text or json in controller method, you should add the @RestController on your controller class or add @ResponseBody on your method.
if not add this annotation, the spring mvc default is to return the redirected page instead of text or JSON
CodePudding user response:
try with @RestController
annotation