一:模板类
package com.book.ssh.base.actions;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.Map;
import org.apache.struts2.interceptor.RequestAware;
import org.springframework.context.ApplicationContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
/**
*
* Action 基类,封装了泛型参数get set 方法
* 注入spring applicationContext 对象
*
* @param <T> 参数类
*/
public class BaseActionSupport<T> extends ActionSupport implements ModelDriven<T>,RequestAware{
/**
* 声明的参数类
* <br/><em>不建议名称修改为param
* 可能会跟页面param对象冲突,导致通过struts取值机制冲突</em>
*/
protected T formParam;
/**
* spring 上下文
*/
protected ApplicationContext applicationContext;
protected Map<String, Object> request;
public void setRequest(Map<String, Object> arg0) {
this.request = arg0;
}
protected Map<String, Object> session;
/**
* 构造参数对象
*/
public BaseActionSupport() {
if(formParam==null){
try {
formParam = getParameterizedTypeClass().newInstance();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
private Class<T> getParameterizedTypeClass(){
// 获取泛型类型
Type type = getClass().getGenericSuperclass();
Type[] trueType = ((ParameterizedType) type).getActualTypeArguments();
return (Class<T>) trueType[0];
}
public T getFormParam() {
return formParam;
}
public void setFormParam(T formParam) {
this.formParam = formParam;
}
/**
* 将泛型参数类映射为Struts的默认参数包装对象
*/
@Override
public T getModel() {
return formParam;
}
}
页面回显技术:
* 通过模型驱动,在动作类action中,可以获取到页面中元素的值
方法一
* 通过javabean实例的set()方法,将新的内容set到javabean中,从而放置在页面对应元素中
user.setUsername(newUser.getUsername());
user.setTel(newUser.getTel());
user.setDes(newUser.getDes());
方法二
* 首先将值栈中,旧的javabean的内容,删除掉
* 然后将新的内容压入到值栈中的栈顶
ValueStack valueStack = ServletActionContext.getContext().getValueStack();
valueStack.pop();
valueStack.push(newUser);