- nihongye
- 等级:
- 性别:
- 文章: 863
- 积分: 1533
- 来自: 深圳
|
发表时间:2007-06-12
最后修改:2009-08-01
问题1.从客户端传来的id,需要转化成持久化对象,webwork默认会为我们创建出空对象,但不满足,希望webwork能按照id值绑定持久化对象.
解决办法:创建自己的转化器
1.创建xwork-conversion.properties,内容如下
com.abest.common.domain.CommonEntity=com.abest.common.EntityWebworkConverter
其中CommonEntity为所有持久化实体类的超类,更详细的资料见:
http://wiki.opensymphony.com/display/XW/XWork+Conversion
2.实现自定义转换器
public class EntityWebworkConverter extends WebWorkTypeConverter {
public static EntityWebworkConverterDelegate delegate = null;
public EntityWebworkConverter() {
}
public Object convertFromString(Map map, String[] strings, Class toClass) {
return delegate.convertFromString(map,strings,toClass);
}
public String convertToString(Map map, Object o) {
return delegate.convertToString(map,o);
}
}
public class EntityWebworkConverterDelegate extends WebWorkTypeConverter {
private QueryService queryService = null;
public EntityWebworkConverterDelegate(QueryService queryService) {
this.queryService = queryService;
}
public Object convertFromString(Map map, String[] strings, Class toClass) {
if(strings.length > 0)
{
int id = 0;
try {
id = Integer.parseInt(strings[0]);
} catch (NumberFormatException e) {
}
if(id > 0)
{
return queryService.find(toClass,id);
}
}
try {
return toClass.newInstance();
} catch (InstantiationException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
public void setQueryService(QueryService queryService) {
this.queryService = queryService;
}
public String convertToString(Map map, Object o) {
return null;
}
}
在这里,因为不了解webwork有什么合适的机制对converter的创建进行控制,因此,converter使用静态属性delegate,该属性由ServletContextListener来注入
这样便可完成参数的绑定了,页面传的参数形式,譬如 foo.bar=1即可
问题2:如何绑定到列表
1.使用java5泛型,xwork..-tiger.jar
2.客户端参数形式changedList[0].id=1,changedList[0].name=name,changedList[1].id=2,changedList[1].name=name2
3.预load对象,以使得其它属性能正确的绑定到对象中.处理逻辑为"先过滤出id,对起进行参数绑定,之后,再交由webwork自带的参数拦截器去绑定其它的参数",拦截器代码如下(保留使用原有的params拦截器):
public class AnotherGridEditDataBindInterceptor extends AroundInterceptor {
protected void after(ActionInvocation actionInvocation, String s) throws Exception {
}
protected void before(ActionInvocation actionInvocation) throws Exception {
Object action = actionInvocation.getAction();
Map map = actionInvocation.getInvocationContext().getParameters();
Map entityIdMap = new HashMap();
for(int i = 0;i < 200;i++)
{
String key = "changedList[" + i + "].id";
String[] ids = (String[]) map.get(key);
if(ids != null && ids.length > 0)
{
entityIdMap.put("changedList["+i+"]",ids);
map.remove(key);
}
}
for(int i = 0;i < 200;i++)
{
String key = "newList[" + i + "].id";
String[] ids = (String[]) map.get(key);
if(ids != null && ids.length > 0)
{
entityIdMap.put("newList["+i+"]",ids);
map.remove(key);
}
}
bindParametersToTarget(entityIdMap,action);
}
private void bindParametersToTarget(Map propertiesValue, Object target) {
ActionContext invocationContext = ActionContext.getContext();
OgnlValueStack stack = null;
Object preRoot = null;
try {
invocationContext.put(InstantiatingNullHandler.CREATE_NULL_OBJECTS, Boolean.TRUE);
invocationContext.put(XWorkMethodAccessor.DENY_METHOD_EXECUTION, Boolean.TRUE);
invocationContext.put(XWorkConverter.REPORT_CONVERSION_ERRORS, Boolean.TRUE);
if (propertiesValue != null) {
stack = ActionContext.getContext().getValueStack();
preRoot = stack.pop();
stack.push(target);
for (Iterator iterator = propertiesValue.entrySet().iterator();
iterator.hasNext();) {
Map.Entry entry = (Map.Entry) iterator.next();
stack.setValue(entry.getKey().toString(), entry.getValue());
}
}
} finally {
invocationContext.put(InstantiatingNullHandler.CREATE_NULL_OBJECTS, Boolean.FALSE);
invocationContext.put(XWorkMethodAccessor.DENY_METHOD_EXECUTION, Boolean.FALSE);
invocationContext.put(XWorkConverter.REPORT_CONVERSION_ERRORS, Boolean.FALSE);
if (preRoot != null) {
stack.pop();
stack.push(preRoot);
}
}
}
}
其中,changedList表示的是修改过的对象,newList表示的是新增的对象
总结:需要建立Xwork的Converter,Interceptor。servlet的ServletContextListener为converter注入orm的持久对象查找方法;orm提供find(class,id)这样的方法
声明:ITeye文章版权属于作者,受法律保护。没有作者书面许可不得转载。
|
返回顶楼 |
|
|
- downpour
- 等级:
- 性别:
- 文章: 1516
- 积分: 2448
- 来自: 上海
|
好方法!提供了我另外一个思路。
我以前一直是用拦截器+特殊命名规范来做的。比如,我规定,需要绑定持久化对象的命名必须以#结尾:foo.bar#=1。由于默认的params拦截器会把带有#符号的命名过滤掉,所以这些命名正好可以进入我自己的拦截器,截断以后拼上id,再load出来。
如果用Spring的话,我直接使用WebApplicationContextUtils中的静态方法来getBean获取Service,ServletContext则直接ServletActionContext.getServletContext()得到。其实你这里如果用Spring,也可以采取这种方式,应该不需要那个static的delegate了。
|
返回顶楼 |
|
|
- winneryong
- 等级: 初级会员
- 性别:
- 文章: 2
- 积分: 32
- 来自: 北京
|
能不能把你的代码贴全啊.包括配置文件,以及那些用ServletContextListener注入的代码
|
返回顶楼 |
|
|
- lllyq
- 等级:
- 性别:
- 文章: 350
- 积分: 1022
- 来自: Shanghai
|
这个一般我是用ModelDriven(在params之前)了,getModel中去判断有id则取,否则新建实例,用ModelDriven好在validation/i18n都一并绑定了, 多个对象的情况是通过一个ModelSetable对象对多个对象的引用来实现的,也是在getModel中拿,通过action上的范型声明是否为ModelSetable判断,参数传递跟你的类似,不过是keys数组与modelSet.models数组的参数传递,如keys[0]=1,modelSet.models[0].name=1, keys[1]=2,modelSet.models[1].name=2
|
返回顶楼 |
|
|
- linqing
- 等级: 初级会员
- 性别:
- 文章: 3
- 积分: 30
- 来自: 上海
|
如果是Webwork2和Spring结合的话,可以把Converter直接配置到spring里面,转换的时候Webwork会取到这个Bean,名字为“com.abest.common.EntityWebworkConverter”
|
返回顶楼 |
|
|
- linqing
- 等级: 初级会员
- 性别:
- 文章: 3
- 积分: 30
- 来自: 上海
|
/*
* DocumentConventor.java
*
* Created on 2007?1?3?, ??11:15
*
* To change this template, choose Tools | Template Manager
* and open the template in the editor.
*/
package edirectory.web.converter;
import com.opensymphony.webwork.util.WebWorkTypeConverter;
import edirectory.persistence.Document;
import edirectory.service.DocumentManager;
import java.util.Map;
import org.springframework.web.context.WebApplicationContext;
/**
*
* @author linqing
*/
public class DocumentConverter extends WebWorkTypeConverter {
private DocumentManager documentManager;
public String convertToString(Map context, Object o) {
return ((Document)o).getId().toString();
}
public Object convertFromString(Map context, String[] values, Class toClass) {
if(values[0].equals("") ) {
return null;
}
Long id = Long.parseLong(values[0]);
return documentManager.find(toClass, id);
}
public DocumentManager getDocumentManager() {
return documentManager;
}
public void setDocumentManager(DocumentManager documentManager) {
this.documentManager = documentManager;
}
}
|
返回顶楼 |
|
|
- linqing
- 等级: 初级会员
- 性别:
- 文章: 3
- 积分: 30
- 来自: 上海
|
<!-- Services -->
<bean id="documentManager"
class="edirectory.service.impl.JpaDocumentManager"
scope="singleton"
autowire="byName" />
<!-- Converters -->
<bean id="edirectory.web.converter.DocumentConverter"
class="edirectory.web.converter.DocumentConverter"
scope="singleton"
autowire="byName" />
- 描述: 一个通用的EntityManager,整个系统是配置出来的
- 大小: 160.5 KB
|
返回顶楼 |
|
|
- lijiangt
- 等级:
- 文章: 31
- 积分: 181
|
我最近也在思考这个问题,之前在struts 1.3.8里面都是这样做的:
struts-config.xml 表单配置:
xml 代码
- <form-bean name="projectForm"
- type="org.apache.struts.validator.LazyValidatorForm">
- </form-bean>
struts-config.xml action-mapping配置:
xml 代码
- <action path="/project"
- type="com.bupticet.strutsinterceptor.InterceptorActionProxy"
- name="projectForm" parameter="method" scope="request"
- validate="false" cancellable="true">
- <forward name="add-success" path="/add_project.jsp" />
- <forward name="save-success"
- path="/project.do?method=view&id=" redirect="true" />
- <forward name="save-cancel" path="/project.do"
- redirect="true" />
- <forward name="save-failure" path="/add_project.jsp" />
- <forward name="edit-success" path="/edit_project.jsp" />
- <forward name="view-success" path="/view_project.jsp" />
- <forward name="list-success" path="/list_project.jsp" />
- <forward name="update-failure" path="/edit_project.jsp" />
- <forward name="update-cancel" path="/project.do"
- redirect="true" />
- <forward name="update-success"
- path="/project.do?method=view&id=" redirect="true" />
- <forward name="delete-success" path="/project.do?method=list" redirect="true"/>
- <forward name="search-page" path="/search_project.jsp"/>
- </action>
页面表单:
xml 代码
- <html:form action="/project?method=save" method="post">
- <tr>
- <td width='10%' nowrap class="boxHead">项目名称:</td>
- <td background="../images/leftbg2.gif"><html:text property="name" size='100' maxlength='100'/></td>
- </tr>
-
- <tr>
- <td width='10%' nowrap class="boxHead">项目编号:</td>
- <td background="../images/leftbg2.gif"><html:text property="projectNo" size='50' maxlength='60'/></td>
- </tr>
-
- <tr>
- <td width='10%' nowrap class="boxHead">项目类别:</td>
- <td background="../images/leftbg2.gif"><html:text property="sort" size='50' maxlength='60'/>
- <%
- String[] allExistSorts = com.bupticet.research.web.collection.ProjectCollection.getExistSorts();
- if(allExistSorts.length>0){
- pageContext.setAttribute("allExistSorts", allExistSorts);
- %>
- <==备选项:<html:select property="existSorts" onchange="autoPopulate(this,'sort');">
- <html:option value="-1">--- 请选择 ---</html:option>
- <html:option value=""></html:option>
- <html:options name="allExistSorts" labelName="allExistSorts" />
- </html:select>
- <%} %>
-
- </td>
- </tr>
- ......
Action代码:
java 代码
-
-
-
- package com.bupticet.research.web.action;
-
- import java.util.Enumeration;
- import java.util.HashMap;
- import java.util.List;
- import java.util.Map;
-
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
-
- import org.apache.commons.beanutils.BeanUtils;
- import org.apache.commons.beanutils.DynaBean;
- import org.apache.struts.action.ActionForm;
- import org.apache.struts.action.ActionForward;
- import org.apache.struts.action.ActionMapping;
-
- import com.bupticet.base.web.struts.BaseAction;
- import com.bupticet.base.web.struts.StrutsUtils;
- import com.bupticet.constant.StrutsConstant;
- import com.bupticet.helper.GlobalSession;
- import com.bupticet.model.ClientInfo;
- import com.bupticet.research.entity.Fruit;
- import com.bupticet.research.entity.Project;
- import com.bupticet.research.service.ProjectManager;
- import com.bupticet.util.RequestUtils;
- import com.bupticet.util.encode.Decoder;
-
-
-
-
-
- public class ProjectAction extends BaseAction {
-
- private ProjectManager projectManager;
-
-
-
-
-
- public void setProjectManager(ProjectManager projectManager) {
- this.projectManager = projectManager;
- }
-
-
-
-
- public ProjectAction() {
- }
-
-
-
-
-
-
-
-
-
- @Override
- public ActionForward delete(ActionMapping mapping, ActionForm form,
- HttpServletRequest req, HttpServletResponse res) throws Exception {
- String id = req.getParameter("id");
- checkInputPara(new String[] { id });
- projectManager.removeObject( id);
- return mapping.findForward(StrutsConstant.DELETE_SUCCESS);
- }
-
-
-
-
-
-
-
-
-
- @Override
- public ActionForward edit(ActionMapping mapping, ActionForm form,
- HttpServletRequest req, HttpServletResponse res) throws Exception {
- String id = req.getParameter("id");
- checkInputPara(new String[] { id });
- Project p = projectManager.getObject( id);
- if (p == null) {
- this.throwEntityMissingException();
- }
- DynaBean f = (DynaBean) form;
- BeanUtils.copyProperties(f, p);
- saveToken(req);
- return mapping.findForward(StrutsConstant.EDIT_SUCCESS);
- }
-
-
-
-
-
-
-
-
-
- @Override
- public ActionForward list(ActionMapping mapping, ActionForm form,
- HttpServletRequest req, HttpServletResponse res) throws Exception {
- int pageNum = RequestUtils.getIntParameter(req, "pageNum", 1);
- boolean isAsc = RequestUtils.getBooleanParameter(req, "isAsc", false);
- String orderField = RequestUtils.getStringParameter(req, "orderField",
- "project0.BEGIN_DATE");
- req.setAttribute("list", projectManager.getObjectsForPage(
- pageNum, 20, orderField, isAsc));
- return mapping.findForward(StrutsConstant.LIST_SUCCESS);
- }
-
-
-
-
-
-
-
-
-
- @Override
- public ActionForward save(ActionMapping mapping, ActionForm form,
- HttpServletRequest req, HttpServletResponse res) throws Exception {
- if (isCancelled(req)) {
- return mapping.findForward(StrutsConstant.SAVE_CANCEL);
- }
- checkAndClearToken(req);
- saveToken(req);
- if (!this.validateForm(mapping, form, req)) {
- return mapping.findForward(StrutsConstant.SAVE_FAILURE);
- }
- DynaBean f = (DynaBean) form;
- if (null != projectManager.checkName((String) f.get("name"))) {
- this.saveErrors(req,
- addError("projectForm.error.existSameNameProject"));
- return mapping.findForward(StrutsConstant.SAVE_FAILURE);
- }
- if (null != projectManager.checkNo((String) f.get("projectNo"))) {
- this.saveErrors(req,
- addError("projectForm.error.existSameNoProject"));
- return mapping.findForward(StrutsConstant.SAVE_FAILURE);
- }
- GlobalSession globalSession = (GlobalSession) req.getSession(true)
- .getAttribute("globalSession");
-
- Project project = new Project();
- BeanUtils.copyProperties(project, f);
- project.setEnterorId(globalSession.getUserID());
- projectManager.saveObject( project);
- return StrutsUtils.getExtForward(mapping, StrutsConstant.SAVE_SUCCESS,
- project.getId());
- }
-
-
-
-
-
-
-
-
-
- @Override
- public ActionForward update(ActionMapping mapping, ActionForm form,
- HttpServletRequest req, HttpServletResponse res) throws Exception {
- if (isCancelled(req)) {
- return mapping.findForward(StrutsConstant.UPDATE_CANCEL);
- }
- checkAndClearToken(req);
- saveToken(req);
- if (!this.validateForm(mapping, form, req)) {
- return mapping.findForward(StrutsConstant.UPDATE_FAILURE);
- }
- DynaBean f = (DynaBean) form;
- String id = (String) f.get("id");
- String existId = projectManager.checkName((String) f.get("name"));
- if (existId != null && !id.equals(existId)) {
- this.saveErrors(req,
- addError("projectForm.error.existSameNameProject"));
- return mapping.findForward(StrutsConstant.UPDATE_FAILURE);
- }
- existId = projectManager.checkNo((String) f.get("projectNo"));
- if (existId != null && !id.equals(existId)) {
- this.saveErrors(req,
- addError("projectForm.error.existSameNoProject"));
- return mapping.findForward(StrutsConstant.UPDATE_FAILURE);
- }
- Project project = projectManager.getObject(
- (String) f.get("id"));
- BeanUtils.copyProperties(project, f);
- projectManager.saveObject( project);
- return StrutsUtils.getExtForward(mapping,
- StrutsConstant.UPDATE_SUCCESS, project.getId());
- }
-
-
-
-
-
-
-
-
-
- @Override
- public ActionForward view(ActionMapping mapping, ActionForm form,
- HttpServletRequest req, HttpServletResponse res) throws Exception {
- String id = req.getParameter("id");
- checkInputPara(new String[] { id });
- Project p = projectManager.getObject( id);
- if (p == null) {
- this.throwEntityMissingException();
- }
- List<Fruit> fruits = projectManager.getFruitsOfProject(p.getId());
- req.setAttribute("fruits", fruits);
- req.setAttribute("info", p);
- return mapping.findForward(StrutsConstant.VIEW_SUCCESS);
- }
-
-
-
-
-
-
-
-
-
- public ActionForward audit(ActionMapping mapping, ActionForm form,
- HttpServletRequest req, HttpServletResponse res) throws Exception {
- req.setAttribute("auditFlag", new Boolean(true));
- return this.edit(mapping, form, req, res);
- }
-
-
-
-
-
-
-
-
-
- public ActionForward goSearch(ActionMapping mapping, ActionForm form,
- HttpServletRequest req, HttpServletResponse res) throws Exception {
- return mapping.findForward("search-page");
- }
-
-
-
-
-
-
-
-
-
- @SuppressWarnings("unchecked")
- public ActionForward search(ActionMapping mapping, ActionForm form,
- HttpServletRequest req, HttpServletResponse res) throws Exception {
- Map<String, String> p = new HashMap<String, String>();
- for(Enumeration<String> e = req.getParameterNames();e.hasMoreElements();){
- String key = e.nextElement();
- String value = req.getParameter(key);
- if (value != null && !"".equals(value)) {
- p.put(key, Decoder.customDecode(value));
- }
- }
- int pageNum = RequestUtils.getIntParameter(req, "pageNum", 1);
- boolean isAsc = RequestUtils.getBooleanParameter(req, "isAsc", false);
- String orderField = RequestUtils.getStringParameter(req, "orderField",
- "project0.BEGIN_DATE");
- req.setAttribute("list", projectManager.search(p, pageNum, 20,
- orderField, isAsc));
- req.setAttribute("search", "true");
- return mapping.findForward(StrutsConstant.LIST_SUCCESS);
- }
-
- }
|
返回顶楼 |
|
|
- lijiangt
- 等级:
- 文章: 31
- 积分: 181
|
主要是利用DynaBean,从客户端提交的数据都保存导DynaBean里面,然后再通过beanutils拷贝到实体对象里面去, 现在准备用struts2,正打算实现一个拦截器,将客户端表单提交过来的数据保存到DynaBean对象里面,然后再手动拷贝导实体对象。
|
返回顶楼 |
|
|
- lijiangt
- 等级:
- 文章: 31
- 积分: 181
|
不过感觉楼上几位思路更好,这样最简单。
|
返回顶楼 |
|
|