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?
Related
This question already has answers here:
How should I use servlets and Ajax?
(7 answers)
Closed 5 years ago.
I created a login form which as I wanted to practice ajax from JQUERY. Unfortunately this program is given me unexpected error.
ISSUE
Browser is given me 500 error : NullPointerException
So I printed username and password. Then I saw that for one button click username and password print for two times and for first time it is same values as I entered and second time username is Null password is similar to entered value.And other thing is although I commented out the Ajax part that second scenario is happening (null username and entered password printing)
JSP:
<form action="" style="border:1px solid #ccc" method="post">
<div class="container">
<h2>LogIn Form</h2>
<label><b>Email</b></label>
<input type="text" placeholder="Enter Email" name="email" id="uName" required>
<label><b>Password</b></label>
<input type="password" placeholder="Enter Password" name="psw" id="psw" required>
<div class="clearfix">
<button type="button" class="cancelbtn">Cancel</button>
<button type="submit" class="signupbtn" id="login">LogIn</button>
</div>
</div>
</form>
JQUERY
<script type="text/javascript">
$(document).ready(function() {
alert("qwqw");
$('#login').click(function(){
$.post('userRegistrationServlet',{
uName : $('#uName').val(),
psw : $('#psw').val()},
function(responseText) {
alert(uName);
alert("Login Successfully..!");
});
});
});
</script>
Servlet
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
//PrintWriter out = response.getWriter();
String userName = request.getParameter("uName");
System.out.println(userName+"uName");
String psw = request.getParameter("psw");
System.out.println(psw+"psw");
RequestDispatcher rd;
if(!userName.isEmpty()| userName != null){
rd = request.getRequestDispatcher("/Header.html");
rd.forward(request, response);
}else{
rd = request.getRequestDispatcher("/SignUp.jsp");
rd.forward(request, response);
}
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException{
request.getRequestDispatcher("UserRegistration.jsp").forward(request,response);
}
Please help me to solve this issue..Thank you..!
I'd rather put an event handler on the "submit" event of the form, then call preventDefault() and stopPropagation() on the event:
$("#myform").on("submit", function(e) {
e.preventDefault();
e.stopPropagation();
$.post('userRegistrationServlet',{
uName : $('#uName').val(),
psw : $('#psw').val()},
function(responseText) {
alert(uName);
alert("Login Successfully..!");
});
});
this button type is 'submit' so when you click it your form will be submit coherently but no url path
LogIn
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");
}
}
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.
I have jsp page (say, source.jsp) with form:
<html>
<head>
<body>
<form action="Servlet123" method="POST">
// form fileds ...
</form>
</body>
</head>
</html>
And the required doPost in servlet -
#WebServlet("/Servlet123")
public class Servlet123 extends HttpServlet {
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
//use with requset...
}
}
How can I get the page (in this case - source.jsp) sending the request to this servlet? Is there a method in request/session?
Use passing parameter in a request through a hidden field:
In your jsp page:
<form action="Servlet123" method="post">
<input type="hidden" name="namePage" value="sourcePage" />
</form>
In your servlet:
String namePage = request.getParameter("namePage");
String referer = request.getHeader("referer");
But read Alternative to "Referer" Header
(especially BalusC's answer).
<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");
.......
}