Spring Boot Thymeleaf form post data than json data - spring-boot

My problem is I have thymeleaf template for reset password and I want passwords post than json data (actualy post than form data) to my spring boot server. How can I do it?
My rest controller:
#PostMapping(value = "/save-new-password")
public String saveStudent(#Valid #RequestBody NewPasswordDTO newPasswordDTO) {
return "OK";
}
Part from my reset-password-page.html:
<body>
<form th:action="#{/save-new-password}" th:object="${newPasswordDTO}" method="post">
<div class="box">
<h1>RESET PASSWORD</h1>
<input class="password" name="newPassword" type="password" placeholder="New password" th:field="*{newPassword}">
<input class="password" name="confirmPassword" type="password" placeholder="Confirm password" th:field="*{confirmPassword}">
<input class="button" type="submit" value="RESET"/>
</div>
</form>
</body>

Related

Can't load page in Spring Boot using th:object

It contains a line error: "An error happened during template parsing (template: "class path resource [templates//register.html]")".
I can't open register html page to add new object into db. why?
<form th:action="#{/register-user}" th:object="user" method="post">
<div class="form-group">
<label for="email">Email:</label>
<input type="email" class="form-control" id="email" placeholder="Enter email" name="email">
</div>
<div class="form-group">
<label for="password">Password:</label>
<input type="password" class="form-control" id="password" placeholder="Enter password" name="pswd">
</div>
<div class="form-group form-check">
</div>
<button type="submit" class="btn btn-primary">Register</button>
</form>
My controller
#RequestMapping(path="/register-user", method = RequestMethod.POST)
public String registerNewUser(#Valid #ModelAttribute("user") User user){
userService.register(user);
return "redirect:/login";
}
Your "user" is a model attribute, hence, to access it (and use it as the th:object) you gotta use the ${...} syntax. The result would look like this:
<form th:action="#{/register-user}" th:object="${user}" method="post">

Send form in JSON using Thymeleaf and Spring boot

I'm using a form using Thymeleaf to send data to my Service.
Here is my Form:
<form th:object="${individualEntity}" th:action="#{/save}" method="post">
<div class="form-group">
<label>FirstName:</label>
<input type="text" class="form-control" th:field="*{individualName.givenName}"/>
</div>
<div class="form-group">
<label>LastName:</label>
<input type="text" class="form-control" th:field="*{individualName.surname}"/>
</div>
<div class="form-group">
<label>Address:</label>
<input type="text" th:field="*{address}"/>
</div>
<div class="row">
<button type="submit">Submit</button>
</div>
When I debug the request sent using this form it gives me this data : individualName.givenName=xxxx&individualName.surname=xxxxx&address=xxxx
However I want that it will be in JSON when sending because my microservice consumes JSON.
What should I do to correct that !
Here is my service:
#PostMapping(value = "save")
public String saveIndividual(Individual individual){
individualService.saveIndividual(individual);
return "redirect:/getIndividual/" + individual.getId();
}
Thanks

Spring Security with Angular2

I'm trying to authenticate my user from an Angular2 form using Spring Security, but its not working. I've looked all over the web, but seem to find no right answer to it, could someone point out where I am going wrong -
Here's a snippet from my spring-security.xml -
<security:form-login login-page="/"
authentication-failure-url="/security/login"
default-target-url="/"/>
<security:access-denied-handler error-page="/security/denied"/>
<security:logout invalidate-session="true"
logout-success-url="/security/logout/success"
logout-url="/security/logout"/>
Here's my angular2 form -
<form (ngSubmit)="onLogin(f.value)" class="form-horizontal" role="form" #f="ngForm">
<div class="form-group">
<label class="col-sm-3 control-label" for="j_username">Username:</label>
<div class="col-sm-8">
<input type="text" class="form-control" placeholder="Username" name="j_username" [(ngModel)]="user.userName"
maxlength="50" id="j_username" required >
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label" for="j_password">Password:</label>
<div class="col-sm-8">
<input type="password" class="form-control" placeholder="Password" name="j_password" [(ngModel)]="user.password"
maxlength="50" id="j_password" required>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-8 col-sm-10">
<input type="submit" class="btn btn-default" value="Login">
</div>
</div>
</form>
And here's the component code -
onLogin(f) {
this.userService.makeHttpCall(f);
}
And finally the service which calls the spring security -
makeHttpCall(f): void {
let userName = f['j_username'];
let password = f['j_password'];
let data = 'j_username='+userName+'&j_password='+password;
console.log(data);
let headers = new Headers({'Content-Type': 'application/x-www-form-urlencoded'});
let options = new RequestOptions({headers: headers}
);
this.http.post('/j_spring_security_check', data, options)
.map(this.extractData)
.catch(this.handleError);
}
Could someone point out where i am going wrong? the http call, does not make it to the AuthenticationManager defined in my spring security configuration.
In Angular2, HTTP calls are triggered as soon as you subscribe to them. Adjust the code like this:
this.http.post('/j_spring_security_check', data, options)
.map(this.extractData)
.catch(this.handleError).
.subscribe(data => {
// do something here with the response
})

Cannot submit a form on SpringMVC

I am fairly new to SpringMVC and have a form that can not submit to the back-end. I created the form as following and when I submit it error 404 will be returned. I changed action to /MyProject/contact but did not work.
<form class="form-horizontal" role="form" method="post"
action="/contact">
<div class="form-group">
<div class="col-md-12">
<label class="sr-only" for="exampleInputName2">Name
</label> <input type="text" class="form-control" id="name"
name="name" placeholder="Your name" value="">
</div>
</div>
<div class="form-group">
<div class="col-md-12">
<label class="sr-only" for="exampleInputName2">Email
Address</label> <input type="email" class="form-control" id="email"
name="email" placeholder="Your email" value="">
</div>
</div>
<div class="form-group">
<div class="col-md-12">
<label class="sr-only" for="exampleInputName2">Phone
Number</label> <input type="number" class="form-control" id="phone"
name="phone" placeholder="Phone number" value="">
</div>
</div>
<div class="form-group">
<div class="col-md-12">
<label class="sr-only" for="exampleInputName2">Enquiry</label>
<textarea class="form-control" rows="4" name="message"
placeholder="Please enter your enquiry"></textarea>
</div>
</div>
<div class="form-group">
<div class="col-md-2 " style="float: right;">
<input id="submit" name="submit" type="submit" value="Send"
class="btn btn-primary">
</div>
</div>
<div class="form-group">
<div class="col-sm-10 col-sm-offset-2">
<! Will be used to display an alert to the user>
</div>
</div>
</form>
Controller
#Controller
public class ContactController {
#RequestMapping(value="/contact", method=RequestMethod.POST)
public String processForm(Contact contact, Model model){
System.err.println("Contact Name is:" + contact.getName());
return null;
}
}
Error
HTTP Status 404 - /contact
type Status report
message /contact
description The requested resource is not available.
Its beacuse spring does not know how to pass the param Contact contact to your controller method. You need to do couple of things to make it work. Change your form to like below.
<form class="form-horizontal" role="form" method="post" modelAttribute="contact" action="/contact">
Your controller to take contact as model attribute.
#Controller
public class ContactController {
#RequestMapping(value="/contact", method=RequestMethod.POST)
public String processForm(#ModelAttribute Contact contact, Model model){
System.err.println("Contact Name is:" + contact.getName());
return null;
}
}
For a better understanding of what a model attribute does, there are plenty of samples and explanation online. Hope this helps.
I could solve the problem by help of minion's answer, following this tutorial and adding following link
#RequestMapping(value = "/contact", method = RequestMethod.GET)
public ModelAndView contactForm() {
System.err.println("here in GET");
return new ModelAndView("contact", "command", new Contact());
}

How to collect form data and convert them json format and send back to server in spring mvc

I have form and I want to grab the data inserted by users and then convert them json format.
So first here is my form—
<form id="patient_form" action="#" class="form-horizontal">
<div class="control-group">
<label class="control-label" for="firstName"> First Name<em>*</em></label>
<div class="controls">
<input type="text" id="firstName" class="required" maxlength="100"
placeholder="First Name" />
</div>
</div>
<div class="control-group">
<label class="control-label" for="middleNameInitial">
Middle Name Initial</label>
<div class="controls">
<input type="text" id="middleNameInitial"
placeholder="Middle Name Initial" class="input-small"
maxlength="1" />
</div>
</div>
<div class="control-group">
<label class="control-label" for="lastName"> Last Name <em>*</em></label>
<div class="controls">
<input type="text" id="lastName" placeholder="Last Name"
class="required" maxlength="100" />
</div>
</div>
<div class="control-group">
<label class="control-label" for="dateOfBirth"> Date Of
Birth</label>
<div class="controls">
<input type="text" id="dateOfBirth" class="required" />
</div>
</div>
<div class="control-group">
<div class="controls">
<button type="button" class="btn btn-primary"
onclick="savePatientInfo()">Save Changes</button>
<button type="button" class="btn"
onclick="cancelPatientInfoForm()">Cancel</button>
</div>
</div>
</form>
And then I want to send back them to server. And for server side code, I’m using spring mvc and client side I’m using JQuery.
Now how can I do it? I need two things basically,
Ajax call (JavaScript function to which will basically do 3 things, one- grab the form data and convert them into json and then ajax call)
Sever side method to consume ajax call (Controller method as I’m
suing spring mvc.)
Any help is much appreciated.
First of all you need to perform ajax call from the JSP as below:
$.post("${pageContext.servletContext.contextPath}/ajaxTestData",
{
firstName:$("#firstName").val(),
middleNameInitial:$("#middleNameInitial").val(),
<other form data>
},
function(j)
{
<j is the string you will return from the controller function.>
});
Now in the controller you need to map the ajax request as below:
#RequestMapping(value="/ajaxTestData", method=RequestMethod.POST)
#ResponseBody
public String calculateTestData(#RequestParam("firstName") String firstName, #RequestParam("middleNameInitial") String middleNameInitial, HttpServletRequest request, HttpServletResponse response){
<perform the task here and return the String result.>
return "xyz";
}
I have not used the JSON input and result in this way but I think if you return the Pojo then it might converts the same in the json format automatically. Just check that.
Hope this helps you. Cheers.

Resources