简体   繁体   中英

java servlet redirect with attribute

I have servlet which depending on incoming URL performs different code:

if (URIstring.startsWith("/categories")) {
   //process request and send it to categories.jsp
} else if (URIstring.startsWith("/projects")) {
    //process request and send it to projects.jsp
}

Application starts from /context/categories url and goes to first if . On categories page, using form, I allow user to choose category. After user chose category, response to servlet comes like

/projects?category=1 

Next I want to catch exceptions when user instead of numbers uses string or letters (which will generate NumberFormatException in else if (URIstring.startsWith("/projects")) part. I want to process this exception in following way: if servlet receives smth like

/projects?category=string 

catch exception, redirect it back to categories page but with attribute set, like

error="You entered wrong input! Try again." 

In categories.jsp file put

<c:out value="${error}"/>

In this case this line would be shown only in case of exception thrown. But how can I redirect between two jsps(of parts of if constructor) with attributes set. I have found only

else if (URIstring.startsWith("/projects")) {
    try {
        //process request and send it to projects.jsp
    } catch (NumberFormatException e) {
        resp.sendRedirect("/context/categories"); 
    }
}

which redirects to needed if part and JSP but without my error attribute((( I tried:

req.setAttribute("error", "You entered wrong input! Try again.");

But it works for projects.jsp, not on redirected jsp((((

resp.sendRedirect will terminate the current request and send a 302 redirect back to the client. Any attribute you have set on the request on the server side is then forgotten.

What you need to do is a server-side redirect, which can be accomplished with the RequestDispatcher.forward method. java doc

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