我正在为项目创建博客系统(学术)。我有一个问题,需要将map
(LinkedHashMap
)传递给jsp
文件。但是浏览器一无所获。这是我的代码:
public void doService (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String path = "localhost:8080/YouBlogger/Posts/";
File dir = new File(path);
File [] files = dir.listFiles();
LinkedHashMap<String, String> map = new LinkedHashMap<String, String>();
Arrays.sort(files, new Comparator<Object>(){
public int compare(Object o1, Object o2) {
return compare( (File)o1, (File)o2);
}
private int compare( File f1, File f2){
long result = f2.lastModified() - f1.lastModified();
if( result > 0 ){
return 1;
} else if( result < 0 ){
return -1;
} else {
return 0;
}
}
});
for(int i=0 ; i < 10 ; i++){
map.put(files[i].getName(), files[i].getPath());
}
request.setAttribute("map", map);
RequestDispatcher dispatcher = request.getRequestDispatcher("/welcome.jsp");
dispatcher.forward(request, response);
}
我100%确定错误在此代码中,就像我硬代码map
一样,JSP显示了其上的数据。这怎么了?可能是path
??
编辑:这是我的JSP代码:
<body>
<div id = "Header">
<h1>You Blogger</h1>
</div>
<div id = "data">
<c:forEach var="country" items="${map}">
${country.key} + ${country.value}
<br/>
</c:forEach>
<form action="new_post" method = "POST">
<input type = "submit" value = "Add A New Post" ></input>
</form>
</div>
</body>
该项目正在Apache Tomcat 8.0上运行,我正在使用Eclipse Luna进行开发。
File
构造函数需要一个真正的途径来访问本地目录。因此,您不应该使用localhost:8080
访问它,而应使用如下
String path="/home/test/apache/webapp/projectname/YouBlogger/Posts/"
如果您不想硬编码路径,则可以使用request.getSession().getServletContext().getRealPath("/")
获取Weberver目录的真实路径
我认为问题在您的代码的第2行和第3行上:
String path = "localhost:8080/YouBlogger/Posts/";
File dir = new File(path);
这将要做的是查看目录c:/localhost:8080/YouBlogger/Posts/
并在此处列出文件,并且由于您的驱动器C上可能不存在此目录:它不会返回。如果要在远程计算机上列出文件,则需要使用某些HTTP客户端或在此处列出现有目录的路径。