Request method 'POST' not supported in spring MVC web app - spring

i am using .html in mvc app. it's showing app perfectly.inside login.html i have used form with method POST for submission but when i submit form showing error that POST is not supported.but when i change everything with .jsp then it let submit form.
here's the controller
#Controller
public class mainController {
#RequestMapping("/login")
public ModelAndView login(Locale locale , Model m) {
System.out.println("modal");
return new ModelAndView ("login");
}
#RequestMapping(path = "/user" , method=RequestMethod.POST)
public String user(#ModelAttribute("user") User user) {
System.out.println(user);
return "user";
}
}
this is login form
<form action="user" method="post" name="user">
<input type="text" name="username" placeholder="uname"/> <br>
<input type="password" name="password" placeholder="password"/> <br>
<input type="date" name="date" placeholder="date"/> <br>
<button type="submit">Submit</button>
</form>
what can I do to submit form using POST method from .html file.

Related

How to pass model value in thymeleaf input text

I have data in a Model object and I want to put that into the input field in my Thymeleaf template, such that if the value is null, nothing will be displayed and otherwise, the input will have the value inside it. I tried this but this is not working.
<input id="first_name" type="text" name="firstName" placeholder="First" value=${accountInfo.firstName} maxlength=31 required>
I passed the values into the model object inside the java exception handler like so:
#ExceptionHandler(value=SignupFormException.class)
public String handle(HttpSession session, SignupFormException ex, Model response) {
response.addAttribute("accountInfo", (Account) session.getAttribute("accountToRegister"));
response.addAttribute("Error", ex.getMessage());
session.invalidate();
return "redirect:/signup";
}
How to fetch the attributes from the accountInfo object I passed in my model in my thymeleaf template?
Update:
Now it is working but not the first time the page is accessed when there is no model object. Following is the code:
My thymeleaf form:
<form action="/signup_do" th:object="${accountInfo}" method="post">
<input id="first_name" type="text" name="firstName" placeholder="First" th:value=*{firstName} maxlength=31 required>
Controller:
#PostMapping("/signup_do")
public String register(Account account, HttpSession session) {
session.setAttribute("accountToRegister", account);
accountManagement.accountRegistration(account);
return "Success";
}
There is a account registration service that throws SignupFormException which is handled by:
#ExceptionHandler(value=SignupFormException.class)
public String handle(HttpSession session, SignupFormException ex, Model response) {
response.addAttribute("accountInfo", (Account) session.getAttribute("accountToRegister"));
response.addAttribute("Error", ex.getMessage());
session.invalidate();
return "redirect:/signup";
}
And only now do I have a model object with properties for the thymeleaf template...
change "value" to "th:field"
OR
change "value" to th:value="${accountInfo.firstName}"
<form action="#" th:action="#{/yourURL}" th:object="${accountInfo}" method="post">
<input id="first_name" type="text" name="firstName" placeholder="First" th:field=*{firstName} maxlength=31 required>
<input type="submit" class="btn btn-primary" value="Submit">
</form>

Passing parameter from get to post method

I'm building an feature for a webste where a user can reset his password. He receives an email with a generated token in the url. When this link is clicked, the user is sent to the /reset page. The Get method for that page is the following:
#RequestMapping(value = "/reset", method = RequestMethod.GET)
public ModelAndView displayResetPasswordPage(ModelAndView modelAndView, #ModelAttribute User user, #RequestParam("token") String token) {
User u = userService.findByResetToken(token);
if (u == null) {
modelAndView.setViewName("error/404");
return modelAndView;
} else {
modelAndView.addObject("token", token);
modelAndView.setViewName("resetPassword");
return modelAndView;
}
}
This works fine, if the token in the url is changed, the user is sent to an error page. Now I want to pass this "token" parameter to the post method:
#RequestMapping(value = "/reset", method = RequestMethod.POST)
public ModelAndView setNewPassword(ModelAndView modelAndView, #RequestParam Map<String, String> requestParams, #ModelAttribute User user, BindingResult bindingResult, RedirectAttributes redir) {
System.out.println("token: " + requestParams.get("token"));
User u = userService.findByResetToken(requestParams.get("token"));
// User u = userService.findByEmail(user.getEmail());
if (u != null) {
User updatedUser = userService.updateUserPassword(user);
modelAndView.addObject("User",updatedUser);
modelAndView.setViewName("redirect:login");
return modelAndView;
} else {
modelAndView.setViewName("resetPassword");
}
return modelAndView;
}
This always returns the resetPassword view, since the requestparams.get("token") always returns an empty string. Am I not using the correct method to get the param value?
The reset password view:
<div class="wrapper">
<form class="form-signin" th:action="#{/reset}" method="post" th:object="${user}">
<h2 class="form-signin-heading">Reset wachtwoord</h2>
<input type="hidden" name="token" th:value="*{resetToken}"/>
<div class="form-group">
<input type="password" th:field="*{encryptedPassword}" id="password" class="form-control input-lg"
placeholder="Password" tabindex="3"/>
<div class="form-group">
<input type="password" th:field="*{matchingPassword}" id="password_confirmation"
class="form-control input-lg" placeholder="Confirm Password" tabindex="4"/>
</div>
<div class="row">
<div class="col-xs-6 col-sm-6 col-md-6">
<input type="submit" class="btn btn-secondary" value="Registreer"/>
</div>
</div>
</form>
This can be done by employing the Flash Scope that will allow your token to survive a redirect. You can do that by:
Making the first controller method accessing the second one via a redirect
Using RedirectAttributes on your first controller method and explicitly adding your token into the RedirectAttributes as a Flash Attribute
Take a look at the documentation about RedirectAttributes.

Insert jsp form to database using spring boot

