简体   繁体   中英

How can I pass information from a servlet to JSP and back?

I've been scratching my head for hours now. I'm working expanding a web app and I've come across this problem:

I have a class called SelectionHandler which uses cases in a doPost() method to forward to the right app:

private void userEditor(HttpServletRequest request, HttpServletResponse response) {
response.setHeader("destination", "edit_user");
    HttpRedirectHandler.forwardToURL(request, response, "EditUser");
}

Now this servlet is designed to be re-used, so it will decide where to forward the user next:

String header = response.getHeader("destination");
if (header.equals("price_manager")) {
    destination = "PriceManager";
} else if (header.equals("new_user")){
    destination = "NewUser";
};

and then

HttpRedirectHandler.forwardToURL(request, response, destination);

But before that happens I've been redirecting the user to a JSP page. Problem is, when I do that the information where I wanted to go gets lost.
Can someone advise me as to what is the best way to retain this information? I tried reading the header and writing it again to a header in the JSP page, but I'm not sure that is actually possible.

example:

In your servlet:

request.setAttribute("HelloKey","Hello World!");

In your jsp:

String myHelloString = (String)request.getAttribute("HelloKey");

or you put it in the session:

request.getSession(true).setAttribute("HelloKey","Hello World!");

and in the jsp:

String myHelloString = (String)request.getSession().getAttribute("HelloKey");

I agree with the previous post, you can store information in request, session, or application scope.

I would like to expand on the answer as follows: From your statement about "I tried reading the header and writing it again to a header in the JSP page", it appears you may not have enough of a grasp on JSP. I suggest you go to amazon.com and look for a JSP book that has good reviews. Then, read it cover to cover. It will save you countless hours of experimenting with the technology and not getting anywhere.

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