Integer.parseInt() doesn't parse String "id" from servlet url parameter - java

I have a .jsp page that lists all of my employees from a database. Next to each employee you can click on the button edit or delete, which will add an id of that employee into url param:
<%
List<Employee> employees = (List<Employee>) request.getAttribute("employees");
if (employees != null)
for (Employee employee : employees) {
%>
<tr>
<td><%=employee.getId()%></td>
<td><%=employee.getName()%></td>
<td><%=employee.getSurname()%></td>
<td><%=employee.getRegistrationDate()%></td>
<td>edit</td>
<td>delete</td>
</tr>
<%
}
%>
When I click on 'delete', the listing is being deleted straight away and I get immediately redirected back to the list of my employees, it works well.
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
int id = (int) request.getAttribute("id");
EmployeeDAO.deleteEmployee(id);
response.sendRedirect("EmployeeServlet");
}
When I click on 'edit', I see te .jsp that has the url with the correct id and it asks me to provide new name and surname of my employee:
<form action="UpdateEmployeeServlet" method="post">
Name <input type="text" name="name"><br>
Surname <input type="text" name="surname"/><br>
<input type="submit"value="Save">
Once i click 'save', I get NullPointerException. It seems like it cannot get or parse the id parameter. Where is an error in my UpdateEmployeeServlet methods?
#WebServlet("/UpdateEmployeeServlet")
public class UpdateEmployeeServlet extends HttpServlet {
public UpdateEmployeeServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
int id = Integer.parseInt(request.getParameter("id"));
Employee employee = EmployeeDAO.getEmployeeById(id);
request.getRequestDispatcher("updateemployee.jsp").forward(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Employee employee = new Employee((int) request.getAttribute("id"), request.getParameter("name"),
request.getParameter("surname"), Date.valueOf(request.getParameter("registration_date")));
int status = EmployeeDAO.updateEmployee(employee);
request.getRequestDispatcher("employeelist.jsp").forward(request, response);
}
}

Integer.parseInt tries to convert a String to an Integer and will throw an Exception if it fails to do so. Since you get a NullPointerException, it is clear that request.getParameter("id") is null. The reason of this is that your form does not contain any items with the name of id. Try to add a hidden input to the form there with name="id" and the correct value. It should solve your problem.

Doing form handling with Servlets is really low-level and there is no need to reinvent the wheel. You should consider using Spring MVC which has excellent support for form handling.
Having said that check the parameters of your <form>. You are handing over name, surname and submit to doPost(). There is no id given. Furthermore as pointed out already you are using request.getAttribute("id") instead of request.getParameter("id").
You could set your object to request scope in your doGet()-method: request.setAttribute("employee", employee). You would then access the fields of this object in your JSP. Add this to your form: <input type="hidden" value="${requestScope.employee.id}"/>. You should also mask your IDs (e.g. HashIds) and read about CSRF

Related

How to retrieve json obj value in my jsp web project from a form

In mydemo.java I have this code:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
JsonObject person = new JsonObject();
person.addProperty("firstName", "Andrew");
person.addProperty("lastName", "Coolins");
person.addProperty("address", " xx september");
String person= request.getParameter("firstname");
and my output for json string is:
{"firstName":"Andrew","lastName":"Coolins","address":" xx september"}
In mydemo2.java in method post, I want to add something like this:
String jsonobj= request.getParameter("firstname"); //for example
request.setAttribute("firstname", firstname); //for example
request.getRequestDispatcher("index.jsp").forward(request, response);
My question is, how can I retrieve values for example "firstname" of json obj from a form in my index.jsp when the user insert data for firstname and then clicks on submit button? Can you explain to me with code?
For example, you can add something like this to your jsp page
<form method=post action =someServlet>
<input type="text" name="firstname"/>
<input type=submit value="Do something"/>
</form>
Then in your servlet
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
String firstname = request.getParameter("firstname");
//do something
}
I didn’t fully understand the question, did you ask about this?

JSP servlet not executing doPost method

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");
}
}

ModelAndView not working properly [duplicate]

This question already has answers here:
Show JDBC ResultSet in HTML in JSP page using MVC and DAO pattern
(6 answers)
Closed 6 years ago.
I have written the code in java. All the things are working properly. I just want to return the value of modelandview that is not returning correct web page. It is throwing blank page. The code of my controller is:
public class Part3 extends HttpServlet {
Num num = new Num();
String name[];
Record record = null;
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ModelAndView mv = new ModelAndView();
String number = request.getParameter("number");
num.setNumber((number));
Driver driver = GraphDatabase.driver("bolt://localhost", AuthTokens.basic("neo4j", "neo4j"));
Session session = driver.session();
StatementResult result = session.run("MATCH (tom {name: '" + number + "'}) RETURN tom.name, tom.born, tom.roles;");
while (result.hasNext()) {
record = result.next();
}
session.close();
driver.close();
request.setAttribute("selectObject", record);
mv.setViewName("index");
return mv;
}
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException {
try {
handleRequest(request, response);
} catch (IOException ex) {
Logger.getLogger(Part3.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
My HTML page is index.html and its code is:
<form action ="number" name ="number">
<b>Enter Song ID:</b>
<input type="text" name='number' required placeholder="Enter SongID"><br /><br /><br />
<input type="submit" value="Submit" class="btn btn-primary" style="background-color: orangered"/>
</form>
${selectObject}
</div>
ModelAndView is a spring mvc object. You cannot use it in a servlet.
Your servlet is doing nothing, in a servlet you need to write to the object HttpServletResponse.
What do you try to do with this code handleRequest(request, response); ?
update :
First, In your object reponse, you can get a PrintWriter : response.getWriter(). Write response in this writer.
Second, delete ModelAndView, you don't need it. Try to understand what is a servlet before using Spring MVC.
Here is a simple example : http://www.tutorialspoint.com/servlets/servlets-first-example.htm

Paypal Integration on Java web applicaton

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.

reading the form data in servlet. data posted with post method and servlet called with ?q=test1

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");

Categories