Send POST request from Spring controller - java

I have a question to you. Let me explain the situation. We have a jsp page, there is a post form here with some inputs. When user enter some data and submit the form, my spring controller handles this request, transforms income data and then I should send it's trasformed data with post request to another site with the client redirection. In other words I want to know is it some oppotunity to use response.sendRedirect("some other website url") with post request in my controller? Or how I can do it another way?
For example simple form:
<form action="myServerSideUrl" method="post>
<input type="text" name="Input1"/>
<input type="text" name="Input1"/>
<input type="submit" value="submit"/>
</form>
When user submit it, it comes to server, then for example I sum Input1 and Input2 (Input3), and then I want to redirect user to another site with Input3 POST request.

You may use Spring's own RestTemplate or a simple java.net.URLConnection (but you have to write a bit more code) to make a POST request in your controller.
So upon receiving the request in your #Controller you can just forward it wherever you want.

<html:form action="changePassword" method="POST"
commandName="changePasswordForm">
<label> <html:password path="password" id="oldPassword"
maxlength="128" class="input" required="required"
placeholder="Current Password" />
</label>
<label> <html:password path="newPassword" id="password"
maxlength="15" required="required" class="input"
placeholder="New Password" />
</label>
<label> <html:password path="confirmPassword"
id="confirmNewPassword" maxlength="15" required="required"
class="input" placeholder="Confirm Password" />
</label>
<label> <html:input path="" type="submit" value="SAVE"
/>
</label>
</html:form>
Spring Controller is below :
#RequestMapping(value = "changePassword", method = RequestMethod.POST)
public String changePassword( #ModelAttribute(value = "searchForm") SearchForm searchForm,
Model inModel,
HttpServletRequest inRequest )
{
String viewName ="changePassPage";
// do something logic related to change password.
return viewName ;
}
Form Bean Or POJO Model in spring:
public class SearchForm
{
private String password;
private String newPassword;
private String confirmPassword;
//setter & getter;
}
You can try with Spring Post Example

Related

Spring-MVC : two jsps into one controller with one requestMapping

Can I use one request mapping for two jsps?
I am currently calling one request mapping from one controller but one of the jsps doesn't seem to be caught by the controller.
Both jsps have the same form action and same form method:
first.jsp look like this:
<form:form method="POST" action="/ShowroomNav/requestQuote" id="requestQuoteForm">
<input type="hidden" value=${product.productCode } name="productCodes" />
<input type="hidden" id="requestQuoteEmailAddress" name="requestQuoteEmailAddress" />
</form:form>
the second.jsp look like this:
<form:form method="POST" action="/ShowroomNav/requestQuote" id="requestQuoteForm">
<input type="hidden" id="requestQuoteEmailAddress" name="requestEmailAddress" />
<c:forEach var="product" items="${products}">
<input type="hidden" value=${product.productCode } name="productCodes" />
<div class="box">
<img
src="public/productImages/${product.productCode}/${product.productCode}A.jpg"
style="max-width: 100%"
onclick="productProfile('${product.productCode}')" /><br /> <label
class="name">${product.productName}</label>
</div>
</c:forEach>
</form:form>
both of them submits the function by a javascript call of :
$("#requestQuoteSubmitButton").one("click",function(){
$("#requestQuoteEmailAddress").val($("#requestQuoteEmailAddressModal").val());
alert($("#requestQuoteEmailAddress").val());
$("#requestQuoteForm").submit();
});
this is how the controller.java looks like:
#RequestMapping(value = "/requestQuote", method = RequestMethod.POST) // or GET
public String requestQuote(#RequestParam("requestQuoteEmailAddress") String requestQuoteEmailAddress, #RequestParam("productCodes") String[] productCodes) {
System.out.println(">>>> requesting quotes >>>>");
for(int i=0; i<productCodes.length; i++) {
System.out.println(" Product Codes : " + productCodes[i]);
}
System.out.println("requestQuoteEmailAddress : " + requestQuoteEmailAddress );
System.out.println("<<<<< requesting quotes <<<<");
return "productSearch";
}
So I don't know why the second.jsp cannot be caught by the controller as it always shows this error when I try to submit it.
HTTP Status 400 - The request sent by the client was syntactically incorrect.
Can somebody help please?
The problem is (a typo?) in your 2nd line of your second.jsp snippet:
<input type="hidden" id="requestQuoteEmailAddress" name="requestEmailAddress" />
The id attribute is mainly for client side reference, and doesn't matter when form is submitted (see HTML input - name vs. id). What's important is the name attribute. So when the POST request is sent to server, the request body looks like:
requestEmailAddress=...&productCodes=...&productCodes=...
Since you annotated the handler method parameter as #RequestParam("requestQuoteEmailAddress"), Spring MVC looks for requestQuoteEmailAddress instead of requestEmailAddress, thus the error (#RequestParam's required is true by default).

