[Foolish Old Man Series] April 2023 Java face-to-face question brushing system-004. Login and permission verification

Article Directory

1. Login and permission verification

1. Login

1.1 Rapid development of login function

1. Find the project webapp/login.jsp login page, and modify the action path submitted by the form form

<form action="${pageContext.request.contextPath}/login?operation=login" method="post">
</form>
copy

2. Add a login method in the background UserServlet

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    String operation = request.getParameter("operation");
    if("list".equals(operation)){
        this.list(request,response);
    }
    //middle omitted
    else if("login".equals(operation)){
        this.login(request,response);
    }
}
private void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    String email = request.getParameter("email");
    String pwd = request.getParameter("password");
    User user = userService.login(email,pwd);
    if(user != null) {
        request.getSession().setAttribute("loginUser", user);
        //jump page
        request.getRequestDispatcher("/WEB-INF/pages/home/main.jsp").forward(request, response);
    }else{
        response.sendRedirect(request.getContextPath()+"/login.jsp");
    }
}
copy

3. Add a login method in the UserService layer interface

/**
     * Login by email and password
     * @param email
     * @param pwd
     * @return
     */
    User login(String email, String pwd);
copy

4. Implement the login method in the corresponding implementation class

@Override
public User login(String email, String pwd) {
    SqlSession sqlSession = null;
    try{
        //1. Get SqlSession
        sqlSession = MapperFactory.getSqlSession();
        //2. Get Dao
        UserDao userDao = MapperFactory.getMapper(sqlSession,UserDao.class);
        //3. Call the Dao layer operation
        pwd = MD5Util.md5(pwd);
        return userDao.findByEmailAndPwd(email,pwd);
    }catch (Exception e){
        throw new RuntimeException(e);
        //record log
    }finally {
        try {
            TransactionUtil.close(sqlSession);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
copy

5. Add a query method to the UserDao interface

User findByEmailAndPwd(@Param("email")String email, @Param("password")String pwd);
copy

6. Add query in UserDao.xml

<select id="findByEmailAndPwd" parameterType="map" resultMap="BaseResultMap">
    select
    <include refid="Base_Column_List"/>
    from ss_user
    where email = #{email,jdbcType=VARCHAR} and password = #{password,jdbcType=VARCHAR}
</select>
copy

7. Modify the path of the content area of ​​/WEB-INF/pages/home/main.jsp

<!-- content area -->
<div class="content-wrapper">
    <iframe id="iframe" name="iframe"
            style="overflow:visible;"
            scrolling="auto"
            frameborder="no" height="100%" width="100%"
            src="${ctx}/system/user?operation=home"></iframe>
</div>
copy

8. Add methods in the background UserServlet

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    String operation = request.getParameter("operation");
    if("list".equals(operation)){
        this.list(request,response);
    }
    //middle omitted
    else if("home".equals(operation)){
        this.home(request,response);
    }
}
private void home(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    request.getRequestDispatcher("/WEB-INF/pages/home/home.jsp").forward(request, response);
}
copy

1.2 User menu control data preparation

Let's first complete the logout operation after login, which is a set of

1. Find logout in /WEB-INF/pages/home/header.jsp, add request connection

<div class="pull-right">
    <a href="${ctx}/system/user?operation=logout" class="btn btn-default btn-flat">log out</a>
</div>
copy

2. Add the corresponding method logout in the background UserServlet

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    String operation = request.getParameter("operation");
    if("list".equals(operation)){
        this.list(request,response);
    }
    //middle omission
    else if("login".equals(operation)){
        this.login(request,response);
    }else if("logout".equals(operation)){
        this.logout(request,response);
    }else if("home".equals(operation)){
        this.home(request,response);
    }
}
private void logout(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    request.getSession().removeAttribute("loginUser");
    response.sendRedirect(request.getContextPath()+"/login.jsp");
}
copy

3. When the user logs in, it is necessary to query all the modules corresponding to the role corresponding to the user, so it is necessary to modify the user login method in the background UserServlet and add data query

private void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    String email = request.getParameter("email");
    String pwd = request.getParameter("password");
    User user = userService.login(email,pwd);
    if(user != null) {
        request.getSession().setAttribute("loginUser", user);
        //If the login is successful, load all modules corresponding to the role corresponding to the user
        List<Module> moduleList = userService.findModuleById(user.getId());
        request.setAttribute("moduleList",moduleList);
        //jump page
        request.getRequestDispatcher("/WEB-INF/pages/home/main.jsp").forward(request, response);
    }else{
        response.sendRedirect(request.getContextPath()+"/login.jsp");
    }
}
copy

4. Add the method findModuleById in the UserService interface

/**
     * Query all operable menu objects according to user id
     * @param id user id
     * @return
     */
    List<Module> findModuleById(String id);
