4

I've created two sets of servlets: Views and Controllers/Handlers

  • Views: Perform simple reads and forward data to JSPs
  • Controllers: Perform database updates or inserts and send a notification to either a JSP or a View type servlet

Notification here is a status message for the user. Example: "You have successfully updated blah..."

If I use requestDispatcher.forward() in controllers and the user refreshes (after the Controller has passed control to view/jsp) the page by confirming resend there is a chance of duplicate actions being performed

If I use response.sendRedirect() I cannot seem to send any notifications without setting these in the session

Is there a good design practice that helps here? Any good link to MVC for java w/o frameworks that handles this particular scenario would be appreciated.

I am not using Spring or Struts - just plain old HTTPServlets

Example - Controller:

public XServlet extends HttpServlet{
     public void processRequest(request, response) throws ...{ 
         //Do some stuff here
         if(success){
             setUserMessage("Hooray ur profile pic is uploaded!");
         } else {
             setUserMessage("Oh no! We couldn't upload that file its too biG!");
         }

         //Send the notification
         request.setAttribute("status", getUserMessage());
         request.getRequestDispatcher("editProfile.jsp").forward(request, response);
    }
}

Doing this means that if the user tries to refresh the page the control will again pass to this controller and some actions may be repeated unnecessarily.

However if I use sendRedirect() then I cannot show the status message without either resorting to a session attribute or appending it to the url.

5
  • I cannot seem to send any notifications What does that mean? What are you trying to achieve? Give a concrete example use-case.
    – JB Nizet
    Sep 5, 2015 at 7:45
  • Hi, I've elucidated the Q with a few more details. Notifications here mean status messages for the end user.
    – MandarK
    Sep 5, 2015 at 7:56
  • 1
    You answered your own question. Sending a redirect consists in telling the browser to send a new request. So everything stored in the first request's attributes is lost when handling the new request. So you indeed need session attributes or parameters in the URL.
    – JB Nizet
    Sep 5, 2015 at 7:59
  • 1
    I get that but now the status is stored in the session meaning once its displayed i have to clear it. Is there a cleaner mechanism to achieve this? Thanks
    – MandarK
    Sep 5, 2015 at 8:00
  • MVC frameworks have things called "flash attributes", which basically do what you're describing: when accessing them, they're removed from the session. Since you decided to not use any higher-level framework, you also decided to reinvent and redo by yourself all the features implemented by these frameworks.
    – JB Nizet
    Sep 5, 2015 at 8:02

2 Answers 2

5

You're looking for the "flash scope".

The flash scope is backed by a short living cookie which is associated with a data entry in the session scope. Before the redirect, a cookie will be set on the HTTP response with a value which is uniquely associated with the data entry in the session scope. After the redirect, the presence of the flash scope cookie will be checked and the data entry associated with the cookie will be removed from the session scope and be put in the request scope of the redirected request. Finally the cookie will be removed from the HTTP response. This way the redirected request has access to request scoped data which was been prepared in the initial request.

In plain Servlet terms that's thus like below:

  1. Create the flash scope and add entries:

    String message = "Some message";
    
    // ...
    
    Map<String, Object> flashScope = new HashMap<>();
    flashScope.put("message", message);
    
  2. Before redirect, store it in the session keyed by an unique ID and set it as cookie:

    String flashScopeId = UUID.randomUUID().toString();
    request.getSession().setAttribute(flashScopeId, flashScope);
    Cookie cookie = new Cookie("flash", flashScopeId);
    cookie.setPath(request.getContextPath());
    response.addCookie(cookie);
    
    // ...
    
    response.sendRedirect(request.getContextPath() + "/someservlet");
    
  3. In next request, find the flash cookie, map it back into request scope and delete cookie:

    if (request.getCookies() != null) {
        for (Cookie cookie : request.getCookies()) {
            if ("flash".equals(cookie.getName())) {
                Map<String, Object> flashScope = (Map<String, Object>) request.getSession().getAttribute(cookie.getValue());
    
                if (flashScope != null) {
                    request.getSession().removeAttribute(cookie.getValue());
    
                    for (Entry<String, Object> entry : flashScope.entrySet()) {
                        request.setAttribute(entry.getKey(), entry.getValue());
                    }
                }
    
                cookie.setValue(null);
                cookie.setMaxAge(0);
                cookie.setPath(request.getContextPath());
                response.addCookie(cookie);
            }
        }
    }
    

This could be further abstracted using context-specific helper method like setFlashAttribute() and a servlet filter with a response wrapper.

3
  • BalusC thank you again....the amount of information you provide has helped me a lot.....
    – Grim
    Dec 11, 2016 at 19:06
  • Is this generally what is used to display temporary messages of this kind and avoid having them be indexable? Are there any other options that you could point me to? Do some people do a forward instead of a redirect in order to solve this issue?
    – theyuv
    Oct 28, 2021 at 14:26
  • See the question. The asker themselves has already very clearly elaborated this.
    – BalusC
    Oct 28, 2021 at 15:30
1

use bean to set request scope message

@SessionScoped
public class Message implements Serializable {

private static final long serialVersionUID = 1L;

public Message() {
}

@PostConstruct
private void prepareMessage() {
    messages = new HashMap<>(10);
}

private HashMap<String, String> messages;

public String add(String value) {
    if (messages.size() == 10) {
        messages.clear();
    }
    String key = generateRandomKey();
    messages.put(key, value);
    return key;
}

private String generateRandomKey() {
    SecureRandom random = new SecureRandom();
    return String.valueOf((random.nextInt(999999) + 1));
}

public String get(String key) {
    String msg= messages.get(key);
    messages.remove(key);
    return msg;
  }
    }

rediect

protected void doPost(HttpServletRequest request, HttpServletResponse        response)
            throws ServletException, IOException {
 //operation
String mKey = msg.add("some msg.");
            response.sendRedirect("mastercontroller?viewID=" + entity + "&mKey=" + mKey);}

and forward

 protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String viewId = request.getParameter("viewID");
    System.out.println(viewId);
    String mKey = request.getParameter("mKey");

    if (mKey == null || mKey.isEmpty()) {
        request.getRequestDispatcher(viewId + ".jsp").forward(request, response);
    }else{
        String responseMsg=msg.get(mKey);
        if(responseMsg==null){
            request.getRequestDispatcher(viewId + ".jsp").forward(request, response);
            return;
        } 
        request.setAttribute("postback", "true");
        request.setAttribute("responseMsg",responseMsg);
        request.getRequestDispatcher(viewId + ".jsp").forward(request, response);
    }

}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.