Spring MVC Form Not Submitting Value

Resolution
I've now managed to get this working.
It was my own oversight that was causing the null result, and thanks to #WillKeeling for pointing out that I was mapping the form to the wrong controller method.
Rather than creating a new Role object for the form to submit, I was (for an unknown reason) asking it to submit a User object.
My working JSP & Controller below:
<form:form method="POST" action="/users/${user.username}/addRole" modelAttribute="newRole">
<div class="input-group">
<span class="input-group-addon">Roles</span>
<form:select class="form-control" path="rolename" multiple="false">
<form:options items="${roles}" title="rolename" itemValue="rolename" itemLabel="rolename" />
</form:select>
<span class="input-group-addon"><input type="submit" value="Add Role" class="btn btn-xs btn-warning"/></span>
</div>
</form:form>
Controller Mapping
#RequestMapping(value = "/{username}/addRole", method = RequestMethod.POST)
public String addUserRoles(#ModelAttribute("newRole") Role newRole, #PathVariable("username") String username) {
System.out.println(newRole.getRolename());
return "redirect:/users/" + username;
}
Original Question
I may be missing something obvious here but I was hoping someone may be able to help.
I'm building an access management system for the team I work in. I've got a form on a jsp (code below) which should submit a new "role" object that can be handled into the repository in the back end.
At the moment however, when I click submit the logging reports that the value is "null". Can somebody please shed some light on why this is?
Form in JSP
<form:form method="POST" action="/users/${user.username}/addRole" modelAttribute="user">
<div class="input-group">
<span class="input-group-addon">Roles</span>
<form:select class="form-control" path="roles" multiple="false">
<form:options items="${roles}" title="roles" itemValue="rolename" itemLabel="rolename" />
</form:select>
<span class="input-group-addon"><input type="submit" value="Add Role" class="btn btn-xs btn-warning"/></span>
</div>
</form:form>
Controller
Original path is /users with the following controller.
#RequestMapping(value = "/{username}/addRole", method = RequestMethod.POST)
public String addUserRoles(#ModelAttribute("user") User user) {
System.out.println(user.getRoles());
return "redirect:/users/" + user.getUsername();
}
Result in Console
Role [rolename=null]

Adding a Captcha to a PlayFramework 1.2.x login page

I have the task of maintaining a small application written with PlayFramework 1.2.x. One item that needs done: adding a Captcha to the login page. This is apparently harder than one thinks, since the login-page is handled semi-automatically by the Secure module.
When handling a normal HTTP form, the PlayFramework passes the form variables to the controller method as parameters. Using the standard Secure module, the login form contains only the user-name and the password, and these are passed to the authenticate method.
Now, I can create a custom login-form that includes a captcha, and I am also allowed to override the authenticate method in the Secure module. The problem is this: I cannot change the parameters of the authenticate method to include the captcha-code, or else it is no longer overriding the method in the superclass (and the method is then never called).
Here is a simple login form, with the Captcha adapted from the "yabe" example:
#{extends 'main.html' /} #{set title:'Login' /}
#{form #authenticate()}
<p>
<label for="username">User name: </label> <input type="text"
name="username" id="username" maxlength="30"
value="${params.username}" />
</p>
<p>
<label for="password">Password: </label> <input type="password"
name="password" id="password" maxlength="30" " />
</p>
<p>
<label for="code">Please type the code below: </label> <img
src="#{Captcha.captcha(randomID)}" /> <br /> <input type="text"
name="code" id="code" size="18" value="" /> <input type="hidden"
name="randomID" value="${randomID}" />
</p>
<p>
<input type="submit" id="signin" value="Log in" />
</p>
#{/form}
Here is a simple authenticate method that does not work, because "code" and "randomID" are undefined. Again, I cannot just add the parameters to authenticate, or else it no longer overrides the method from the superclass, and is not called.
package controllers;
import play.cache.Cache;
import play.data.validation.Required;
import models.*;
public class Security extends Secure.Security {
static boolean authenticate(String username, String password) {
boolean auth = false;
if (code.equals(Cache.get(randomID))) {
auth = (User.connect(username, password) != null);
}
return auth;
}
}
Question: how can I get the values "code" and "randomID" from the form to the authenticate method? Is there some other way of accessing values from the form?
You are in a Play! controller, so you have access to the object request.params, out of which you can fetch the parameters, as in request.params.get("code").

Send and receive POST request in Playframework

I am writing application on playframework. I have a search form and I want to send POST request and be able to accept it in my controller, how this is possible?
There Many samples for it, First Add a method login in your Application (or whatever) controller.
Lets assume your posting login details for your controller.
public static void login(String userCode,String password){
User loginUser = User.find("byUserCodeAndPassword",userCode,password).first();
if(loginUser == null){
flash.put("username",userCode);
flash.error("Invalid Credentials");
index();
}
else{
Cache.set(session.getId(),loginUser,"20mn");
Home.Home();
}
}
In your conf/routes file add
POST / Application.login
Assuming you have a index.html in your app/views/Application folder.
From the Html Page:
<div id="login">
#{form #login(), id:'formLogin'}
<p class="field">
<label>User Code:</label>
<input type="text" name="userCode" size="19" value="${flash.userCode}" required>
</p>
<p class="field">
<label>Password:</label>
<input type="password" name="password" size="19" required>
</p>
<p class="buttons">
<input type="submit" value="Login">
</p>
#{/form}

form values not submitted to the servlet

I am trying to submit the text field value and print it using the servlet. The index.jsp is my main page and I am using jsp:include to include the form which reside in another page which is login.html.
here is the code i have for login.html
<form id="f1" action="ControllerServlet" method="GET">
<p>username
<input class ="text-input" type="text" id="txtusername" />
</p>
<p>
<input type="submit" value="submit" />
</p>
the index.jsp
<div id="col3_content" class="clearfix">
<h1>H1 Heading</h1>
<jsp:include page="login.html"></jsp:include>
</div>
the controller servlet
String usrname = request.getParameter("txtusername").toString();
out.print(usrname);
The problem is this is throwing a null pointer exception. what am I doing wrong here ? any help appreciated. thanks
Please use name not id
<input class ="text-input" type="text" name="txtusername" />
The id is not used to identify the name of the input parameter. The right attribute for the parameter is name, currently you are using an input without a name. So use
<input class ="text-input" type="text" name="txtusername" id="txtusername" />
You need to define name attribute of input tag to get it in Servlet by name.
<input class ="text-input" type="text" id="txtusername" name="txtusername" />
Also make sure you are writing code in doGet or service method of servlet as you have GET as action in form tag.
Code for Login.html
<form action="ControllerServlet" method="GET">
<p>username :
<input type ="text" name="txtusername" /></p>
<p><input type="submit" value="submit" /> </p>
</form>
ControllerServlet.java
public void service(ServletRequest request, ServletResponse response)
{
String username = request.getParameter("txtusername");
PrintWriter out = response.getWriter();
out.println("User Name " + username)
I faced a similar situation, when I checked front end, the form seems to have all the value populated correctly. However, after form.submit, from server side using request.getParameter("the parameter") does not return the value populated. After tuning on the network traffic tab in browser, I see the parameter was there, but there was a typo.
Hopefully could save you some time if same thing happens to you.

Categories