Accessing user details after logging in with Java EE Form authentication

ぐ巨炮叔叔 提交于 2019-12-05 18:48:55
BalusC

Create a filter which checks if the user is logged in while no associated User object from the database is present in the session. Then, just load that data and put in session.

Basically,

@WebFilter("/*")
public class UserFilter implements Filter {

    @EJB
    private UserService service;

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        String remoteUser = request.getRemoteUser();

        if (remoteUser != null) {
            HttpSession session = request.getSession();

            if (session.getAttribute("user") == null) {
                User user = service.find(remoteUser);
                session.setAttribute("user", user);
            }
        }

        chain.doFilter(req, res);
    }

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