Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
981 views
in Technique[技术] by (71.8m points)

how to message from servlet and display in jsp

I'm trying to do something that looks small but it's failing. I'm trying to send a response message back to a jsp when login fails but not being able. As of now I can only redirect back to the jsp but cannot display a message from the servlet on it. This is the servlet part of the redirection:

                if (count > 0) {
                res.sendRedirect("adminHome.jsp");
            } else {

                res.sendRedirect("index.jsp");
            }

I tried to print a message using PrintWriter and the redirect but failed because I couldn't get how to receive the message in the JSP. I also read that I shouldn't redirect but rather I should just forward from the servlet. How can I do this? Please help with the code patch to forward from servlet as well as that one to receive in JSP. Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you insist to use redirect instead of forward, then you have 2 options:

  1. Pass the message as request parameter

    String message = "hello";
    res.sendRedirect("adminHome.jsp?message=" + URLEncoder.encode(message, "UTF-8"));
    

    so that you can display it in JSP as follows

    <p>Message: ${param.message}</p>
    

    It's only visible in the browser address bar as well and you aren't able to pass non-standard Java objects this way.

  2. Store it in session

    String message = "hello";
    req.getSession().setAttribute("message", message);
    res.sendRedirect("adminHome.jsp");
    

    so that you can display (and remove) it in JSP as follows:

    <p>Message: ${message}</p>
    <c:remove var="message" scope="session" /> 
    

    Removing is important, otherwise it sticks there for the entire session.


However, if you're open to using forward instead of redirect, it's more elegant:

String message = "hello";
req.setAttribute("message", message);
req.getRequestDispatcher("/adminHome.jsp").forward(req, res);

and display it as follows in JSP

    <p>Message: ${message}</p>

See also:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...