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");
}
}
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?
So this is the code i'm using to send the parameter "idemp" that contains the value ${masession.idemp}
<a href="<c:url value="/consultertickets">
<c:param name="idemp" value="${masession.idemp}"/>
</c:url>">
<img src="<c:url value="/inc/liste.png"></c:url>" alt="consulter tickets" />
</a>
when redirected to the servlet "/consultertickets" the browser URL shows:
http://localhost:4040/monprojet2/consultertickets?idemp=64
so the parameter is passed and working but the method used to obviously GET and not POST, which is the method i'm using in the servlet, here's the servlet's code.
#WebServlet(urlPatterns= {"/consultertickets"})
public class ConsulterTickets extends HttpServlet {
private String VUE = "/WEB-INF/ListeTickets.jsp";
#EJB
private TicketDao ticketDao;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.getServletContext().getRequestDispatcher(VUE).forward(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
CreationTicketForm ticketform = new CreationTicketForm(ticketDao);
List<Ticket> lticket = ticketform.recupererTickets(request);
boolean resultat;
if(lticket.isEmpty())
{
//resultat="Vous n'avez soumit aucun ticket";
resultat = false;
request.setAttribute("resultat", resultat);
this.getServletContext().getRequestDispatcher("/ListeTickets2.jsp").forward(request, response);
}else{
//String VUE = "/ListeTickets.jsp";
resultat=true;
request.setAttribute("resultat", resultat);
request.setAttribute("lticket", lticket);
this.getServletContext().getRequestDispatcher(VUE).forward(request, response);
}
}
}
is there any way to pass a parameter to a servlet through POST method, without going through the <form></form>
Solution 1:
Modifying doGet method
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//this.getServletContext().getRequestDispatcher(VUE).forward(request, response);
doPost(request, response);
}
Solution 2:
Remove the doGet() and change doPost() to service()
Edit1:
See, Hyperlinks(<a> tag) are meant to send GET request but not POST.
So, if you want to achieve sending POST request using Hyperlink there is no straight way. But, Javascript can be your help.
Using Javascript you can guide <a> to send POST request along with the help of <form>.
I just modified your code little bit. This should help you.
<a href="javascript:document.getElementById('form1').submit()">
<img src="<c:url value="/inc/liste.png"></c:url>" alt="consulter tickets" />
</a>
<form action="<c:url value="/consultertickets"/>" method="post" id="form1">
<input type="hidden" name="idemp" value="${masession.idemp}"/>
</form>
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 am trying to implement a simple login servlet but it's not working properly.
What I wanted to know is how to pass the parameters using a HTTP POST. It already works with HTTP GET but the username and password are visible from the URL. It would be better to hide them in a POST.
<form method="post" action="home" >
<input name="username" class="form-login" title="Username" value="" size="30" maxlength="2048" />
<input name="password" type="password" class="form-login" title="Password" value="" size="30" maxlength="2048" />
<input type="submit" value="Connect">
</form>
web.xml
<servlet>
<servlet-name>home</servlet-name>
<servlet-class>controller.HomeController</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>home</servlet-name>
<url-pattern>/home</url-pattern>
</servlet-mapping>
Servlet:
public class HomeController extends HttpServlet {
private HttpSession session;
private UserBean userBean;
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
UserBean user = new UserBean();
String userName = request.getParameter("username");
String password = request.getParameter("password");
user.setUsername(userName);
user.setPassword(password);
user = UserDAO.login(user);
dispatch(request, response, ApplicationRessource.getInstance().getHomePage());
}
protected void dispatch(HttpServletRequest request,
HttpServletResponse response, String page)
throws javax.servlet.ServletException, java.io.IOException {
RequestDispatcher dispatcher = getServletContext()
.getRequestDispatcher(page);
dispatcher.forward(request, response);
}
}
The problem is that the userName and password strings are always empty, meaning that the parameters are never fetched from the POST. What am I doing wrong?
it should work, can you check by changing form method to get and trying, you should see parameters in url.
Please try this
In your doPost(..) method code only doGet(..) and put all your logic in doGet(..) and check if still it is giving blank values.
Let me know what is the output.
Example:-
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request,response);
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
UserBean user = new UserBean();
String userName = request.getParameter("username");
String password = request.getParameter("password");
user.setUsername(userName);
user.setPassword(password);
user = UserDAO.login(user);
dispatch(request, response, ApplicationRessource.getInstance().getHomePage());
}
this simple implementation should have worked ..but since its not, there maybe some code which is manipulating the request. The code you have posted is not sufficient to determine that.
Some pointers I can give are -
Check your web.xml to see if there is any filter/interceptor which is manipulating the request.
Which web/app server are you using? Have you checked the service(Http...) method implementation of HttpServlet. You can try placing a debug point in service(..) method to see if the request object here has the required request parameters. If it doesn't, then the problem exists either in some filter or your jsp itself.
What does dispatch(request, response, ApplicationRessource.getInstance().getHomePage()); do? I know the problem is before this line, but this is not a standard HttpServlet method, so I assume there's lot more custom code then whats been posted in the question above.
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");