在上篇文章我们看到了用wicket开发的第一个程序。但是有点是非常不好的,就是html页面跟Java在同一目录下,这跟我们平时开发,是不同的,如果页面过多,后期维护也是很麻烦的。这篇文章我们就来说下,怎么把html放在webapp下了?
先来看下修改后的项目结构:
看下MyLcator.java这个文件:
package cn.ztz.application;
import java.net.URL;
import org.apache.wicket.core.util.resource.UrlResourceStream;
import org.apache.wicket.core.util.resource.locator.ResourceStreamLocator;
import org.apache.wicket.protocol.http.WebApplication;
import org.apache.wicket.util.resource.IResourceStream;
/**
*
* @author azhong
* 2015-08-19 20:52:47
*/
public class MyLocator extends ResourceStreamLocator {
@Override
public IResourceStream locate(Class<?> clazz, String path) {
String extension = path.substring(path.lastIndexOf(".") + 1);
String clazzName=clazz.getName();
String fileName=clazzName.substring(clazzName.lastIndexOf(".")+1);
URL url;
try{
url=WebApplication.get().getServletContext().getResource("/"+fileName+"."+extension);
if(url!=null){
return new UrlResourceStream(url);
}
}catch(Exception e){
e.printStackTrace();
}
return super.locate(clazz, path);
}
}
HelloWorldApplication.java
package cn.ztz.application;
import org.apache.wicket.Page;
import org.apache.wicket.protocol.http.WebApplication;
/**
* @author azhong
* @version 1.0
* 2015-08-19 20:54:04
*
*/
public class HelloWorldApplication extends WebApplication {
@Override
public Class<? extends Page> getHomePage() {
return HelloWorld.class;
}
//初始化加载路径就可以了
@Override
protected void init() {
getResourceSettings().setResourceStreamLocator(new MyLocator());
}
}
HelloWorld.java
package cn.ztz.application;
import org.apache.wicket.markup.html.WebPage;
import org.apache.wicket.markup.html.basic.Label;
/**
* @author azhong
* @version 1.0
* 2015-08-19 20:53:24
*
*/
public class HelloWorld extends WebPage {
public HelloWorld(){
add(new Label("message","Hello world----wicket"));
}
}
现在大功告成,就是这么简单。
其实还有种方法也能实现这种效果,这里博主就不说了。自我感觉没这种好。