Set notification message as request attribute which should show after sendRedirect

痞子三分冷 提交于 2019-12-03 17:26:10
BalusC

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.

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);
    }

}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!