Sheetal Jain
Sheetal Jain

Reputation: 105

fetch data from servlet sent from another servlet

I am trying to pass data from one servlet to another servlet but when I fetch it from another servlet its returning null.

ViewServlet.java

 @WebServlet("/ViewServlet")
public class ViewServlet extends HttpServlet {
private static final long serialVersionUID = 1L;

/**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
 */
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    response.setContentType("text/html");
    PrintWriter out=response.getWriter();
    out.println("<a href='index.html'>Add New Employee</a>");
    out.println("<h1>All Employees</h1>");
    List<Employee> emp=EmpDao.getAllEmployees();
    out.print("<table width='50' border='1'>");
    out.print("<tr><th>Id</th><th>Username</th><th>email</th><th>country</th><th>Edit</th><th>Delete</th></tr>");
    for(Employee e:emp){
        System.out.println("in view "+e.getId());
    out.print("<tr><td>"+e.getId()+"</td><td>"+e.getUsername()+"</td><td>"+e.getPassword()+"</td><td>"+e.getEmail()+"</td><td>"+e.getCountry()+"</td><td><a href='EditServlet?id"+e.getId()+"''>edit</a></td><td><a href='DeleteServlet?id"+e.getId()+"'>Delete</a></td></tr>");
    }
    out.println("</table>");
}

Here in this class I am trying to send id to my another servlet EditServlet. Inside the for loop its printing all the id's and even in html its there. But in EditServlet its returning null.

EditServlet.java

@WebServlet("/EditServlet")
public class EditServlet extends HttpServlet {
private static final long serialVersionUID = 1L;


protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    response.setContentType("text/html");
    PrintWriter out=response.getWriter();
    String id2=request.getParameter("id");
    System.out.println("id is"+request.getParameter("id"));//Null is getting printed
    int id=Integer.parseInt(id2);
    System.out.println("Inside doGet id is"+id);//NumberFormatException

}}

Upvotes: 0

Views: 563

Answers (1)

Mark Olsson
Mark Olsson

Reputation: 320

You're missing an equals in the link. Your code is generating the URL EditServlet?id1, so the parameter sent will be id1 with no value, when you want EditServlet?id=1 so you'll get a parameter id with the value 1.

<a href='EditServlet?id"+e.getId()+"''>edit</a>

should be

<a href='EditServlet?id="+e.getId()+"'>edit</a> (note extra ' also removed)

The same applies to the delete link.

The easiest way to find parameter problems like this is to use the browser's developer tools to look at what the browser actually sends and receives. Or if the server was launched from an IDE, there should be a way to view the details of each request (the HTTP Server Monitor in NetBeans for example).

Upvotes: 1

Related Questions