Java filter for specific pages

Asked

Viewed 260 times

1

How do I control the access of pages with Java? I have a filter already implemented, which controls whether the user is logged in or not.

However, I have a page that I need to check the user’s permission... The page will only be accessed if the user is an administrator.

When the user is accessing the processing page and is not an ADMINISTRATOR user, the page should not be accessed.

I want to know how to do this in the filter part in Java. My code is this:

    public void doFilter(ServletRequest request, ServletResponse response, 
    FilterChain chain) throws IOException, ServletException {

    String context = request.getServletContext().getContextPath();

    try{
        HttpSession session = ((HttpServletRequest)request).getSession();
        User user = null;
        if(session != null){
            user = (User) session.getAttribute("user");

        }
        if(user == null){
            HttpServletResponse resp =((HttpServletResponse)response);

            resp.sendRedirect(context + "/");
        } else {
            chain.doFilter(request, response);
            JPAUtil.closeEntityManager();
        }
    }catch(Exception e){
        e.printStackTrace();
    }
}

1 answer

0


Very simple friend, in the Database, you will have to save the type of a user, administrator, or client. When you put the user in the session, make sure that their type is set, in the filter you would do something like:

First you do the Filter mapping, in my case, all the pages you have "/admin/" will be filtered so that only administrators have access.

The mapping is done like this

@WebFilter(urlPatterns="/admin/*")
public class FilterAdm implements Filter

This is the doFilter method

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    HttpServletRequest req = (HttpServletRequest) request;
    HttpServletResponse resp = (HttpServletResponse) response;
    User user = (User) req.getSession().getAttribute("userSession");
    if (user == null || !user.getType().equals("adm")) {
        resp.sendError(400);
    } else {
        chain.doFilter(request, response);
    }     
}

I hope I’ve helped !

  • Only this way, it will give Resupply.sendError(400) to all pages... But this is only to happen if it is the treatment page.

  • So you should do the Filter mapping, sorry, think you would understand, I’ll edit the answer

Browser other questions tagged

You are not signed in. Login or sign up in order to post.