struts1.x 校验

h1>登录(validator框架客户端验证(javascript))</h1>

<hr>

<html:javascript formName="loginForm"/>

<html:form action="login2.do" onsubmit="return validateLoginForm(this)">

      username : <html:text property="username"/><br/>

      password : <html:password property="password"/><br>

   <html:submit/>

  </html:form>



25、声明式异常



Action中

UserManager.getInstance().login(username, password);

       return mapping.findForward("success");



业务逻辑记得先建立两个异常类

    public void login(String username, String password) {

//     if (!"admin".equals(username)) {

//         throw new UserNotFoundException();

//     }

//     if (!"admin".equals(password)) {

//         throw new PasswordErrorException();

//     }

//  }



Struts配置文件中



定义全局异常



<global-exceptions>

    <!-- 全局异常

           <exception key="user.not.found" type="com.bjsxt.struts.UserNotFoundException" path="/login_error.jsp"/>

           <exception key="user.password.error" type="com.bjsxt.struts.PasswordErrorException" path="/login_error.jsp"/>

     -->



定义action

<action-mappings>

       <action path="/login"

              type="com.bjsxt.struts.LoginAction"

              name="loginForm"

              scope="request"

              validate="false"

              input="/login.jsp"<!-- 默认异常转向 -->

       >  

       <!--

           <exception key="user.not.found" type="com.bjsxt.struts.UserNotFoundException" path="/login_error.jsp"/>

           <exception key="user.password.error" type="com.bjsxt.struts.PasswordErrorException" path="/login_error.jsp"/>

        -->  

           <forward name="success" path="/login_success.jsp"/>

           <forward name="error" path="/login.jsp"/>

       </action>



Jsp页面

<html:errors/>



声明式异常传递一个站位附的办法



异常类中

public class UserNotFoundException extends RuntimeException {



    public UserNotFoundException(String msg) {

       super(msg);

    }

}



业务调用中



public void login(String username, String password) {

//     if (!"admin".equals(username)) {

//         throw new UserNotFoundException(username);

//     }

//     if (!"admin".equals(password)) {

//         throw new PasswordErrorException();

//     }

//  }



26、个性化异常处理



建立资源文件



user.login.success={0},登录成功

user.not.found=用户不能找到,用户名称=[{0}]

user.password.error=密码错误

user.login.error=登录失败



建立一个异常处理类



public class ErrorCodeException extends RuntimeException {

   

    private String errorCode;

   

    private Object[] args;

    //没有占位符

    public ErrorCodeException(String errorCode) {

       this(errorCode, null);

    }

    //有一个占位符的

    public ErrorCodeException(String errorCode, Object args0) {

       this(errorCode, new Object[]{args0});

    }

    //有多个占位符的

    public ErrorCodeException(String errorCode, Object[] args) {

       this.errorCode = errorCode;

       this.args = args;

    }

   

    public String getErrorCode() {

       return errorCode;

    }



    public Object[] getArgs() {

       return args;

    }

}



业务调用类



public void login(String username, String password) {

//     if (!"admin".equals(username)) {

//         throw new ErrorCodeException("user.not.found", username);

//     }

//     if (!"admin".equals(password)) {

//         throw new ErrorCodeException("user.password.error");

//     }



Struts配置文件



先建立一个继承handle 类复写里面的一点方法

public class ErrorCodeExceptionHandler extends ExceptionHandler {



    public ActionForward execute(

            Exception ex,

            ExceptionConfig ae,

            ActionMapping mapping,

            ActionForm formInstance,

            HttpServletRequest request,

            HttpServletResponse response)

            throws ServletException {

    //写下面的if方法

        if (!(ex instanceof ErrorCodeException)) {

            return super.execute(ex, ae, mapping, formInstance, request, response);

        }

       

    //

            ActionForward forward = null;

            ActionMessage error = null;

            String property = null;



            // Build the forward from the exception mapping if it exists

            // or from the form input

            if (ae.getPath() != null) {

                forward = new ActionForward(ae.getPath());

            } else {

                forward = mapping.getInputForward();

            }



            // Figure out the error

            if (ex instanceof ModuleException) {

                error = ((ModuleException) ex).getActionMessage();

                property = ((ModuleException) ex).getProperty();

            } else {

            //修改下面   

              ErrorCodeException ece = (ErrorCodeException)ex;

              String errorCode = ece.getErrorCode();

              Object[] args = ece.getArgs();

              error = new ActionMessage(errorCode, args);

              property = error.getKey();

            //

                //error = new ActionMessage(ae.getKey(), ex.getMessage());

                //property = error.getKey();

            }



            this.logException(ex);



            // Store the exception

            request.setAttribute(Globals.EXCEPTION_KEY, ex);

            this.storeException(request, property, error, forward, ae.getScope());



            return forward;



        }   

}



写struts配置文件的这里



全局异常

  <exceptionkey="error.exception" type="com.bjsxt.struts.AppException" handler="com.bjsxt.struts.AppExceptionHandler"/>



27、不要个性化异常



建立一个异常类

public class AppException extends RuntimeException {

   

    public AppException(String msg) {

       super(msg);

    }



业务调用



public void login(String username, String password) {

       if (!"admin".equals(username)) {

           throw new AppException("用户不能找到,用户=【" + username + "】");

       }

       if (!"admin".equals(password)) {

           throw new AppException("密码不正确!");

       }



Struts配置文件

      <exceptionkey="error.exception" type="com.bjsxt.struts.AppException"/>



配置资源文件



error.exception={0}



没有必要建立一个异常处理类



28、forwardaction的使用



只要这样配置就能转向了不用配置action



<action path="/login1"

              type="org.apache.struts.actions.ForwardAction"

              parameter="/login.jsp"

       ></action>



29、Dispatchaction



页面转向window.self.location = "usermaint.do?command=find&userId=" + document.getElementsByName("selectFlag")[j].value;



采用DispathAction

    * 如果覆写DispathAction中的execute方法,必须显示的用super调用execute方法

    * parameter参数值不能是execute或perform





30、容错处理//可以去掉查找所有用户的方法

protected ActionForward unspecified(ActionMapping mapping, ActionForm form,

           HttpServletRequest request, HttpServletResponse response)

           throws Exception {

      

       System.out.println("-----------UserAction.unspecified()-----------");

      

       //调用业务逻辑操作

       List userList = UserManager.getInstance().findAllUserList();

       request.setAttribute("userlist", userList);

      

       return mapping.findForward("list_success");

      

//     ActionForward af = new ActionForward();

//     af.setPath("/user/usermaint.do?command=list");

//     af.setRedirect(true);

//     return af;

    }



31、模式匹配



建立三个页面

Add—success.jsp

Del-success.jsp

Modify-success.jsp



Jdp页面中



    <a href="user/add.do?command=add">添加用户</a><br>

    <a href="user/del.do?command=del">删除用户</a><br>

    <a href="user/modify.do?command=modify">修改用户</a><br>



Struts配置



<action path="/user/*"

              type="com.bjsxt.struts.UserAction"

              parameter="command" 

       >

           <!--

           <forward name="success" path="/user/{1}_success.jsp"/>

            -->

            <forward name="success" path="/{0}_success.jsp"/>

       </action>



Action中

return mapping.findForward("success");



33、补充说明



要把所有的jsp放到web-inf下浏览器是不能访问得到的,只有通过Action才能访问得到





注意图片的现实只与basename有关系也目录无关系

../img

<action path="/basedata/additem"与下面无关

<forwardname="upload_detail" path="/WEB-INF/jsp/basedata/item_upload.jsp"/>






验证用户存在与否

建立一个基本的action,然后其他action继承它就可以了!

public class BaseAction extends DispatchAction {



    @Override

    public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {

       if (request.getSession().getAttribute("user") == null) {

           return mapping.findForward("index");

       }

      

       return super.execute(mapping, form, request, response);

    }



其他action

public class ItemAction extends BaseAction {



注意返回的设置要带上返回的差数

否则用过滤类来保存

或用threadlocal做传递



function goBack() {

       window.self.location = "item.do?command=list&pageNo=${itemForm.pageNo}&pageSize=${itemForm.pageSize}";

    }



下拉选择列表的写法



<td><select name="unitId" class="select1" id="unitId">

         <c:forEach items="${drp:getItemUnitList()}" var="iu" >

             <c:set var="select" value=""/>

             <c:if test="${ iu.id eq item.unit.id }">

                <c:set var="select" value="selected"/>

             </c:if>

             <option value="${iu.id}" ${ select }>${iu.name}</option>

        </c:forEach>

        </select></td>





分页补充



function resetItem() {

       document.getElementsByName("clientIdOrName").value = "";

    }

   

    function topPage() {

       window.self.location = "item.do?command=list&pageNo=${pagemodel.topPageNo}&pageSize=${itemForm.pageSize}&clientIdOrName=${ itemForm.clientIdOrName }"

    }

   

    function previousPage() {

       window.self.location = "item.do?command=list&pageNo=${pagemodel.previousPageNo}&pageSize=${itemForm.pageSize}&clientIdOrName=${ itemForm.clientIdOrName }"

    }  

   

    function nextPage() {

       window.self.location = "item.do?command=list&pageNo=${pagemodel.nextPageNo}&pageSize=${itemForm.pageSize}&clientIdOrName=${ itemForm.clientIdOrName }"

    }

   

    function bottomPage() {

       window.self.location = "item.do?command=list&pageNo=${pagemodel.bottomPageNo}&pageSize=${itemForm.pageSize}&clientIdOrName=${ itemForm.clientIdOrName }"

    }

   

按键事件的设置

function myOnkeypress() {

       if (window.event.keyCode == 13) {

           queryItem();

       }

单元格中



<td width="46%"><input name="clientIdOrName" type="text"  class="text1" id="clientIdOrName" value="${ itemForm.clientIdOrName }" size="50" maxlength="50" onkeypress="myOnkeypress()">

你可能感兴趣的:(JavaScript,框架,jsp,struts,浏览器)