代码重构,代码优化

public class BaseAction<T> extends ActionSupport implements ModelDriven<T> {
	
	//分页数据显示

		protected int page; //当前页
		protected int rows;// 显示条数
		public void setPage(int page) {
			this.page = page;
		}
		public void setRows(int rows) {
			this.rows = rows;
		}

	protected T model;// new User(); //子类 同级用

	@Override
	public T getModel() {
		
		return model;
	}
	
	public  BaseAction(){
	/*	//子类实例创建时,自动调用父类无参构造函数
		//UserAction extends BaseAction<User>  
		//UserAction userAction = new UserAction();//@Controller,<bean id="" class=""/> //实例创建方式
		//this == userAction//谁调用this指向谁
		//this.getClass().getGenericSuperclass() == BaseAction<User>.class获取父类 class对象,带泛型
		
		ParameterizedType parameterizedType = (ParameterizedType) this.getClass().getGenericSuperclass();//拿到父类class对象
		//
		//parameterizedType.getActualTypeArguments()  //[User.class]数组内放实体类class对象 ,获取父类泛型,参数可能有多个,返回数组
		//
		Type[] actualTypeArguments = parameterizedType.getActualTypeArguments(); 
		//actualTypeArguments[0]==User.calss;
		Class<T> entityClass=(Class<T>) actualTypeArguments[0];//转换成Class对象
		try {
			//entityClass.newInstance();实例化对象== new User
			 model = entityClass.newInstance();//是实例化对象  model
			
			
		} catch (InstantiationException | IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		*/
		//获取父类class对象,带参数
		ParameterizedType parameterizedType=(ParameterizedType) this.getClass().getGenericSuperclass();
		//获取泛型
		Type[] actualTypeArguments = parameterizedType.getActualTypeArguments();
		
		//转换成class对象
		Class<T>entityClass=(Class<T>) actualTypeArguments[0];
		try {
			//实例化对象
			model=entityClass.newInstance();
			
		} catch (InstantiationException | IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	
	public void page2Json(Page<T>page,String[]excludes) {//发生变动的参数 ,当参数传过来
		//将返回的java数据用map集合封装
				Map<String,Object>map=new HashMap<>();
				map.put("total", page.getNumberOfElements());//总数据数
				map.put("rows", page.getContent());//当前数据集合

				//将返回的分页数据转换成json格式
					//json-lib:将java数据转换成json数据
					//jsonObject:将java数据转换成json对象
					//jsonArray:将java数据转换成jeon数组
					//jsonConfig:将数据中不必要的属性排除 
				JsonConfig jsonConfig=new JsonConfig();
				//排除不必要的属性加载  ,解决懒加载  nosession
				jsonConfig.setExcludes(excludes);
				
				JSONObject jsonObject=JSONObject.fromObject(map,jsonConfig);//将jsonConfig传进去 ,转换json 时忽略
				String json = jsonObject.toString();
				
				ServletActionContext.getResponse().setContentType("text/json;charset=UTF-8");
				try {
					ServletActionContext.getResponse().getWriter().print(json);
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
	
	}

web层Action继承使用

Page<Area>page =areaService.pageQuery(spec, pageable);
		String[]excludes={"subareas"};
		this.page2Json(page, excludes);
		return null;

猜你喜欢

转载自blog.csdn.net/l1046060465/article/details/81105608