为了将隐藏参数从 JSF 2.0 Managed BEan 操作处理程序传递到 Servlet,我将参数值传递到 Session 属性中:
public void callServlet(long id) {
try {
ExternalContext ctx = FacesContext.getCurrentInstance().getExternalContext();
HttpSession sess = (HttpSession) ctx.getSession(false);
sess.setAttribute("id", id);
ctx.redirect("MyServlet");
} catch (IOException ex) {
Logger.getLogger(ResultBean.class.getName()).log(Level.SEVERE, null, ex);
}
}
是否有更好的方法来做到这一点,例如是否可以使用 flash 映射将这个隐藏参数发送到 Servlet?
最佳答案
Flash 范围在幕后使用 cookie 和 session 范围的组合。因此,要达到相同的效果,您需要通过 JSF 设置 cookie,并在 Servlet 中获取 cookie。但这并不比你已经拥有的好多少。如果您想防止最终用户知道/猜测该值并希望确保同一 session 中多个请求的完整性,另一种方法是通过 session 中的唯一标识符存储属性并将其作为请求参数传递。
public void callServlet(Long id) throws IOException {
ExternalContext ec = FacesContext.getCurrentInstance().getExternalContext();
String uuid = UUID.randomUUID().toString();
ec.getSessionMap().put(uuid, id);
ec.redirect("MyServlet?id=" + uuid);
}
(请注意,我修复了您的代码以删除潜在的 NullPointerException
并消除了在 JSF 中包含 javax.servlet
特定代码的需要,这是一个标志不良实践)
在 servlet 中:
String uuid = request.getParameter("id");
Long id = (Long) request.getSession().getAttribute(uuid);
request.getSession().removeAttribute(uuid);
// ...
关于java - 我可以使用 JSF flash 将参数传递给 Servlet 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8183313/