RootController 继承 BasicController 在 index 方法中 确认restful接口;
POST---save保存、DELETE---delete删除、PUT----update更新、GET----show获取数据;
public void index() {
String method = getRequest().getMethod();
if (method.equals("POST")) {
save();
return;
} else if (method.equals("DELETE")) {
delete();
return;
} else if (method.equals("PUT")) {
update();
return;
} else if (method.equals("GET")) {
show();
return;
}
}
// JFinalV3中
com.jfinal.config.BasicController 继承自 jfinal的 Controller
public abstract class BasicController extends Controller {
protected static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
public BasicController() {
}
protected void renderXml(String view) {
this.render(new FreeMarkerXMLRender(view));
}
protected void renderError(String error) {
this.renderJson(AjaxMessage.error(error));
}
protected void renderFailure(String failure) {
this.renderJson(AjaxMessage.failure(failure));
}
protected void renderSuccess(String message) {
this.renderJson(AjaxMessage.ok(message));
}
protected void renderSuccess() {
this.renderJson(AjaxMessage.ok());
}
protected void renderError(String error, Exception e) {
this.renderJson(AjaxMessage.error(error, e));
}
protected String renderTpl(String view) {
Enumeration attrs = this.getAttrNames();
HashMap root = Maps.newHashMap();
while(attrs.hasMoreElements()) {
String attrName = (String)attrs.nextElement();
root.put(attrName, this.getAttr(attrName));
}
return FreemarkerKit.processString(view, root);
}
protected void todo() {
this.renderJson(AjaxMessage.developing());
}
}
配置文件AppConfig 继承自 JFinalConfig
com.jfinal.initalizer.AppConfig
public class AppConfig extends JFinalConfig {
public static final String APPLICATION_PROP = "application.conf";
private Routes routes;
private Properties properties;
private static final String MODEL_PACKAGE = "app.models";
private static final String CONTROLLER_PACKAGE = "app.controllers";
private static final String INTERCEPTORS_PACKAGE = "app.interceptors";
private static final String BASE_VIEW_PATH = "/WEB-INF/views/";
private static final String DEFAULT_DOMAIN = "http://127.0.0.1:8080/";
private static String view_path;
private static String domain;
public AppConfig() {
}
public static String getBaseViewPath() {
return view_path;
}
public static String getDomain() {
return domain;
}
public void configConstant(Constants constants) {
this.properties = this.loadPropertyFile("application.conf");
constants.setDevMode(this.getPropertyToBoolean("dev.mode", false).booleanValue());
constants.setLoggerFactory(new LogbackLoggerFactory());
view_path = this.getProperty("view.path", "/WEB-INF/views/");
constants.setBaseViewPath(view_path);
domain = this.getProperty("domain", "http://127.0.0.1:8080/");
String view_type = this.getProperty("view.type", "free_marker");
ViewType viewType = ViewType.valueOf(view_type.toUpperCase());
constants.setViewType(viewType);
if(viewType == ViewType.FREE_MARKER) {
Configuration view_404 = FreeMarkerRender.getConfiguration();
view_404.setSharedVariable("block", new BlockDirective());
view_404.setSharedVariable("extends", new ExtendsDirective());
view_404.setSharedVariable("override", new OverrideDirective());
view_404.setSharedVariable("super", new SuperDirective());
view_404.setSharedVariable("prettyTime", new PrettyTimeDirective());
}
String view_4041 = this.getProperty("view.404");
if(!Strings.isNullOrEmpty(view_4041)) {
constants.setError404View(view_4041);
}
String view_500 = this.getProperty("view.500");
if(!Strings.isNullOrEmpty(view_500)) {
constants.setError500View(view_500);
}
try {
int e = this.getPropertyToInt("thread.pool.size", Integer.valueOf(0)).intValue();
if(e > 0) {
ThreadPool.setPool(Executors.newFixedThreadPool(e));
}
} catch (Exception var7) {
throw new ReflectException("thread pool size must be a number");
}
}
public void configRoute(Routes routes) {
this.routes = routes;
routes.add(new AutoBindRoutes("app.controllers"));
}
public void configPlugin(Plugins plugins) {
String db_url = this.getProperty("db.url");
if(!Strings.isNullOrEmpty(db_url)) {
DruidPlugin db1_url = new DruidPlugin(db_url, this.getProperty("db.username"), this.getProperty("db.password"));
db1_url.addFilter(new StatFilter());
WallFilter mongo_url = new WallFilter();
mongo_url.setDbType("mysql");
db1_url.addFilter(mongo_url);
plugins.add(db1_url);
AutoTableBindPlugin redis_host = new AutoTableBindPlugin(db1_url, SimpleNameStyles.LOWER_UNDERLINE, this.getProperty("db.models", "app.models"));
redis_host.setDialect(new MysqlDialect());
redis_host.setShowSql(this.getPropertyToBoolean("dev.mode", false).booleanValue());
plugins.add(redis_host);
if(this.getPropertyToBoolean("db.sqlinxml", false).booleanValue()) {
plugins.add(new SqlInXmlPlugin());
}
}
String db1_url1 = this.getProperty("db1.url");
if(!Strings.isNullOrEmpty(db1_url1)) {
DruidPlugin mongo_url1 = new DruidPlugin(db1_url1, this.getProperty("db1.username"), this.getProperty("db1.password"));
mongo_url1.addFilter(new StatFilter());
WallFilter redis_host1 = new WallFilter();
redis_host1.setDbType("mysql");
mongo_url1.addFilter(redis_host1);
plugins.add(mongo_url1);
SlaveAutoTableBindPlugin log_server = new SlaveAutoTableBindPlugin(mongo_url1, SimpleNameStyles.LOWER_UNDERLINE, this.getProperty("db1.models", "app.models"));
log_server.setDialect(new MysqlDialect());
log_server.setShowSql(this.getPropertyToBoolean("dev.mode", false).booleanValue());
plugins.add(log_server);
if(this.getPropertyToBoolean("db.sqlinxml", false).booleanValue()) {
plugins.add(new SqlInXmlPlugin());
}
}
if(this.getPropertyToBoolean("security", false).booleanValue()) {
plugins.add(new ShiroPlugin(this.routes));
}
if(this.getPropertyToBoolean("cache", false).booleanValue()) {
plugins.add(new EhCachePlugin());
}
if(this.getPropertyToBoolean("job", false).booleanValue()) {
plugins.add(new QuartzPlugin(this.properties));
}
String mongo_url2 = this.getProperty("mongo.url");
String redis_host2;
int log_server1;
if(!Strings.isNullOrEmpty(mongo_url2)) {
redis_host2 = this.getProperty("mongo.host", "127.0.0.1");
if(!Strings.isNullOrEmpty(redis_host2) || !Strings.isNullOrEmpty(mongo_url2)) {
log_server1 = this.getPropertyToInt("mongo.port", Integer.valueOf(27017)).intValue();
String alp = this.getProperty("mongo.db", "test");
boolean moriph = this.getPropertyToBoolean("mongo.moriph", false).booleanValue();
MongodbPlugin mongodb = new MongodbPlugin(redis_host2, log_server1, alp, moriph);
plugins.add(mongodb);
}
}
redis_host2 = this.getProperty("redis.host", "");
if(!Strings.isNullOrEmpty(redis_host2)) {
log_server1 = this.getPropertyToInt("redis.port", Integer.valueOf(6379)).intValue();
JedisPlugin alp1 = new JedisPlugin(redis_host2, log_server1, 2000);
plugins.add(alp1);
}
String log_server2 = this.getProperty("log.server", "");
if(!Strings.isNullOrEmpty(log_server2)) {
AkkaLogPlugin alp2 = new AkkaLogPlugin(log_server2);
plugins.add(alp2);
}
}
public void configInterceptor(Interceptors interceptors) {
if(this.getPropertyToBoolean("dev.mode", false).booleanValue() && this.getPropertyToBoolean("db.sqlinxml", false).booleanValue()) {
interceptors.add(new SqlInXmlInterceptor());
}
interceptors.add(new ContextInterceptor());
(new AutoOnLoadInterceptor(interceptors, "app.interceptors")).load();
}
public void configHandler(Handlers handlers) {
handlers.add(new SessionHandler());
DruidStatViewHandler dvh = new DruidStatViewHandler("/admin/monitor", new IDruidStatViewAuth() {
public boolean isPermitted(HttpServletRequest request) {
return true;
}
});
handlers.add(dvh);
AddHeaderHandler ahh = new AddHeaderHandler();
if(this.getPropertyToBoolean("allow.origin", false).booleanValue()) {
ahh.addHeader("Access-Control-Allow-Origin", "*");
}
ahh.addHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT, PATCH, OPTIONS");
ahh.addHeader("Access-Control-Allow-Headers", "tf-token,tf-uid,accept, content-type");
handlers.add(ahh);
UrlSkipHandler ush = new UrlSkipHandler(".*[/][A-Za-z0-9]+[.][w][s].*", true);
handlers.add(ush);
}
}
JFinalApplicationInitializer
public class JFinalApplicationInitializer
implements ServletContainerInitializer
{
public void onStartup(Set<Class<?>> classSet, ServletContext ctx)
throws ServletException
{
URL url = Resources.getResource("application.conf");
if (url == null) {
throw new IllegalArgumentException("Parameter of file can not be blank");
}
InputSupplier<InputStream> inputSupplier = Resources.newInputStreamSupplier(url);
try
{
Properties p = new Properties();
p.load((InputStream)inputSupplier.getInput());
boolean security = Boolean.getBoolean(p.getProperty("security", "false"));
if (security)
{
ctx.addListener("org.apache.shiro.web.env.EnvironmentLoaderListener");
ctx.addFilter("ShiroFilter", "org.apache.shiro.web.servlet.ShiroFilter")
.addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), true, new String[] { "/*" });
}
app_name = p.getProperty("app", "");
}
catch (IOException e)
{
String app_name;
throw new IllegalArgumentException("Properties file can not be loading: " + url);
}
String app_name;
FilterRegistration.Dynamic jfinalFilter = ctx.addFilter("jfinal@app", "com.jfinal.core.JFinalFilter");
jfinalFilter.setInitParameter("configClass", "com.jfinal.initalizer.AppConfig");
jfinalFilter.addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), true, new String[] { "/*" });
jfinalFilter.setAsyncSupported(true);
System.out.println("initializer " + app_name + " Application ok!");
}
}
绑定路由:AutoBindRoutes
public class AutoBindRoutes extends Routes
public class AutoBindRoutes
extends Routes
{
private boolean autoScan = true;
private List<Class<? extends Controller>> excludeClasses = Lists.newArrayList();
private boolean includeAllJarsInLib;
private List<String> includeJars = Lists.newArrayList();
protected final Logger logger = Logger.getLogger(getClass());
private String suffix = "Controller";
private final String controller_package;
public AutoBindRoutes(String controller_package)
{
this.controller_package = controller_package;
}
public AutoBindRoutes()
{
this.controller_package = "";
}
public AutoBindRoutes autoScan(boolean autoScan)
{
this.autoScan = autoScan;
return this;
}
public AutoBindRoutes addExcludeClasses(Class<? extends Controller>... clazzes)
{
if (clazzes != null) {
Collections.addAll(this.excludeClasses, clazzes);
}
return this;
}
public AutoBindRoutes addExcludeClasses(List<Class<? extends Controller>> clazzes)
{
this.excludeClasses.addAll(clazzes);
return this;
}
public AutoBindRoutes addJars(String... jars)
{
if (jars != null) {
Collections.addAll(this.includeJars, jars);
}
return this;
}
public void config()
{
ClassSearcher searcher = Strings.isNullOrEmpty(this.controller_package) ? ClassSearcher.of(Controller.class) :
ClassSearcher.of(Controller.class, this.controller_package);
List<Class<? extends Controller>> controllerClasses = searcher
.includeAllJarsInLib(this.includeAllJarsInLib).injars(this.includeJars).search();
for (Class controller : controllerClasses) {
if (!this.excludeClasses.contains(controller))
{
ControllerBind controllerBind = (ControllerBind)controller.getAnnotation(ControllerBind.class);
if (controllerBind == null)
{
if (this.autoScan)
{
add(controllerKey(controller), controller);
this.logger.debug("routes.add(" + controllerKey(controller) + ", " + controller.getName() + ")");
}
}
else if (StringKit.isBlank(controllerBind.viewPath()))
{
add(controllerBind.controllerKey(), controller);
this.logger.debug("routes.add(" + controllerBind.controllerKey() + ", " + controller.getName() + ")");
}
else
{
add(controllerBind.controllerKey(), controller, controllerBind.viewPath());
this.logger.debug("routes.add(" + controllerBind.controllerKey() + ", " + controller + "," +
controllerBind.viewPath() + ")");
}
}
}
}
private String controllerKey(Class<Controller> clazz)
{
Preconditions.checkArgument(clazz.getSimpleName().endsWith(this.suffix),
" does not has a @ControllerBind annotation and it's name is not end with " + this.suffix);
String controllerKey = "/" + StringKit.firstCharToLowerCase(clazz.getSimpleName());
controllerKey = controllerKey.substring(0, controllerKey.indexOf(this.suffix));
return controllerKey;
}
public AutoBindRoutes includeAllJarsInLib(boolean includeAllJarsInLib)
{
this.includeAllJarsInLib = includeAllJarsInLib;
return this;
}
public AutoBindRoutes suffix(String suffix)
{
this.suffix = suffix;
return this;
}
}
Run_Configurations.txt
Run Configurations... / Debug Configurations...
1: Main
project(required) ---> your_project_name
Main class(required) ---> com.jfinal.core.JFinal
2: Argument
Program arguments(optional) ---> WebRoot 80 / 5
VM arguments(optional) ---> -XX:PermSize=64M -XX:MaxPermSize=256M