今天遇到一个情况:render到两个模板页面,但数据处理,setAttr的内容都相同,本来没有两个模板页面的时候,是直接写到controller进行setAttr的,可是想复用这个方法,那就在一个controller调用另一个controller?(重定向的话好像也不符合要求)
然后想了个错误的方法:
//错误的例子:
public class RepertoryController extends Controller {
//报表
public void index(){
//把controller传过去service层,在service进行setAttr
StayService.me.indexServer(this);
render("/repertory.html");
}
}
public class StaySteelController extends Controller {
public void index() {
StayService.me.indexServer(this);
render("/staySteel.html");
}
}
//封装index缓存线程方法
public void indexServer(Controller controller){
Map<String, Object> cacheMap = CacheKit.get("diskcache", "stock");
if (cacheMap == null) {
cacheMap = new HashMap<>();
List<Stock> stockList = StayService.me.getAllStock(null);
cacheMap.put("stockList", stockList);
CacheKit.put("diskcache", "stock", cacheMap);
controller.setAttr("cacheMap", cacheMap);
logger.info("第一次启动 缓存");
CacheKit.put("runThread", "runThread", "runThread");
} else {
controller.setAttr("cacheMap", cacheMap);
// 5秒内访问,不进行刷新
String cacheMapThread = CacheKit.get("runThread", "runThread");
if (cacheMapThread == null) {
getAllStockByThread();
CacheKit.put("runThread", "runThread", "runThread");
logger.info("启动 缓存刷新");
}
}
}然而这种方式,虽然能实现需求,但是在“jfinal俱乐部”老大哥指出了种方式的问题:


改成这样了:
public class StaySteelController extends Controller {
public void index() {
Ret ret = StayService.me.indexServer();
setAttr("cacheMap", ret.get("cacheMap"));
render("/staySteel.html");
}
}
public class RepertoryController extends Controller {
//报表
public void index(){
Ret ret = StayService.me.indexServer();
setAttr("cacheMap", ret.get("cacheMap"));
render("/repertory.html");
}
}
//返回Ret index缓存线程方法
public Ret indexServer(){
Ret ret = new Ret();
Map<String, Object> cacheMap = CacheKit.get("diskcache", "stock");
if (cacheMap == null) {
cacheMap = new HashMap<>();
List<Stock> stockList = StayService.me.getAllStock(null);
cacheMap.put("stockList", stockList);
CacheKit.put("diskcache", "stock", cacheMap);
ret.set("cacheMap", cacheMap);
//controller.setAttr("cacheMap", cacheMap);
logger.info("第一次启动 缓存");
CacheKit.put("runThread", "runThread", "runThread");
} else {
ret.set("cacheMap", cacheMap);
//controller.setAttr("cacheMap", cacheMap);
// 5秒内访问,不进行刷新
String cacheMapThread = CacheKit.get("runThread", "runThread");
if (cacheMapThread == null) {
getAllStockByThread();
CacheKit.put("runThread", "runThread", "runThread");
logger.info("启动 缓存刷新");
}
}
return ret;
}请指点。。。。
还有一个很重要的点,将 controller 传入 service 层,破坏了封装性, controller 调用方需要知道 service 层中传了什么值给 controller