How to Send Post request in java with javax.portlet.ActionResponse.sendRedirect method? - servlets

I want to POST to URL but following making it as GET , so How can I POST the
Object portletResponse = webAppAccess.getHttpServletRequest()
.getAttribute(Constants.PORTLET_RESPONSE);
if (portletResponse instanceof javax.portlet.ActionResponse) {
javax.portlet.ActionResponse actionResponse = (javax.portlet.ActionResponse) portletResponse;
actionResponse.sendRedirect(URL);
}

Have you tried to use RequestDispater instead of response.sendRedirect?
It retains the original request, without changing it.
So, it will remain POST if it was POST.

I have done this by using FORM POST method as follows.
webAppAccess.processPage("importedPage");
Added this imported Page in model :
<HTML>
<HEAD>
<title>New Page</title>
</HEAD>
<Body onload="">
<form id="FormID" method="POST" action="actionURL">
<input type="hidden" name="id" id="ID" value="<%=webAppAccess.getVariables().getString("ID")%>"/>
<noscript>
<p>Your browser does not support JavaScript or it is disabled.
Please click the button below to process the request.
</p>
<input type="submit" value="Proceed " name ="submit"></input>
</noscript>
<script>
document.getElementById('FormID').submit();
</script>
</form>
and then MVC controller mapping as follows:
#RequestMapping(value = {"/Details"}, method = RequestMethod.POST)
public String mthDetails(final Model p_model, #RequestParam(value = "id", required = false) final String p_ID){
//code for further logic using ID
}

Related

Spring MVC is confusing get and post methods with the same request mapping

I have a login controller that I've mapped the "/login" path to two different methods. One will be called for get and the other for post.
#RequestMapping(value = "/login", method = RequestMethod.GET)
public String login(Model model){
LoginDto loginDto = new LoginDto();
model.addAttribute("loginDto", loginDto);
return "home/login";
}
#RequestMapping(value = "/login", method = RequestMethod.POST)
public String doLogin(#Valid LoginDto loginDto, BindingResult bindingResult){
if(bindingResult.hasErrors()){
return "home/login";
}
return "redirect:/";
}
I have the thymeleaf form
<form method="POST" th:action="#{/login}" th:object="${loginDto}">
<div class="form-group-row">
<label> Email </label>
<input type = "text" th:field = "*{email}"/>
<span th:if="${#fields.hasErrors('email')}" th:errors = "*{email}"></span>
</div>
<div>
<label> Password </label>
<input type = "text" th:field = "*{password}"/>
</div>
<input type="submit" />
</form>
When enter data and click submit the method with the GET request is called. I know this from inserting breakpoints in both methods. Also the url now has a ?errors at the end of it. I've also changed the url mapping to the second method to "doLogin" like this
#RequestMapping(value = "/dologin", method = RequestMethod.POST)
public String doLogin(#Valid LoginDto loginDto, BindingResult bindingResult){
if(bindingResult.hasErrors()){
return "home/login";
}
return "redirect:/";
}
and changed the form to this
<form method="POST" th:action="#{/dologin}" th:object="${loginDto}">
<div class="form-group-row">
<label> Email </label>
<input type = "text" th:field = "*{email}"/>
<span th:if="${#fields.hasErrors('email')}" th:errors = "*{email}"></span>
</div>
<div>
<label> Password </label>
<input type = "text" th:field = "*{password}"/>
</div>
<input type="submit" />
</form>
and it works. I can enter data and hit the submit button and I'm in the doLogin method. However, I would like to keep this mapping of GET and POST to the same url to do different things based on the request method.
Further more, when I created the form at first, I forgot to specify a method="post" and while testing it submitted get requests to "/login" from this form. Perhaps that wired something up that needs to be unwired.
Is this a bug? I can map the same url with different request methods to other controller methods but this one doesn't seem to want to work. Any Ideas?
I've figured it out. The reason the method that is mapped to the POST request is because I'm using spring security and it's not completely set up. The login page for spring security was mapped to /login as well and the appended
localhost/login?error
to the url string is something spring security appends when there is an error with the login process. I have not set up authentication with spring security yet so it believes there's an error. I will continue on setting up spring security but this is the reason my POST request was not mapped to the doLogin method.

Error uploading file from form-data to Spring Server

I am uploading a picture using form-data taking the picture from the Client's PC to Spring MVC Server.
Update Page:
<!DOCTYPE html >
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Spring MVC - Upload File</title>
</head>
<body>
<form id="form1" method="post" action="/upload" enctype="multipart/form-data" accept-charset="utf-8">
<!-- File input -->
<input name="file" id="file" type="file" /><br/>
<input type="submit" value="Upload" />
</form>
</body>
</html>
And this is the Spring Controller
#RequestMapping(value = "upload", method = RequestMethod.POST)
public #ResponseBody
String provaUpdate(MultipartHttpServletRequest request,Principal p,HttpServletResponse response)throws IOException {
String result="";
LocalFileManager mLocalFileManager = LocalFileManager.get();
Iterator<String> iterator = request.getFileNames();
while(iterator.hasNext())
{
System.out.println("iterator.next()="+iterator.next());
}
System.out.println("request.getFileMap().isEmpty()??"+request.getFileMap().isEmpty());
// mLocalFileManager.saveLocalData(g,g.getPicturesCount(), request.getFile("new").getInputStream());
return result;
}
So, when i run that, it just prints:
request.getFileMap().isEmpty()??true
Then, no Files seems to be uploaded, but if I get the request.getInputStream() I can write a TXT File showing that:
------WebKitFormBoundaryWG8vA5PuTFFxPBqK
Content-Disposition: form-data; name="file"; filename="1.jpg"
Content-Type: image/jpeg
�� JFIF ��ICC_PROFILE 蠠 mntrRGB XYZ ٠ $ acsp �� ӭ )𽞯򕮸B򤊃9
desc D ybXYZ bTRC Ԡ dmdd ࠠ ɧXYZ
h gTRC Ԡ lumi
| meas
//(Symbols) Long ETC, so the picture is sent !!
------WebKitFormBoundaryWG8vA5PuTFFxPBqK--
So, seems that the picture is sent correctly but the MultipartHttpServletRequest is not able to get the File.
Which is my mistake?
I think,you may be missing below entry in your spring configuration xml file.
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- below properties can be configured as per your need -->
<property name="maxUploadSize" value="5000000" />
<property name="maxInMemorySize" value="5000000" />
</bean>
The mistake was that i am working with Thymeleaf, so the form is different.
It is solved changing that:
1- Create a class that contains a MultipartFile, like this:
public class Images {
MultipartFile image;
public MultipartFile getImage() {
return image;
}
public void setImage(MultipartFile image) {
this.image = image;
}
}
2- The correct form code for a Spring Server working with Thymeleaf:
<form id="myform" action="#" th:action="#{/upload}" th:object="${Images}" method="POST" modelAttribute="Images" enctype="multipart/form-data">
<input type="file" th:field="${Images.image}" name="file"/>
<input type="submit" value="Upload"/>
</form>
And finally the correct Controller method:
#RequestMapping(value = "upload", method = RequestMethod.POST)
public String addVocabularyValadate( #ModelAttribute("Images") Images images,BindingResult bindingResult,
Model model) throws IOException
{
System.out.println("inputstream Nombre!"+images.getImage().getOriginalFilename());
if(bindingResult.hasFieldErrors() == true)
return "error";
else
return "upload OK!";
}

Forward and pass data along in Asp.net

In Asp.net Entity Framework I need to forward to another page and pass some data processed by the second page along.
In PHP I could do something like
<!-- page1.php -->
<form action="page2.php" method="POST">
<input type="hidden" name="id" />
<input type="submit" value="Go to page 2" />
</form>
<!-- page2.php -->
<?php
echo $_POST['id'];
?>
How can this be implemented in Asp.net?
Edit: There is a simple solution using Javascript and jQuery.
<!-- on page 1 -->
$('input[type=submit]').on('click', function (e) {
// Forward to browsing page and pass id in URL
e.preventDefault();
var id= $('input[name=id]').val();
if ("" == id)
return;
window.location.href = "#Request.Url.OriginalString/page2?id=" + id;
});
<!-- on page 2 -->
alert("#Request.QueryString["id"]");
There are, at least, two options:
Session state, like this:
Putting data into Session (your first page)
Session["Id"] = HiddenFieldId.Value;
Getting data out of Session (your second page)
// First check to see if value is still in session cache
if(Session["Id"] != null)
{
int id = Convert.ToInt32(Session["Id"]);
}
Query string, like this:
Putting the value into the URL for the second page as a query string
http://YOUR_APP/Page2.aspx?id=7
Reading the query string in the second page
int id = Request.QueryString["id"]; // value will be 7 in this example
There's a lot of ways to do this, take a look at this link for some guidance.
HTML page:
<form method="post" action="Page2.aspx" id="form1" name="form1">
<input id="id" name="id" type="hidden" value='test' />
<input type="submit" value="click" />
</form>
Code in Page2.aspx:
protected void Page_Load(object sender, EventArgs e)
{
string value = Request["id"];
}
MVC would look like...
#using (Html.BeginForm("page2", "controllername", FormMethod.Post))
{
#Html.Hidden(f => f.id)
<input type="submit" value="click" />
}
also, read through these MVC tutorials, you shouldn't blindly translate what you know in PHP to ASP.NET MVC, since you need to learn the MVC pattern too.
You can also use <form> with method="POST" in ASP.NET. And get value in code:
int id = int.Parse(Request.Form["id"]);

