이것은 최근 일련의 조잡한 작업을 통해 Entity 클래스에 액세스하는 것과 비슷합니다. 즉, 특정 패키지 내의 모든 엔티티 클래스를 조작 할 수있는 몇 가지 중요한 동작이 있습니다. 이 전략을 Employee 및 Visitor 클래스에 적용 할 수 있어야합니다. 그것은 한마디로 작동 방법
는 :
1) 네임 스페이스 또는 작업 이름 작성해야하는 클래스의 이름 중 하나에 지정해야합니다.
2) struts2s 준비 가능 인터페이스를 사용하여 모델을 작성하십시오. (1 단계에서 결정한 클래스를 반대로 생성하십시오.) 2)에서 정의한 객체를 반환하는 모델 구동 인터페이스를 사용하십시오. 객체가 스택의 맨 위에 있고 단순히 "name"이라고 말할 수 있습니다. 1 단계에서 결정한 클래스의 이름 속성이라는 것을 알고 있어야합니다.이 단계는 피할 수 있지만 꽤 좋지는 않습니다.
위의 세 단계를 수행하는 데는 작은 결함이 있습니다. 사용자 정의 스택 인 "staticParams-prepare-params"스택이 필요합니다.
먼저 예를 들어 다음이 작업을하기 위해 그 스택의 정의는, 당신은 질문이 있으면 알려 주시기 바랍니다 :
<package name="staticParams-prepare-parms" extends="struts-default">
<result-types>
<result-type name="kjson" default="true" class="com.quaternion.demo.result.Kjson"/>
</result-types>
<interceptors>
<interceptor-stack name="staticParamsPrepareParamsStack">
<interceptor-ref name="exception"/>
<interceptor-ref name="alias"/>
<interceptor-ref name="i18n"/>
<interceptor-ref name="checkbox"/>
<interceptor-ref name="multiselect"/>
<interceptor-ref name="staticParams"/>
<interceptor-ref name="actionMappingParams"/>
<interceptor-ref name="servletConfig"/>
<interceptor-ref name="prepare"/>
<interceptor-ref name="chain"/>
<interceptor-ref name="modelDriven"/>
<interceptor-ref name="fileUpload"/>
<interceptor-ref name="staticParams"/>
<interceptor-ref name="actionMappingParams"/>
<interceptor-ref name="params">
<param name="excludeParams">dojo\..*,^struts\..*,^session\..*,^request\..*,^application\..*,^servlet(Request|Response)\..*,parameters\...*</param>
</interceptor-ref>
<interceptor-ref name="conversionError"/>
<interceptor-ref name="validation">
<param name="excludeMethods">input,back,cancel,browse</param>
</interceptor-ref>
<interceptor-ref name="workflow">
<param name="excludeMethods">input,back,cancel,browse</param>
</interceptor-ref>
</interceptor-stack>
</interceptors>
<default-interceptor-ref name="staticParamsPrepareParamsStack"/>
</package>
: 여기
package com.quaternion.demo.action.crud;
import com.quaternion.demo.orm.ActionValidateable;
import com.quaternion.demo.service.CrudService;
import com.quaternion.demo.util.ActionUtils;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import com.opensymphony.xwork2.Preparable;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
// Adds a new record to the database
@ParentPackage("staticParams-prepare-parms")
@Namespace("/crud/{entityName}")
@Result(type = "kjson") //TODO: could rid of this line by setting the result as the default for the package
public class AddAction extends ActionSupport implements Preparable, ModelDriven {
private static final Logger log = Logger.getLogger(AddAction.class.getName());
@Autowired
private CrudService crudService;
private String entityName;
private Object entityModel;
private Map jsonModel = new HashMap(); //for output, return the newly created object
private Class clazz;
@Override
public String execute() throws ClassNotFoundException, InstantiationException, IllegalAccessException {
log.log(Level.INFO, "In execute entityName is set with {0}", entityName);
//If an id is passed in it will merge the object with that id, null will be used for unset attributes
String status = SUCCESS;
boolean error = false;
Object entity = null;
try {
entity = crudService.create(clazz, entityModel);
} catch (Exception e) {
error = true;
status = ERROR;
jsonModel.put("message", e.getMessage());
}
if (error == false) {
jsonModel.put("entity", entity);
}
jsonModel.put("status", status);
return SUCCESS;
}
public Object getEntityModel() {
return entityModel;
}
public void setEntityModel(Object entityModel) {
this.entityModel = entityModel;
}
public Object getJsonModel() {
return jsonModel;
}
@Override
public Object getModel() {
return this.entityModel;
}
@Override
public void prepare() throws Exception {
log.log(Level.INFO, "In prepare entityName is set with {0}", entityName);
clazz = ActionUtils.initClazz(entityName);
entityModel = clazz.newInstance();
}
public String getEntityName() {
return entityName;
}
public void setEntityName(String entityName) {
this.entityName = entityName;
}
//TODO: validation would be a good idea can't implement in this class need to delegate
//if entity implements a validate method, this validate should
//call that validate
@Override
public void validate(){
if (entityModel instanceof ActionValidateable){
((ActionValidateable)entityModel).validate(this);
}
}
}
스택에 대한 정의입니다
kjson 결과 유형이 궁금 할 수 있습니다. 몇 가지 다른 작업에서 struts2-json 플러그인으로 인해 어려움을 겪었습니다. 일반 페이징 및 읽기 작업을 만들었습니다. "flexjson"은 기본적으로 콜렉션을 직렬화하지 않으므로 지연로드 문제를 방지합니다 (컬렉션이로드되지 않은 경우에도 이러한 간단한 서비스의 경우 항상 그렇습니다). 그래서 kjson은 flexjson을 사용하여 json을 리턴하는 결과 유형.
[유형 변환] (http://struts.apache.org/release/2.0.x/docs/type-conversion.html) 문서를 참조하십시오. –