在看了轉載的那篇【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 閱讀(345) 評論(0)  編輯  收藏 所屬分類: Struts

          只有注冊用戶登錄后才能發表評論。


          網站導航:
           
           
          主站蜘蛛池模板: 冀州市| 霍山县| 冕宁县| 广丰县| 普安县| 旬阳县| 成都市| 当阳市| 辽宁省| 长宁区| 连南| 惠州市| 内丘县| 庐江县| 日照市| 买车| 南皮县| 孙吴县| 新安县| 合阳县| 瓮安县| 上杭县| 临西县| 柳江县| 敦化市| 兴文县| 祁阳县| 北流市| 富平县| 宾川县| 榕江县| 夏邑县| 建宁县| 五家渠市| 阳江市| 金华市| 威信县| 浙江省| 博罗县| 塔河县| 曲阜市|