Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing the value from a servlet to another

Tags:

java

servlets

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;
like image 697
Rusty Avatar asked Jan 24 '26 04:01

Rusty


1 Answers

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

like image 197
Victor Sorokin Avatar answered Jan 26 '26 22:01

Victor Sorokin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!