get the value sent by ajax

I have:
<form method="POST" name="f">
<input type="file" name="FileUpload" id="FileUpload" />
</form>
I'm sent the file using ajax,using the uplaod.file method:
document.getElementById('FileUpload').onchange = function() {
file = this.files[0];
ajax = new XMLHttpRequest;
ajax.file = file;
//etc..
ajax.open('post','Default.aspx', true);
ajax.setRequestHeader('foo','baa');
ajax.send(file);
}
Request.Forms["FileUplaod"] // don't works
How I get the value (the file) sent by ajax in my asp.net application?
I tried sent by http headers(is not pratice good,I know) but there problem with long length.
Thanks in advance.
try this form attribute :
form action="some/action" method="POST" enctype="multipart/form-data"

POST data getting 'lost' somewhere

UPDATE
So it turns out internet exploder's stranglehold on "security" to "make up" for being so bad at security was causing my problems. I should have checked that out first haha. Thanks everyone for the input, it has given me ideas on how to optimize my application :D
I am writing a web app (in ASP.NET 3.5) that integrates with a platform app. The platform app takes the user's credentials and puts them into an "empty" HTML page that consists of a form with hidden items containing said credentials and POSTS to the webapp (default.aspx):
<HTML>
<HEAD>
<SCRIPT LANGUAGE=JSCRIPT>
function OnLoad(){
try {
document.form1.submit();
}
catch(e){
}
}
</SCRIPT>
</HEAD>
<BODY OnLoad="OnLoad()">
<FORM ACTION="http://localhost:51816/gs_ontheweb/default.aspx" METHOD=POST NAME=form1 TARGET="_NEW">
<INPUT TYPE="HIDDEN" NAME="ClientID" VALUE="123456">
<INPUT TYPE="HIDDEN" NAME="Password" VALUE="2830088828">
<INPUT TYPE="HIDDEN" NAME="PracType" VALUE="051">
<INPUT TYPE="HIDDEN" NAME="Encrypt" VALUE="12345620081111">
</FORM>
</BODY>
</HTML>
When my default.aspx page gets loaded up, it calls the following function:
Dim ClientID As String = Request.Form("ClientID")
Dim PassWord As String = Request.Form("Password")
Dim PracType As String = Request.Form("PracType")
Each one of them result in empty strings. Any ideas on why this is happening? Thanks in advance.
EDIT: Is there something I need to configure in my web.config file to make this work properly? Request.Params("<param name>") does not work.
Your issue is the "Target" property on the Form. Why is this here?
(I also took the liberty of cleaning your HTML up a little)
<html>
<head>
<title>Test JS Post</title>
<script type="text/javascript" language="javascript">
<!--
function OnLoad(){
try
{
alert("Posting...");
document.form1.submit();
}
catch(e)
{
alert("ERROR!");
alert(e);
}
}
//-->
</script>
</head>
<body onload="OnLoad()">
<form action="http://localhost:49684/Default.aspx" method="post" name="form1">
<input type="hidden" name="ClientID" value="123456" />
<input type="hidden" name="Password" value="2830088828" />
<input type="hidden" name="PracType" value="051" />
<input type="hidden" name="Encrypt" value="12345620081111" />
<h1>This is in the form. Submit me here:</h1><input type="submit" value="foo" />
</form>
</body>
</html>
In the code behind of Default.aspx:
Private Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init
For Each value As String In Request.Form.Keys
Debug.WriteLine(String.Format("{0} = ""{1}""", value, Request.Form.Item(value)))
Next
End Sub
That HTML is just on the user's harddrive? Maybe the browser security won't let that POST because it's deemed to be a risk.
As a test -- take that exact HTML file and put it on your webserver and then browse to it. If it works, might be the browser refusing to send the data. You could check with Fiddler (for IE) or Firebug in FireFox.
Why not use System.Net.WebClient?
Some sample code (sorry, it's C#. Looks like your looking for VB. I can't translate quickly.)
System.Net.WebClient wc = new System.Net.WebClient();
byte[] b;
byte[] res;
string formdata = "text=test text&password=secret&checkbox=on&textarea=a longer text sentence&submit=submit";
// encode the form data string into a byte array
b = System.Text.Encoding.ASCII.GetBytes(formdata);
// set the content type for a form
wc.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
// POST and get data
res = wc.UploadData("http://localhost:51816/gs_ontheweb/default.aspx", b);
//convert the return page from byte[] to ascii
string s = System.Text.Encoding.ASCII.GetString(res);

Resources