1、异常(例:struts_7)
1.1 src中:
public class MyExceptionHandle extends ExceptionHandler {
@Override
public ActionForward execute(Exception ex, ExceptionConfig ae,ActionMapping mapping, ActionForm formInstance,
HttpServletRequest request, HttpServletResponse response) throws ServletException {
// TODO Auto-generated method stub
//处理自己定义的异常
String pack = ex.getClass().getPackage().getName();
if("com.pk.exception".equals(pack)){
String key = ae.getKey();
request.setAttribute("errors",key);
String path = ae.getPath();
return new ActionForward(path);
}
return super.execute(ex, ae, mapping, formInstance, request, response);
}
}
配置在配置文件中配置
<action path="/user/save" type="com.pk.struts.action.UserAction" parameter="saveUser" name="saveUserForm" scope="request">
<exception key="保存失败" type="com.pk.exception.DaoException"
path="/error.jsp" handler="com.pk.exception.MyExceptionHandle"
></exception>
</action>
继承runtimeException或exception
2、action是单例
3、actionForm是多例
4、struts1.2的工作流程
所有以.do结尾的请求,都会由Web.xml里面的actionServlet截获,ActionServlet会加载一个Struts-config.xml
,在这个配置文件当中<action-mapping>里面可以有多个action,每个action标签当中都会有path="/请求",对应 type="Action"来处理对应请求
5、生成actionform有两种方式
5.1一种是在配置文件当中动态获取
<form-bean name="loginForm" type="org.apache.struts.action.DynaActionForm">
<form-property name="uname" type="java.lang.String"></form-property>
<form-property name="pwd" type="java.lang.String"></form-property>
</form-bean>
5.1.1该方法当用到bean时需要在action中使用一个类,用法如下
DynaActionForm dynaActionForm = (DynaActionForm) form;
String uname = (String) dynaActionForm.get("uname");
String pwd = (String) dynaActionForm.get("pwd");
5.2一种是继承ActionForm
6、跳转(两种方法)
<global-forwards/>下的<forward/>里配置 记住forward里有个redirect属性
在<action-mapping/>下的<forward/>里配置
7、上传文件 要使用FormFile类
7.1步骤如下
UploadForm uploadForm = (UploadForm) form;
String fileName = uploadForm.getFileName();
FormFile myFile = uploadForm.getMyFile();
System.out.println(fileName);
FileOutputStream fileOutputStream = new FileOutputStream("c://"+myFile.getFileName());
fileOutputStream.write(myFile.getFileData());
fileOutputStream.flush();
fileOutputStream.close();
8、效验
8.1 在actionform中重载 validate方法
@Override
public ActionErrors validate(ActionMapping mapping,
HttpServletRequest request) {
// TODO Auto-generated method stub
ActionErrors actionErrors = new ActionErrors();
if(uname==null||uname.trim().length()<1){
actionErrors.add("uname", new ActionMessage("errors.uname"));
}
if(pwd==null||pwd.trim().length()<1){
actionErrors.add("pwd", new ActionMessage("errors.pwd"));
}
if(age<18||age>100){
actionErrors.add("age", new ActionMessage("errors.age"));
}
return actionErrors;
}
8.2 需要在配置文件中配置
<action-mappings >
<action path="/register" type="com.pk.struts.action.UserAction" name="userForm" scope="request" validate="true" input="/user.jsp">
</action>
</action-mappings>