在看了转载的那篇【extends ActionServlet】文章之后,很多疑问都还没解决,于是动手写了一个Web project。

(一)
  下列是所有文件:
  CheckRequestProcessor  RequestProcessor类型
  UserLoginAction        action
  userLogin.jsp
  successfullyLogin.jsp
  failureLogin.jsp
  manage.jsp
  accessDenied.jsp

(二)文件的内容:

2.1:
struts-config.xml:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.1//EN" "http://jakarta.apache.org/struts/dtds/struts-config_1_1.dtd">

<struts-config>
  <data-sources />
  <form-beans >
    <form-bean name="userLoginForm" type="cn.edu.scut.www.ginge.form.UserLoginForm" />

  </form-beans>

  <global-exceptions />
  <global-forwards />
  <action-mappings >
    <action
      attribute="userLoginForm"
      input="/form/userLogin.jsp"
      name="userLoginForm"
      path="/userLogin"
      scope="request"
      type="cn.edu.scut.www.ginge.action.UserLoginAction">
      <forward name="successfullyLogin" path="/successfullyLogin.jsp" />
      <forward name="failureLogin" path="/failureLogin.jsp" />
    </action>
   
    <action
     path="/accessManagePage"
     type="cn.edu.scut.www.ginge.action.AccessManagePageAction"
     roles="administrator">
      <forward name="success" path="/manage.jsp" />
      <forward name="failure" path="/accessDenied.jsp" />
    </action>

  </action-mappings>

  <controller>
        <set-property  property="processorClass"
        value="cn.edu.scut.www.ginge.CheckRequestProcessor"/>
 </controller>
  <message-resources parameter="cn.edu.scut.www.ginge.ApplicationResources" />
</struts-config>


2.2:
userLogin.jsp的主要内容:
 
        <html:form action="/userLogin.do">
            userName : <html:text property="userName"/><html:errors property="userName"/><br/>
            password : <html:password property="password"/><html:errors property="password"/><br/>
            <html:submit/><html:cancel/>

2.3:
successfullyLogin.jsp的主要内容:
<a href="http://localhost:8099/StrutsRoles/accessManagePage.do">manage all members</a>

2.4 manage.jsp的主要内容:
<h1><font color="red">这是管理员管理的页面</font></h1> <br>

2.5 accessDenied.jsp的主要内容:
 <h1><font color="red">抱歉,你的权限不够!</font></h1>

2.6:
UserLoginAction.java:


//Created by MyEclipse Struts
// XSL source (default): platform:/plugin/com.genuitec.eclipse.cross.easystruts.eclipse_3.9.210/xslt/JavaClass.xsl

package cn.edu.scut.www.ginge.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import cn.edu.scut.www.ginge.form.UserLoginForm;

/**
 * MyEclipse Struts
 * Creation date: 12-10-2005
 *
 * XDoclet definition:
 * @struts:action path="/userLogin" name="userLoginForm" input="/form/userLogin.jsp" scope="request" validate="true"
 * @struts:action-forward name="success" path="/accessDenied.jsp"
 * @struts:action-forward name="failure" path="/accessDenied.jsp"
 */
public class UserLoginAction extends Action {

    // --------------------------------------------------------- Instance Variables

    // --------------------------------------------------------- Methods

    /**
     * Method execute
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @return ActionForward
     */
    public ActionForward execute(
        ActionMapping mapping,
        ActionForm form,
        HttpServletRequest request,
        HttpServletResponse response) {
        UserLoginForm userLoginForm = (UserLoginForm) form;
        if("ginge".equals(userLoginForm.getUserName()) && "ginge".equals(userLoginForm.getPassword()))
            {
               HttpSession session = request.getSession(true);
               session.setAttribute("userName", userLoginForm.getUserName());
               return mapping.findForward("successfullyLogin");
            }
        if("fantasyginge".equals(userLoginForm.getUserName()) && "fantasyginge".equals(userLoginForm.getPassword()))
            {
               HttpSession session = request.getSession(true);
               session.setAttribute("userName", userLoginForm.getUserName());
               return mapping.findForward("successfullyLogin");
            }
        else
            return mapping.findForward("failureLogin");
    }

}

2.7:
AccessManagePageAction.java

//Created by MyEclipse Struts
// XSL source (default): platform:/plugin/com.genuitec.eclipse.cross.easystruts.eclipse_3.9.210/xslt/JavaClass.xsl

package cn.edu.scut.www.ginge.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

/**
 * MyEclipse Struts
 * Creation date: 12-10-2005
 *
 * XDoclet definition:
 * @struts:action validate="true"
 * @struts:action-forward name="success" path="/authorizedAccess.jsp"
 * @struts:action-forward name="failure" path="/accessDenied.jsp"
 */
public class AccessManagePageAction extends Action {

    // --------------------------------------------------------- Instance Variables

    // --------------------------------------------------------- Methods

    /**
     * Method execute
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @return ActionForward
     */
    public ActionForward execute(
        ActionMapping mapping,
        ActionForm form,
        HttpServletRequest request,
        HttpServletResponse response) {

        //if processRoles passed, then forward the user to the resources he has asked
        return mapping.findForward("success");
    }

}



2.8

这是RequestProcess  process method的默认实现:

public void process(HttpServletRequest request,
                        HttpServletResponse response)
        throws IOException, ServletException {

        // Wrap multipart requests with a special wrapper
        request = processMultipart(request);

        // Identify the path component we will use to select a mapping
        String path = processPath(request, response);
        if (path == null) {
            return;
        }
       
        if (log.isDebugEnabled()) {
            log.debug("Processing a '" + request.getMethod() +
                      "' for path '" + path + "'");
        }

        // Select a Locale for the current user if requested
        processLocale(request, response);

        // Set the content type and no-caching headers if requested
        processContent(request, response);
        processNoCache(request, response);

        // General purpose preprocessing hook
        if (!processPreprocess(request, response)) {
            return;
        }
       
        this.processCachedMessages(request, response);

        // Identify the mapping for this request
        ActionMapping mapping = processMapping(request, response, path);
        if (mapping == null) {
            return;
        }

        // Check for any role required to perform this action
        if (!processRoles(request, response, mapping)) {
            return;
        }

        // Process any ActionForm bean related to this request
        ActionForm form = processActionForm(request, response, mapping);
        processPopulate(request, response, form, mapping);
        if (!processValidate(request, response, form, mapping)) {
            return;
        }

        // Process a forward or include specified by this mapping
        if (!processForward(request, response, mapping)) {
            return;
        }
       
        if (!processInclude(request, response, mapping)) {
            return;
        }

        // Create or acquire the Action instance to process this request
        Action action = processActionCreate(request, response, mapping);
        if (action == null) {
            return;
        }

        // Call the Action instance itself
        ActionForward forward =
            processActionPerform(request, response,
                                 action, form, mapping);

        // Process the returned ActionForward instance
        processForwardConfig(request, response, forward);

    }


2.9
CheckRequestProcessor  的代码:

package cn.edu.scut.www.ginge;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.RequestProcessor;

public class CheckRequestProcessor extends RequestProcessor {

    protected boolean processPreprocess(HttpServletRequest request,
            HttpServletResponse response) {
        // TODO Auto-generated method stub
        HttpSession session = request.getSession(false);
        // If user is trying to access login page
        // then don't check
        if (request.getServletPath().equals("/userLogin.do")
                || request.getServletPath().equals("/login.do"))
            return true;
        // Check if userName attribute is there is session.
        // If so, it means user has allready logged in
        if (session != null && session.getAttribute("userName") != null)
            return true;
        else {
            try {
                // If no redirect user to login Page
                request.getRequestDispatcher("/form/userLogin.jsp").forward(request,
                        response);
            } catch (Exception ex) {
            }
        }
        return false;
    }

    protected boolean processRoles(HttpServletRequest request,
            HttpServletResponse response, ActionMapping mapping) throws IOException,
            ServletException {
        // TODO Auto-generated method stub
        String [] roles = mapping.getRoleNames();
        if ((roles == null) || (roles.length < 1)) {
            return (true);
        }
       
        HttpSession session = request.getSession(false);
       
        String userName = null;
        String actualRoles = null;
        if (session != null && session.getAttribute("userName") != null)
        {
            userName = (String)session.getAttribute("userName");
           
            //unidentified user
            if((actualRoles = processUserActualRole(userName)) == null)
            {
                return false;
            }
           
            for(int i = 0; i < roles.length; i ++)
            {
                if (actualRoles.equalsIgnoreCase(roles[i])) {
                    if (log.isDebugEnabled()) {
                        log.debug(" User '" + request.getRemoteUser() +
                            "' has role '" + roles[i] + "', granting access");
                    }
                   
                    return (true);
                }
            }
        }
       
//         The current user is not authorized for this action
        if (log.isDebugEnabled()) {
            log.debug(" User '" + request.getRemoteUser() +
                      "' does not have any required role, denying access");
        }
       
       
        //user's priviledge isn't sufficient
        /*
        response.sendError(
                HttpServletResponse.SC_FORBIDDEN,
                getInternal().getMessage("notAuthorized", mapping.getPath()));
                */
        try {
            // If no redirect user to login Page
            request.getRequestDispatcher((mapping.findForward("failure")).getPath()).forward(request,
                    response);
        } catch (Exception ex) {
        }
       
       
        return (false);
    }

    protected void processContent(HttpServletRequest request,
            HttpServletResponse response) {
        // TODO Auto-generated method stub
        // Check if user is requesting ContactImageAction
        // if yes then set image/gif as content type

        response.setContentType("text/html;charset=gb2312");

    }
   
    protected String processUserActualRole(String userName)
    {
        //or other bussiness login,or access database to get the user information
        if("fantasyginge".equalsIgnoreCase(userName))
        {
            return "administrator";
        }
        else if("ginge".equals(userName))
        {
            return "normalUser";
        }
        else
            return null;
    }


}


程序运行效果:
用用户名ginge登录并且访问已设roles访问控制的结果:

抱歉,你的权限不够!


而用fantasyginge登录并且访问已设roles访问控制的结果:

这是管理员管理的页面


posted on 2005-12-10 23:51 fantasyginge 阅读(329) 评论(0)  编辑  收藏 所属分类: Struts

只有注册用户登录后才能发表评论。


网站导航: