packageme.ooi.testSpark;import static spark.Spark.*;importjava.io.File;importjava.io.IOException;importjava.util.ArrayList;importjava.util.HashMap;importjava.util.List;importjava.util.Map;importorg.slf4j.Logger;importorg.slf4j.LoggerFactory;importfreemarker.template.Configuration;importfreemarker.template.TemplateExceptionHandler;importspark.ModelAndView;importspark.Session;importspark.template.freemarker.FreeMarkerEngine;/***
一个用户管理的例子
*
Author: jun.zhao
*
Date: 2016年10月24日
*/public classUserMgr {public static final Logger LOG = LoggerFactory.getLogger(HelloSpark.class) ;private static final Configuration FREEMARKER_CFG = newConfiguration() ;public static final String SESSION_USER = "session_user";private UserService userService = newUserService() ;static{
String templateDir= getWebContentDir()+"template";try{if( LOG.isInfoEnabled() ){
LOG.info("模板目录为:"+templateDir) ;
}
FREEMARKER_CFG.setDirectoryForTemplateLoading(newFile(templateDir));
}catch(IOException e) {
e.printStackTrace();
}
FREEMARKER_CFG.setDefaultEncoding("UTF-8");
FREEMARKER_CFG.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
}public voidinit(){
configServer();
configStaticFile();
configFilter();
configRequest();
}//设置服务器的一些参数
public voidconfigServer(){//设置端口//This has to be done before using routes and filters
port(8080) ;//设置线程池
int maxThreads = 1000;int minThreads = 10;int timeOutMillis = 30*1000;
threadPool(maxThreads, minThreads, timeOutMillis);
}public staticString getWebContentDir(){//webcontent下的文件
String root = System.getProperty("user.dir") ;
String webContentDir= root + File.separator + "WebContent" +File.separator ;returnwebContentDir ;
}//静态文件设置
public voidconfigStaticFile(){//测试html等静态资源,这些资源可以直接访问//classpath下文件
staticFiles.location("/publicres") ;//webcontent下的文件
String publicDir = getWebContentDir() + "public"; ;if( LOG.isInfoEnabled() ){
LOG.info("public目录为:"+publicDir) ;
}
staticFiles.externalLocation(publicDir) ;
}//用户权限拦截器
public voidconfigFilter(){//不需要登录的地址
List dontNeedLoginPathList = new ArrayList<>() ;
dontNeedLoginPathList.add("/login") ;
dontNeedLoginPathList.add("/login.html") ;//假设session中有用户,则可以访问所有内容,否则提示登录
before((request, response) ->{if( LOG.isInfoEnabled() ){
LOG.info("拦截器拦截请求:"+request.pathInfo()) ;
}if( !dontNeedLoginPathList.contains(request.pathInfo()) ){
Session session=request.session() ;
User u=session.attribute(SESSION_USER) ;if( u == null){
response.redirect("/login.html") ;//终止请求继续走下去(不终止的话拦截器就没有意义了)
halt() ;
}
}
}) ;
}//所有的流程
public voidconfigRequest(){//异常处理,不处理异常就不知道报了什么异常
exception(RuntimeException.class, (exception, request, response) ->{//...
exception.printStackTrace() ;
halt(500) ;
});
exception(Exception.class, (exception, request, response) ->{//...
exception.printStackTrace() ;
halt(500) ;
});//登录
post("/login", (request, response) ->{if( LOG.isInfoEnabled() ){
LOG.info("进入请求:"+request.pathInfo()) ;
}//这里就用name来验证用户了
String name = request.queryParams("name") ;
User u=userService.getUserByName(name) ;if( u == null){
response.redirect("/login.html") ;
}else{
request.session().attribute(SESSION_USER, u) ;
response.redirect("/user/list");
}return null;
});//登出
get("/logout", (request, response)->{if( LOG.isInfoEnabled() ){
LOG.info("进入请求:"+request.pathInfo()) ;
}
request.session().removeAttribute(SESSION_USER) ;
response.redirect("/login.html") ;return null;
}) ;//用户列表
get("/user/list", (request, response)->{if( LOG.isInfoEnabled() ){
LOG.info("进入请求:"+request.pathInfo()) ;
}
Map data = new HashMap<>() ;
List userList =userService.findUser() ;
data.put("userList", userList) ;return new ModelAndView(data, "user/list.html") ;
},newFreeMarkerEngine(FREEMARKER_CFG)) ;
}
}