简体   繁体   中英

getting data from servlet class

I have a class that gets data from the servlet like so :

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    response.setContentType("text/html");{
        ServletOutputStream  out = response.getOutputStream();
        try {
            out.println("<html><head><title>" +  "</title></head>");
            out.println("<body><h1>" +  "</h1>");
            name = request.getParameter("username" );
            message = "hi there";
            //String  comment = request.getParameter( "comment" );
            out.println("Name:" + name + "<BR>");
            //out.println("Comment: " + comment + "<BR>");
        }
        catch(Throwable  t ) {
            out.println("<P><pre>");
            t.printStackTrace( new PrintStream(out) );
            out.println ("</pre><P>");
        }
        out.println ("</body></html>");
    }
}

And that works fine, but I want to use the name parameter in a different class on the server too. Can I use something like :

getServletContext().setAttribute("package", "name");

And call the attribute from the class like that? Or is there another way I can save the value in the servlet context or in the servlet so I can call it again? all i really want to do is after the servlet is loaded, to keep the last value it's processed somewhere and use that in another class when needed.

All Help is appreciated!! :)

getServletContext() is one of the ways to share data between servelts. So, yes your approach should be fine.

If the data is specific to user, instead of getServletContext() , it is better to use HttpSession .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM