Rusty
Rusty

Reputation: 384

Passing the value from a servlet to another

I am trying to pass the value from one servlet to another, and I think I have tried just about everything but it always ends up null. I am trying to get the "id" from beside delete task. I have tried storing it in a session, I have tried playing with request.getParameter. Any ideas on what I should do?

try{
        int id = DataAccess.getUserID(name);
        list = DataAccess.displayTasks(id);
    }
    catch(Exception e){e.printStackTrace();}

out.println(OurUtils.getHeader("List of Tasks"));
    out.println("<center><h2>List of Your Tasks</h2>");
    out.println("<table>");
    for (Tasks T : list){
        out.println("<tr>");
        out.println("<td><a href = \"DeleteTask?id="+T.getId()+"\">Delete</a></td>");
        out.println("<td><a href = \"ModifyTask?id="+T.getId()+"\">Modify</a></td>");
        out.println("<td>"+T.getTask()+"</td></tr>");
    }
    out.println("</table>");
    out.println("");
    out.println("<a href=\"AddTask\">Add a new task</a>");
    out.println("</center>");
    out.println(OurUtils.getFooter());

here is my display task method

public static ArrayList<Tasks> displayTasks(int id) throws ClassNotFoundException, 
IllegalAccessException, InstantiationException,SQLException{
Class.forName(driver).newInstance();
con = DriverManager.getConnection(url,sqluser,sqlpass);
st = con.createStatement();
String sql = "SELECT task from Assignment2Tasks where userID = "+id+"";
ResultSet rs = st.executeQuery(sql);

ArrayList<Tasks> list = new ArrayList<Tasks>();

while(rs.next()){
    Tasks T = new Tasks(rs.getString(1));
    list.add(T);
}

con.close();
return list;

Upvotes: 3

Views: 2274

Answers (5)

Rusty
Rusty

Reputation: 384

I have discovered the solution to my problem. In my DisplayTasks method, I was just pulling the string for the task and putting it in the t object and I was not pulling the ID from the table. I couldn't pass the ID to the other servlet because it was and empty variable..

Upvotes: 0

Victor Sorokin
Victor Sorokin

Reputation: 11996

Okay, maybe you already know it, but this is how your service objects (such as DAO objects) and domain objects (lists of tasks) can be shared across your servlets:

  1. In your web.xml you define listener object, implementing ServletContextListener, so listener will be called once application is deployed into Servlet container (jetty, tomcat):

     <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
             version="3.1">
    
        <servlet>
            <servlet-name>Main</servlet-name>
            <servlet-class>vic.web.MainServlet</servlet-class>
            <load-on-startup>1</load-on-startup>
        </servlet>
    
        <listener>
            <listener-class>vic.web.AppInitializationListener</listener-class>
        </listener>
    
        <servlet-mapping>
            <servlet-name>Main</servlet-name>
            <url-pattern>/main</url-pattern>
        </servlet-mapping>
    
    </web-app>
    
  2. In code of that listener you initialize your data layer and put reference to it inside ServletContext, which is guaranteed to be shared across all servlets of your webapp, which are run in the same JVM:

    public class AppInitializationListener implements ServletContextListener {
    
        private static final Logger logger = LoggerFactory.getLogger(MainServlet.class);
    
        static final String INITIAL_TASKS_KEY = "INITIAL_TASKS_KEY";
        @Override
        public void contextInitialized(ServletContextEvent sce) {
            logger.info("Application initialization commences...");
            sce.getServletContext().setAttribute(INITIAL_TASKS_KEY,
                    new TasksList(Arrays.asList("From me to you", "We can work it out", "Long and winding road")
                    ));
        }
    
        @Override
        public void contextDestroyed(ServletContextEvent sce) {
        }
    }
    
  3. In code of your servlet(s), you override init(ServletConfig config) method which is called by container once servlet is initialized. There, you reach out for data initialized in listener and here you go!

    public class MainServlet extends HttpServlet {
    
        private static final Logger logger = LoggerFactory.getLogger(MainServlet.class);
    
        private TasksList initialTasks;
    
        @Override
        public void init(ServletConfig config) throws ServletException {
            super.init(config);
    
            logger.info("Here");
    
            ServletContext ctx = getServletContext();
            //noinspection unchecked
            initialTasks = (TasksList) ctx.getAttribute(AppInitializationListener.INITIAL_TASKS_KEY);
    
            logger.info("Got: " + initialTasks);
        }
    
        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            PrintWriter writer = resp.getWriter();
            StringBuilder sb = new StringBuilder("<html><body>Hello there. Here are your tasks:<br><ol><br>\n");
            for (String task : initialTasks.getTasks()) {
                sb.append("<li>").append(task).append("</li><br>\n");
            }
            sb.append("</ol>\n</body></html>");
            writer.write(sb.toString());
            writer.flush();
            writer.close();
        }
    
    }
    
  4. Here data layer is just POJO containing static list of tasks. Since you want to get data from DB (naturally), you should put your JDBC initialization code in listener as shown above and make listener put obtained DriverManager into context.

  5. Okay, but in reality you will want to change these things: a) use some MVC framework instead of creating HTML by hand; b) Use DataSource and pool of JDBC connections instead of DriverManager

Upvotes: 2

user562
user562

Reputation: 88

I dont know why you're using all those out.println instead of atleast jsp. I've done this in jsp.

My list in servlet

List<User> list = userService.viewUser();    //userService is used to access the data from db by calling the daoservice
request.setAttribute("list",list);
rs=request.getRequestDispatcher("manageuser.jsp");
rs.include(request,response);

This is my code in jsp, do note that all these data are inside table tag

<%List list=(List)request.getAttribute("list");%>   //Getting the list attributes from the appropriate servlet
<c:forEach items="${list}" var="user">      //for each loop
<tr>
    <td><c:out value="${user.userId}" /></td>
    <td><c:out value="${user.userName}" /></td>
    <td><c:out value="${user.emailId}" /></td>
    <td><a href="menuaction?redirectValue=edituser&Id=${user.userId}">Edit</a>
    <a href="menuaction?redirectValue=deleteuser&Id=${user.userId}">Delete</a></td>
</tr>
</c:forEach>

Then in the servlet where I was doing the deleting operation and editind operation, (for you it's only deletion)

int id = Integer.parseInt(request.getParameter("Id")); //Do the appropriate actions from this id variable

Upvotes: 1

Gurkan İlleez
Gurkan İlleez

Reputation: 1573

<a href = \DeleteTask?id = 15>Delete</a>

when user clicks Delete, you can get id by request.getParameter("id") So you can pass id to other servlet with request.

Also you can store it in session and get it.

request.getSession(true).setAttribute("name",'AAAA');

request.getSession().getAttribute("name");

Upvotes: 0

Ajay Takur
Ajay Takur

Reputation: 6236

Inter-servlet communication: RequestDispatcher object can forward a client's request to a resource(Servelt/Jsp).Here you want Servlet_A to invoke Servlet_B.Use

RequestDispatcher dispatcher = getRequestDispatcher("Servlet_B");
   dispatcher.forward( request, response );

Upvotes: 0

Related Questions