Reputation: 230
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!! :)
Upvotes: 0
Views: 542
Reputation: 66657
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
.
Upvotes: 1