struts1入门

1. 在myEcliple中添加struts1.2支持:

项目上右键 - myEclipse - add struts Capabilities - 选择struts1.2 - ...

注:myEcliple会帮我们做几件事:1.导入struts1.2所需的包;2.在web.xml添加一个filter(org.apache.struts.action.ActionServlet);3.WEB-INF下添加几个tld文件(struts标签)和struts-config.xml、validator-rules.xml;4.src下新建了国际化文件ApplicationResources.properties。

2.通过struts-config.xml的图形化界面新建Form、Action、Jsp。

注:如果JavaBean自己编写,需继承ActionForm。页面通过xx.do可以进入对应action的execute方法。

3.如果action类继承DispatchAction,复制execute方法自定义方法名,如doLogin,在struts-config.xml中对该aciton的配置添加属性parameter="method",此时,就可以通过url参数method=doLogin进入doLogin方法。

4.错误处理机制:

javaBean中重写validate方法:

  ActionErrors errors = new ActionErrors();
  if(!this.name.equals("admin")){
   errors.add("loginError",new ActionMessage("name.is.not.exists"));
  }
  return errors;

ApplicationResources.properties中添加 name.is.not.exists=用户名不存在

<%@ taglib uri="http://struts.apache.org/tags-html" prefix="html"%> //jsp页面引入struts1标签

<html:errors property="loginError"/> //jsp页面显示错误信息

或在action方法中:

  LoginForm loginForm = (LoginForm) form;// TODO Auto-generated method stub
  ActionMessages messages = new ActionMessages();
  if(loginForm.getName().equals("admin")){
   messages.add("loginError",new ActionMessage("admin.can.not.login"));
  }
  if(!messages.isEmpty()){
   super.saveErrors(request.getSession(), messages);
   return mapping.findForward("input");
  }
  return mapping.findForward("login_success");

5.所生成的struts-config.xml:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.2//EN" "http://struts.apache.org/dtds/struts-config_1_2.dtd">
<struts-config>
  <data-sources />
  
  <form-beans >
    <form-bean name="loginForm" type="com.yourcompany.struts.form.LoginForm" >
     <form-property name="name" type="java.lang.String"></form-property>
    </form-bean>
  </form-beans>
  
  <global-exceptions />
  <global-forwards />
  
  <action-mappings >
    <action
      attribute="loginForm"
      input="/index.jsp"
      name="loginForm"
      path="/login"
      scope="request"
      type="com.yourcompany.struts.action.LoginAction">
      <set-property property="cancellable" value="true" />
      <forward name="input" path="/index.jsp" />
    </action>
  </action-mappings>
  <message-resources parameter="com.yourcompany.struts.ApplicationResources" />
</struts-config>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值