copy

5. Implement the method in the implementation class

@Override
public List<Module> findModuleById(String id) {
    SqlSession sqlSession = null;
    try{
        //1. Get SqlSession
        sqlSession = MapperFactory.getSqlSession();
        //2. Get Dao
        ModuleDao moduleDao = MapperFactory.getMapper(sqlSession,ModuleDao.class);
        //3. Call the Dao layer operation
        return moduleDao.findModuleByUserId(id);
    }catch (Exception e){
        throw new RuntimeException(e);
        //record log
    }finally {
        try {
            TransactionUtil.close(sqlSession);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
copy

6. Add the query method findModuleByUserId to the ModuleDao interface

List<Module> findModuleByUserId(String id);
copy

7. Add the corresponding query in ModuleDao.xml

<select id="findModuleByUserId" parameterType="java.lang.String" resultMap="BaseResultMap">
        /*userid->User role relationship table->roleid->role module relationship table->moduleid->module information*/
        SELECT DISTINCT
          m.module_id, m.parent_id, m.name, m.ctype, m.state, m.curl, m.remark
        FROM
            ss_module AS m,
            ss_role_module AS rm,
            ss_role_user AS ru
        WHERE
            m.module_id = rm.module_id
        AND	rm.role_id = ru.role_id
        AND	ru.user_id = #{id,jdbcType=VARCHAR}
    </select>
copy

So far: the module data corresponding to the user's role has been queried, and the follow-up is to control the display on the page

1.3 Login user menu control

1. Find the /WEB-INF/pages/home/aside.jsp page and add the display of the user menu

<!-- sidebar menu: : style can be found in sidebar.less -->
<ul class="sidebar-menu">
    <li class="header">menu</li>

    <c:forEach items="${moduleList}" var="item">
        <c:if test="${item.ctype==0}">
            <li class="treeview">
                <a href="#">
                    <i class="fa fa-cube"></i> <span>${item.name}</span>
                    <span class="pull-right-container"><i class="fa fa-angle-left pull-right"></i></span>
                </a>
                <ul class="treeview-menu">
                    <c:forEach items="${moduleList}" var="item2">
                        <c:if test="${item2.ctype==1 && item2.parentId == item.id}">
                            <li id="${item2.id}">
                                <a οnclick="setSidebarActive(this)" href="${ctx}/${item2.curl}" target="iframe">
                                    <i class="fa fa-circle-o"></i>${item2.name}
                                </a>
                            </li>
                        </c:if>
                    </c:forEach>
                </ul>
            </li>
        </c:if>
    </c:forEach>
copy

2. Permission verification

2.1 Get request url

1. Create a filter: com.iheima.web.filters.AuthorFilter

@WebFilter(value = "/*")
public class AuthorFilter implements Filter {

    private FilterConfig filterConfig;

    /**
     * Initialization method to get the configuration object of the filter
     * @param filterConfig
     * @throws ServletException
     */
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        this.filterConfig = filterConfig;
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
        //1. Define the request and response objects related to the protocol
        HttpServletRequest request ;
        HttpServletResponse response;
        try{
            //2. Convert the parameters into protocol-related objects
            request = (HttpServletRequest)req;
            response = (HttpServletResponse)resp;

            //1. Get this operation
            String url = request.getRequestURI();
            String queryString = request.getQueryString();

            //1. The currently obtained url: /system/dept
            url = url.substring(1);
            //2. Currently obtained query parameters: operation=list operation=toEdit&id=100
            int index = queryString.indexOf('&');
            if(index != -1){
                queryString = queryString.substring(0,index);
            }
            url = url + "?" + queryString;

            //2. Obtain the operations allowed by the current login person

            //3. Compare whether this operation is within the operation range allowed by the current login person
            //3.1 If allowed, release
            //3.2 Jumping to illegal access pages is not allowed

            //6. Release
            chain.doFilter(request,response);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Override
    public void destroy() {
        //can do some cleanup
    }
}
copy

2.2 Obtain the executable operations of the logged-in user

1. After successful login, you need to store the corresponding module information of the user in the session, find the login method login in UserServlet,

private void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    String email = request.getParameter("email");
    String pwd = request.getParameter("password");
    User user = userService.login(email,pwd);
    if(user != null) {
        request.getSession().setAttribute("loginUser", user);
        //If the login is successful, load all modules corresponding to the role corresponding to the user
        List<Module> moduleList = userService.findModuleById(user.getId());
        request.setAttribute("moduleList",moduleList);

        //All url s of the operable modules corresponding to the currently logged-in user are concatenated into a large string
        StringBuffer sbf = new StringBuffer();
        for(Module m: moduleList){
            sbf.append(m.getCurl());
            sbf.append(',');
        }
        request.getSession().setAttribute("authorStr",sbf.toString());

        //jump page
        request.getRequestDispatcher("/WEB-INF/pages/home/main.jsp").forward(request, response);
    }else{
        response.sendRedirect(request.getContextPath()+"/login.jsp");
    }
}
copy

2. Modify AuthorFilter

@Override
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
    //1. Define the request and response objects related to the protocol
    HttpServletRequest request ;
    HttpServletResponse response;
    HttpSession session;
    try{
        //2. Convert the parameters into protocol-related objects
        request = (HttpServletRequest)req;
        response = (HttpServletResponse)resp;
        session = request.getSession();
        //1. Get this operation
        String url = request.getRequestURI();
        //.css   .js    .png   .jpg   .index
        if(url.endsWith(".css")
           || url.endsWith(".js")
           || url.endsWith(".png")
           || url.endsWith(".jpg")
           || url.endsWith("index.jsp")
           || url.endsWith("login.jsp")){
            chain.doFilter(request,response);
            return;
        }
        String queryString = request.getQueryString();
        if(queryString.endsWith("operation=login")){
            chain.doFilter(request,response);
            return;
        }


        //1. The currently obtained url: /system/dept
        url = url.substring(1);
        //2. Currently obtained query parameters: operation=list operation=toEdit&id=100
        int index = queryString.indexOf('&');
        if(index != -1){
            queryString = queryString.substring(0,index);
        }
        url = url + "?" + queryString;

        //2. Obtain the operations allowed by the current login person
        String authorStr = session.getAttribute("authorStr").toString();
        //3. Compare whether this operation is within the operation range allowed by the current login person
        //3.1 If allowed, release
        //3.2 Jumping to illegal access pages is not allowed

        //6. Release
        chain.doFilter(request,response);
    }catch (Exception e){
        e.printStackTrace();
    }
}
copy

2.3 Permission verification

1. Change AuthorFilter,

@Override
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
    HttpServletRequest request ;
    HttpServletResponse response;
    HttpSession session;
    try{
        request = (HttpServletRequest)req;
        response = (HttpServletResponse)resp;
        session = request.getSession();

        //1. Get this operation
        String url = request.getRequestURI();
        //.css   .js    .png   .jpg   .index
        if(url.endsWith(".css")
           || url.endsWith(".js")
           || url.endsWith(".png")
           || url.endsWith(".jpg")
           || url.endsWith("index.jsp")
           || url.endsWith("unauthorized.jsp")
           || url.endsWith("login.jsp")){
            chain.doFilter(request,response);
            return;
        }
        String queryString = request.getQueryString();
        if(queryString.endsWith("operation=login")
           ||queryString.endsWith("operation=home")
           ||queryString.endsWith("operation=logout")){
            chain.doFilter(request,response);
            return;
        }
        //1. The currently obtained url: /system/dept
        url = url.substring(1);
        //2. Currently obtained query parameters: operation=list operation=toEdit&id=100
        int index = queryString.indexOf('&');
        if(index != -1){
            queryString = queryString.substring(0,index);
        }
        url = url + "?" + queryString;

        //2. Obtain the operations allowed by the current login person
        String authorStr = session.getAttribute("authorStr").toString();

        //3. Compare whether this operation is within the operation range allowed by the current login person
        if(authorStr.contains(url)){
            //3.1 If allowed, release
            chain.doFilter(request,response);
            return;
        }else{
            //3.2 Jumping to illegal access pages is not allowed
            response.sendRedirect(request.getContextPath()+"/unauthorized.jsp");
        }
    }catch (Exception e){
        e.printStackTrace();
    }
}
copy

2. For the elements on the page, if there is no operation permission, we can directly make the user invisible, how to operate? Make a judgment on the page, let's give an example, other operations are the same

Find /WEB-INF/pages/system/user/list.jsp,

<div class="btn-group">
    <c:if test="${sessionScope.authorStr.contains('system/user?operation=toAdd')}">
        <button type="button" class="btn btn-default" title="new build" οnclick='location.href="${ctx}/system/user?operation=toAdd"'><i class="fa fa-file-o"></i> new build</button>
    </c:if>
    <button type="button" class="btn btn-default" title="delete" οnclick='deleteById()'><i class="fa fa-trash-o"></i> delete</button>
    <button type="button" class="btn btn-default" title="to refresh" οnclick="window.location.reload();"><i class="fa fa-refresh"></i> to refresh</button>
    <c:if test="${sessionScope.authorStr.contains('system/user?operation=userRoleList')}">
        <button type="button" class="btn btn-default" title="Role" οnclick="roleList()"><i class="fa fa-user-circle-o"></i> Role</button>
    </c:if>
</div>
copy

Tags: interface

Posted by kankaro on Thu, 06 Apr 2023 07:31:38 +0530