Controller里可以用构造方法吗?


JFinal项目启动后,所有的Controller都会被实例化吗?

可不可以在Controller里面使用构造方法呢?比如下面的这个:

public ClientController(){

Client c = new Client();

setSessionAttr("client", c);

}


评论区

java180

2016-09-22 16:49

我尝试了一下,是有出现报错:
[ERROR]-[Thread: http-bio-8080-exec-5]-[com.jfinal.core.ActionHandler.handle()]: /SocketClient/findReader?reader=123&passwd=
java.lang.NullPointerException
at com.jfinal.core.Controller.setSessionAttr(Controller.java:330)
at SocketClient.ClientController.(ClientController.java:11)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at java.lang.Class.newInstance(Unknown Source)
at com.jfinal.core.ActionHandler.handle(ActionHandler.java:68)
at com.jfinal.core.JFinalFilter.doFilter(JFinalFilter.java:72)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:505)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:169)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:956)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:436)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1078)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:625)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:318)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Unknown Source)

JFinal

2016-09-22 16:53

Controller 中可以创建无参构造方法,但不能调用其 setAttr、setSessionAttr 等方法,因为构造方法被调用时,很多数据没准备好,例如 HttpServletRequest 对象没准备好

构造方法首先会被调用,所以这些对象还没来得及准备

JFinal

2016-09-22 16:53

这类需要都是可以通过拦截器解决的

java180

2016-09-23 16:23

@JFinal 恩,老大这么一说就更明白了,后来我也是想到了拦截器,
Client c = ai.getController().getSessionAttr("client");
if (c == null) {
c = new Client();
System.out.println("rebuilded!");
ai.getController().setSessionAttr("client", c);
}

热门反馈

扫码入社