关于strut1的内部原理及相关实现方案
No.1 Servlet 和 Struts开发的步骤对比
基于Servlet开发的5个步骤:针对于(service方法中)
1> 获得表单请求的参数 ,如:request.getParameter("xxx")
2> 校验请求参数的合法性
3> 将参数传入到指定的JavaBean中,(空值过滤,类型转换)
4> 处理业务
5> 转发或重定向到指定路径
基于Struts开发的个步骤:针对于(execute方法中)
1> 获得表单请求的对象(支持类型转换 , 默认情况不会对空值转换成null)
a> 如果FormBean对应的无论是基本类型还是包装类型及BigDecimal、BigInteger,空字符串都会转换成对应的基本类型默认值
b> 在web.xml中配置convertNull=true | 1 | y | yes | on ,之后,那么FormBean中的包装类型及BigDecimal、BigInteger会将空字符串都会转换成对应的基本类型默认值
2> 校验请求参数的合法性
3> 将FormBean的属性值传入到指定的JavaBean中
4> 处理业务
5> 转发或重定向到指定路径
No.2 重定向 和 转发
转发与重定向的区别:
1> 转发与重定向在使用"/"时的区别:
转发里使用"/"表示到达项目的根路径,如: http://serverName:port/projectContext
重定向使用"/"表示到达Web容器的根路径,如: http://serverName:port
2> WEB-INF目录中的文件只能通过转发请求到,重定向无法请求
3> 转发基于一次请求,地址栏不发生改变,共享同一个request请求作用域,而每次重定向都发送新的请求,地址栏发生改变,不共享同一个request请求作用域
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
PersonForm personForm = (PersonForm) form;
Person person = new Person();
/*
person.setName(personForm.getName());
person.setGender(personForm.getGender());
person.setEmail(personForm.getEmail());
IdCard idCard = new IdCard();
idCard.setCardNo(personForm.getCardNo());
person.setIdCard(idCard);
*/
BeanUtils.copyProperties(person, personForm); FormBean 转化成标准JavaBean 让软件不依赖于Strut框架,回归到java基本构架中。
IdCard idCard = new IdCard();
idCard.setCardNo(personForm.getCardNo());
person.setIdCard(idCard);
System.out.println(person.getName());
System.out.println(person.getEmail());
System.out.println(person.getGender());
System.out.println(person.getIdCard().getCardNo());
/*
response.sendRedirect(request.getContextPath() + "/person/list.do");servlet 中的重定向处理方案
return null;
*/
/*
//new ActionForward("/person/list.do")中path参数前默认加入request.getContextPath()
ActionForward forward = new ActionForward("/person/list.do" , false); // false是默认值struts中利用API处理重定向的方式
forward.setRedirect(true);
return forward;
*/
return mapping.findForward("pathName");
}
struts中通过配置文件处理重定向
如果需要传入查询字符串,那么注意,这里是xml文件,一定要符合xml规则,如:&yyy=yyy必须使用&yyy=yyy
<forward name="saveForm" path="/WEB-INF/views/person/saveForm.jsp?xxx=xxx&yyy=yyy"/>
<action name="绑定的FormBean名称" path="请求地址" type="指定的Action类全名">
<forward name="外表API调用的属性名pathName" path="重定向地址" redirect="true"/>
</action>
servlet 和 strutsAPI 的合理搭配 处理一个Action类可以同时多次转发或重定向
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
ActionForward forward = new ActionForward();
String command = request.getParameter("command");
if("saveForm".equals(command)){
forward.setPath("......");
} else if("save".equals(command)){
forward.setPath("......");
}
return forward;
}
备注 :以上内容都是自己在总计 如果有不合理的地方希望大家可以指出,相互学习。