Currently, I am successful in making the first call to the
https://api-3t.sandbox.paypal.com/nvp
which brings me back the TOKEN and ACK which is of course successful... now the problem is how to capture the values from these variables. I couldn't think a way. Can somebody help me getting these values in my servlet so that i could compare and manipulate other steps for online payment !
Thanks in advance !
This is the form i send to https://api-3t.sandbox.paypal.com/nvp
<input type="text" name="USER" value="rspunk07-facilitator_api1.hotmail.com" /><br/>
<input type="text" name="PWD" value="1402570771" /><br/>
<input type="text" name="SIGNATURE" value="AOgUKQLphsryE4s2aIWzkssJyVf3ALKhcP5TZ2W4CnDz.bAbL.WoCv9q" /><br/>
<input type="text" name="METHOD" value="SetExpressCheckout" /><br/>
<input type="text" name="VERSION" value="98" /><br/>
<input type="text" name="PAYMENTREQUEST_0_AMT" value="10" /><br/>
<input type="text" name="PAYMENTREQUEST_0_CURRENCYCODE" value="USD" /><br/>
<input type="text" name="PAYMENTREQUEST_0_PAYMENTACTION" value="SALE" /><br/>
<input type="text" name="cancelUrl" value="http://localhost:8084/E-Drivers_Licensing_System/onlinepayment.jsp" /><br/>
<input type="text" name="returnUrl" value="http://localhost:8084/E-Drivers_Licensing_System/success.jsp" /><br/>
<input type="submit" name="h" value="Register"/>
<input type="reset" name="cancel" value="Cancel"/><br/>
In response to this, i get TOKEN=EC%2d08371303KU3173044&TIMESTAMP=2014%2d06%2d17T10%3a32%3a09Z&CORRELATIONID=26d5a8792d431&ACK=Success&VERSION=98&BUILD=11457922 in the same url https://api-3t.sandbox.paypal.com/nvp
Now, the problem i have is, to capture the details provided in the url from my servlet
public class OnlinePaymentController extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
} finally {
out.close();
}
}
How do i do that ?
// This method is called by the servlet container to process a GET request.
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
doGetOrPost(req, resp);
}
// This method is called by the servlet container to process a POST request.
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
doGetOrPost(req, resp);
}
// This method handles both GET and POST requests.
private void doGetOrPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
// Get the value of a request parameter; the name is case-sensitive
String name = "param";
String value = req.getParameter(name);
if (value == null) {
// The request parameter 'param' was not present in the query string
// e.g. http://hostname.com?a=b
} else if ("".equals(value)) {
// The request parameter 'param' was present in the query string but has no value
// e.g. http://hostname.com?param=&a=b
}
// The following generates a page showing all the request parameters
PrintWriter out = resp.getWriter();
resp.setContentType("text/plain");
// Get the values of all request parameters
Enumeration enum = req.getParameterNames();
for (; enum.hasMoreElements(); ) {
// Get the name of the request parameter
name = (String)enum.nextElement();
out.println(name);
// Get the value of the request parameter
value = req.getParameter(name);
// If the request parameter can appear more than once in the query string, get all values
String[] values = req.getParameterValues(name);
for (int i=0; i<values.length; i++) {
out.println(" "+values[i]);
}
}
out.close();
}
I think the problem is, you don't really want to redirect the user to Paypal since the paypal API response is not designed to be passed back directly to the user.
Instead your Servlet needs to act as a client so the flow would be the following:
User fills out form and submits
Form is submitted to your Servlet rather than the API directly
Your Servlet makes a request to the API using a Java HTTP client such as http://hc.apache.org/httpcomponents-client-ga/
Your Servlet parses and decodes the response from the paypal API
You Servlet forwards to a jsp representing the next step in the payment process.
Presumably all you want is the token which you can then pass back to the client to be written as a hidden field and submitted in the next step.
I'm not very familiar with the PayPal APIs but I would recommend exploring their documentation further to make sure this is the best way to access their services.
Related
I'm very new to java Servlets and the whole integration with HTML so this may be a recurring question, I'm sorry.
I'm supposed to add doPost() to the controller "AddToWaitingList.java" where it should save the name entered in "addClientToWaitingList.html" in the array of class "TheRestaurant"; It also should respond to the request with JSP "addClientToWaitingListResponse.jsp";
This is what I did:
<p>Add client to waiting list:
<form method="post" action="waitingList">
<input type="text" id="add-client-to-waiting-list" name="name" /> <input
type="submit" id="add-client-to-waiting-list-button"
value="Add client to waiting list" />
</form>
<script type="text/javascript">
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String name = request.getParameter("name");
if (name == null)
name = "World";
request.setAttribute("TheRestaurant", name);
request.getRequestDispatcher("addClientToWaitingListResponse.jsp").forward(request, response);
}
</script>
It shows "HTTP ERROR 405 HTTP method POST is not supported by this URL". What am I supposed to do?
I have recently started programming in java and have been trying out some JSP development. I am trying to make a login page which uses the POST method to transfer data to the servlet. Here is my code:
<form method="POST" name ="loginForm" action="userAuth">
<input type="hidden" name="userAction" value="login">
Username: <input type="text" name="txtUsername"> <br>
Password : <input type="password" name="txtPassword">
<br><input type="submit" value="Login">
</form>
The above code is from the initial login page.
The code below is from the userAuth.java file.
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
String userAction = request.getParameter("userAction");
if (userAction.equals("Login")) {
String userName = request.getParameter("txtUsername");
String passWord = request.getParameter("txtPassword");
if (userName.equals("hello") && passWord.equals("hello")) {
response.sendRedirect("Homepage.jsp");
}
}
}
The problem I have is that when I input the correct username and password, the doPost method is not executed, so none of the redirects take place. Rather only the ProcessRequest method is executed which just displays the initial template to the web browser.
Thank you in advance.
P.S I am using Apache Tomcat 8.0.27.0
I have solved the issue...
The issue was with the following line
<input type="hidden" name="userAction" value="**login**">
and the subsequent processing in the second block:
if (userAction.equals("**Login**")) {}
The login value didnt have an uppercase L.
Just changed this.
What does the processRequest() method do? If executes as you say then the server gives a response to the client and the remaining block of code does not execute. Have you tried to run without this function?
Hide the process request method.
Like this:
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//processRequest(request, response);
String userAction = request.getParameter("userAction");
if (userAction.equals("Login")) {
String userName = request.getParameter("txtUsername");
String passWord = request.getParameter("txtPassword");
}
}
I have created two forms in my jsp. 1st one is an upload functionality and other is the submit page functionality. My requirement is to upload the file using upload functionality. and if upload is successful . The pass the file name back to jsp and on submit button pass the file name along with other details to other page.
My code:
MyJsp.jsp
</tr>
<tr>
<td colspan="2" rowspan="2" align="center"> <form action="UploadDownloadFileServlet" method="post"
enctype="multipart/form-data" class="CSSTableGenerator">
Select the Raw Data Sheet of Customer : <input type="file"
name="fileName" class="button"> <input type="submit" value="Upload"
class="button">
</form>
<form action="DataController" method="post" >
<input type="submit" name="listUser" value="Confirm Selection"
class="button" align="middle">
</form>
</td>
</tr>
</table>
My Controller (Servlet):
UploadDownloadFileServlet.java
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
if(!ServletFileUpload.isMultipartContent(request)){
throw new ServletException("Content type is not multipart/form-data");
}
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.write("<html><head></head><body>");
try {
List<FileItem> fileItemsList = uploader.parseRequest(request);
Iterator<FileItem> fileItemsIterator = fileItemsList.iterator();
while(fileItemsIterator.hasNext()){
FileItem fileItem = fileItemsIterator.next();
System.out.println("FieldName="+fileItem.getFieldName());
System.out.println("FileName="+fileItem.getName());
System.out.println("ContentType="+fileItem.getContentType());
System.out.println("Size in bytes="+fileItem.getSize());
String fileName = fileItem.getName().substring(fileItem.getName().lastIndexOf("\\") + 1);
System.out.println("FILE NAME>>>>"+fileName);
File file = new File(request.getServletContext().getAttribute("FILES_DIR")+File.separator+fileName);
System.out.println("Absolute Path at server="+file.getAbsolutePath());
fileItem.write(file);
HttpSession session = request.getSession();
session.setAttribute("Success", "Success");
getServletContext().getRequestDispatcher("/Welcome.jsp").forward(request, response);
/*out.write("File "+fileName+ " uploaded successfully.");
out.write("<br>");
out.write("Download "+fileName+"");*/
}
} catch (FileUploadException e) {
out.write("Exception in uploading file.");
HttpSession session = request.getSession();
session.setAttribute("Failed", "Failed");
getServletContext().getRequestDispatcher("/Welcome.jsp").forward(request, response);
} catch (Exception e) {
out.write("Exception in uploading file.");
HttpSession session = request.getSession();
session.setAttribute("Failed", "Failed");
getServletContext().getRequestDispatcher("/Welcome.jsp").forward(request, response);
}
out.write("</body></html>");/**/
}
}
My Next Contoller for submit button which needs value:
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String upload = (String)request.getAttribute("Success");
if(upload.equalsIgnoreCase("Success")){
System.out.println("SERVLET DOPOST");
String action = (String) request.getAttribute("DownLoadToExcel");
System.out.println(action);
String[] kpi = request.getParameterValues("kpi");
how is it possible in jsp to know that upload was successful and submit should go forward else give an error.
Awaiting reply.
Thanks,
MS
First, after UploadDownloadFileServlet successfully receives and process the upload, you should make it go back to the JSP. You need to "redirect it" to "MyJsp.jsp".
HttpServletResponse.sendRedirect("MyJsp.jsp?fileName2="+fileName);
//- you can also call sendRedirect from a PrintWriter -
Then, in the 2nd form in the JSP you could use something (javascript, scriptlets, a tag library, a custom tag, etc) to detect the parameter "fileName2" and set a hidden input with the name of the file.
Keep in mind you don't sendRedirect() and forward() for the same response.
You can pass as many parameters as you want together with the file name.
<c:forEach var="it" items="${sessionScope.projDetails}">
<tr>
<td>${it.pname}</td>
<td>${it.pID}</td>
<td>${it.fdate}</td>
<td>${it.tdate}</td>
<td> Related Documents</td>
<td>${it.pdesc}</td>
<form name="myForm" action="showProj">
<td><input id="button" type="submit" name="${it.pID}" value="View Team">
</td>
</form>
</c:forEach>
Referring to the above code, I am getting session object projDetails from some servlet, and displaying its contents in a JSP. Since arraylist projDetails have more than one records the field pID also assumes different value, and the display will be a table with many rows.
Now I want to call a servlet showProj when the user clicks on "View Team" (which will be in each row) based on the that row's "pID".
Could someone please let me know how to pass the particular pID which the user clicks on JSP to servlet?
Instead of an <input> for each different pID, you could use links to pass the pID as a query string to the servlet, something like:
View Team
In the showProj servlet code, you'll access the query string via the request object inside a doGet method, something like:
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
String pID = request.getParameter("pID");
//more code...
}
Here are some references for Java servlets:
HttpServletRequest object
Servlet tutorials
Pass the pID along in a hidden input field.
<td>
<form action="showProj">
<input type="hidden" name="pID" value="${it.pID}">
<input type="submit" value="View Team">
</form>
</td>
(please note that I rearranged the <form> with the <td> to make it valid HTML and I also removed the id from the button as it's invalid in HTML to have multiple elements with the same id)
This way you can get it in the servlet as follows:
String pID = request.getParameter("pID");
// ...
Define onclick function on the button and pass the parameter
<form name="myForm" action="showProj">
<input type='hidden' id='pId' name='pId'>
<td><input id="button" type="submit" name="${it.pID}" value="View Team" onclick="populatePid(this.name)">
</td>
.....
Define javascript function:
function populatePid(name) {
document.getElementById('pId') = name;
}
and in the servlet:
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
String pID = request.getParameter("pId");
.......
}
Hey I am trying to read the form data in a servlet sent with post method. And the servlet is called as OnlineExam?q=saveQuestion. Now the servlet is working as:
public class OnlineExam extends HttpServlet {
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
if(request.getParameter("q").equals("saveQuestion")){
/*
* Save the question provided with the form as well as save the uploaded file if any.
*/
saveQuestion(request);
}
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
// doGet(request, response);
saveQuestion(request);
}
public String saveQuestion(HttpServletRequest request){
System.out.println(request.getParameter("question"));
return "";
}
}
HTML form:
<form action="OnlineExam?q=saveQuestion" method="post">
<fieldset>
<legend>Question</legend>
<textarea class="questionArea" id="question" name="question">Enter Question.</textarea>
<br class="clearFormatting"/>
<input class="optionsInput" value="optionA" name="optionA" onfocus = "clearValues('optionA')" onblur = "setValues('optionA')"/>
<br class="clearFormatting"/>
<input class="optionsInput" value="optionB" name="optionB" onfocus = "clearValues('optionB')" onblur = "setValues('optionB')"/>
<br class="clearFormatting"/>
<input class="optionsInput" value="optionC" name="optionC" onfocus = "clearValues('optionC')" onblur = "setValues('optionC')"/>
<br class="clearFormatting"/>
<input class="optionsInput" value="optionD" name="optionD" onfocus = "clearValues('optionD')" onblur = "setValues('optionD')"/>
<br/>
<input class="optionsInput" value="answer" name="answer" onfocus="clearValues('answer')" onblur="setValues('answer')"/>
<input type="submit" value="Save" />
<input type="reset" value="Cancel" />
<button style="display: none" onclick="return deleteQuestion()" >Delete</button>
</fieldset>
</form>
So can anyone illustrate how the servlet is actually called. I mean what is the flow of control i.e. how the things works in this servlet.
And how could i read the param1 there in servlet.
ps: i don't want to post form with get method.
You should get the value of q in your doPost not in your doGet. Because you use method="post" then in the servlet the doPost is the one that called not the doGet. Remove the code in your doGet then insert it to doPost. And you doPost must be something like below code.
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
if(request.getParameter("q").equals("saveQuestion")){
saveQuestion(request);
}
}
Is this solved ?
I am facing same problem.
I tried
Enumeration paramNames = request.getParameterNames();
while(paramNames.hasMoreElements()) {
System.out.println((String)paramNames.nextElement());
}
and it's showing 0 elements, so form data is not being read by servlet.
I got the answer in other thread.
enctype=multipart/form-data was causing this. After removing it from form, was able to read data.
if you POST data to servlet.
doPost will get invoked.
Inside doPost() you can access request param like
request.getParameter("param1");
When you click the "submit" button on your form, the doPost method of your servlet will be called - this is dictated by the method that you put on the "form" in your HTML page. The URL parameters ( q=saveQuestion ) will still be available to your code in the doPost method. You seem to be under the impression that the URL parameters will be processed by the doGet method and the form parameters by the doPost method. That is not the case.
doPost() {
processRequest(request, response);
//to do
}
Remove/comment processRequest(request, response) and try it again. Now you should not get null values.
I know this is an old thread but could not find an answer to this when I searched so I am posting my solution for someone who may have the same issue with getting null from form parameters in the dopost function of their servlet.
I had a similar issue getting null values when using the request.getParameters("param1"); functions. After hours of playing around with it I realized that the param1 that I was using was the ID for the input tag I was requesting. That was wrong. I had to use the NAME attribute of the input tag to get the correct value of the input box. That was all it was. I just had to add a name and get the parameter using this name and that fixed the issue.
Hope this helps someone.
Vinit try the below code
request.getParameter("param1");