I'm a beginner in spring boot I start with creating a contact form that send data to data base. this is the form:
<form:form method="POST" id="contactform" modelAttribute="message">
<div class="form">
<div class="six columns noleftmargin">
<label name="name">Name</label>
<form:input path="name" type="text" class="smoothborder" placeholder="Your name *"/>
</div>
<div class="six columns">
<label name="email">E-mail address</label>
<form:input path="email" type="text" class="smoothborder" placeholder="Your e-mail address *"/>
</div>
<label name="comment">Message</label>
<form:textarea path="comment" class="smoothborder ctextarea" rows="14" placeholder="Message, feedback, comments *"></form:textarea>
<input type="submit" id="submit" class="readmore" value="Submit"/>
</div>
</form:form>
And this is my conact controller:
#Autowired
private MessageRepository messageRepository ;
#RequestMapping(value= "/newmessage", method = RequestMethod.GET)
public String newMessage(ModelMap model) {
Message message = new Message();
model.addAttribute("message", message);
return ("/contact");
}
#RequestMapping(value="/newmessage",method=RequestMethod.POST)
public String saveMessage( Message message, BindingResult result, ModelMap model)
{
if (result.hasErrors()) {
return "/contact";
}
messageRepository.save(message);
model.addAttribute("success", "Message " + message.getName() + " "+ message.getEmail() + " "+ message.getComment()+ " registered successfully");
//return "success";
return "/homepage";
Folder Structure
You need to set the action of the form. If you want to hit /newmessage while submitting form, then you need to change as following :
<form:form method="POST" id="contactform" action="/newmessage" modelAttribute="message">
<!-- The elements of the form -->
</form:form>
Also, you need to add the modelAttribute to your controller method. And you should return only the name of the jsp page. If your page name is homepage.jsp then you should only return homepage from your controller method. Of course, homepage.jsp file needs to be in WEB-INF folder.
#RequestMapping(value="/newmessage",method=RequestMethod.POST)
public String saveMessage(#ModelAttribute("message") Message message, BindingResult result, ModelMap model) {
// Rest of the code
return "homepage";
}

how to get form values to controller in spring mvc

I am trying to get form values from jsp to controller in spring mvc, but i am not able to get form data.
This is my DTO (bean)
public class LoginDTO implements Serializable {
private Long id;
private String username;
private String password;
// setter and getter methods
}
and my Jsp
<form class="form-signin" action="test" method="get" modelAttribute="userFormData">
<input type="text" class="form-control"
placeholder="Email" required autofocus>
<input type="password" class="form-control"
placeholder="Password" required>
<input class="btn btn-md btn-success btn-block"
type="submit" value="Signin">
</form>
and my controller
#RequestMapping(value = "/test", method = RequestMethod.GET)
public String checkLogin(#ModelAttribute("userFormData") LoginDTO formData, BindingResult
result) {
System.out.println("Controller...");
System.out.println("=====> " + formData.getUsername());
System.out.println("=====> " + formData.getPassword());
}
Add names to the controls on your JSP pages.
<input type="text" name="username" ...>
<input type="password" name="password" ...>
To let spring understand which form control value should go to which property of the LoginDTO
we can also use the springframework has given us a form tags.so that we can also use that but in that case you have to define your the input path same as the member varibale given in your class.
like this
<form:form method="post" modelAttribute="userFormData">
<form:input path="username" />
<form:input path="password" />
Then in the controller you can write like this as you have written
public String checkLogin(#ModelAttribute("userFormData") LoginDTO formData, BindingResult
result)
In case you want to get the result on other jsp page as well as on console then do:
public String checkLogin(#ModelAttribute("userFormData") LoginDTO formData, BindingResult
result , Model model){
System.out.println("=====> " + formData.getUsername()); //this outputs username on console
System.out.println("=====> " + formData.getPassword()); //this outputs password on console
model.addAttribute("LoginDTO ", LoginDTO );
return "success"; //this is the return page where the username and password will be rendered as view
}

Passing parameters from JSP to controller - Spring MVC

I have a little problem when I want to pass parameter to my controller.
I have one method in controller:
#RequestMapping("/redirect")
public String print(String type, HttpServletRequest servletRequest)
{
String path = "redirect:" + servletRequest.getParameter("type");
return path;
}
And I have some buttons in my jsp file:
<form method="post" action="/WWP/redirect">
<button onclick=" <input type="text" name="type" value="/developer"/>">Developer</button>
<button onclick=<input type="text" name="type" value="/graphic"/>>Graphic</button>
<button onclick=" <input type="text" name="type" value="/cleaner"/>">Cleaner</button>
</form>
In this way I have 3 buttons and when for example I press Developer button variable "type" is "/developer" and I'm sending it to controller. But now my buttons look like this:
http://imageshack.us/photo/my-images/854/buttonspx.png/
It works correct, but I can't get rid this HTML tag and it's really nervous. How to do this? Or how send value to controller in different way. Thanks in advance.
Instead of normal buttons you can have submit buttons and handle them in controller as below
<input type="submit" value="Developer" name="developer"></input>
<input type="submit" value="Graphic" name="graphic"></input>
<input type="submit" value="Cleaner" name="cleaner"></input>
And you can have different methods in the controller class for each of the buttons clicked using the params attribute like this
#RequestMapping(value = "/redirect", method = {RequestMethod.POST}, params = "developer")
public ModelAndView developerMethod(){
}
#RequestMapping(value = "/redirect", method = {RequestMethod.POST}, params = "graphic")
public ModelAndView graphicMethod(){
}
#RequestMapping(value = "/redirect", method = {RequestMethod.POST}, params = "cleaner")
public ModelAndView cleanerMethod(){
}

Resources