gpt4 book ai didi

java - 文件路径给出 NullPointer

转载 作者:行者123 更新时间:2023-12-01 12:14:41 24 4
gpt4 key购买 nike

在我的 JSP 页面上,我需要显示一个列表,其中包含/public 文件夹中当前存在的所有文件。

这是一个带有 spring 和 hibernate 的 j2ee 项目。在我的用于获取包含所有文件的列表的服务类中,我有以下内容:

public class UploadService {

private static List<File> list = new ArrayList<File>();

public static List<File> getFileList() {

File folder = new File("C:\\Users\\Admin\\Documents\\GitHub\\MyApp\\src\\main\\webapp\\resources\\public");
File[] listOfFiles = folder.listFiles();
list.addAll(Arrays.asList(listOfFiles));

return list;
}

但是,当我写下:

File folder = new File(Structure.defaultUrl+"/public/");

我收到一个空指针..

默认Url如下:

public class Structure {

/**
*
*/
public static String defaultUrl = "/MyApp";

在资源处理程序中:

    public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/public/**").addResourceLocations("/resources/public/");
}

奇怪的部分是,在我的主页上:

<a href ="<%=Structure.defaultUrl%>/public/AlgVW2011.pdf">

它确实有效。我现在真的陷入困境,有人知道我做错了什么吗?

编辑:

搜索了一下问题,可能是MvcConfiguration.java中的一些问题。

public class Initializer implements WebApplicationInitializer {

/**
*
* @param servletContext
* @throws ServletException
*/
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
ctx.register(MvcConfiguration.class);
servletContext.addListener(new ContextLoaderListener(ctx));

ctx.setServletContext(servletContext);

Dynamic servlet = servletContext.addServlet("dispatcher", new DispatcherServlet(ctx));
servlet.addMapping("/");
servlet.setLoadOnStartup(1);
}

}

最佳答案

您无法从服务代码中引用 /public/。只有在 Spring 处理程序将映射解析为 /resources/public/ 后,才能从 Servlet 上下文访问该映射。

使用javax.servlet.ServletContext和Spring的ServletContextResource来获取webapp文件夹中的资源。

@Autowired
private ServletContext servletContext;

public static List<File> getFileList() {
Resource resource = new ServletContextResource(servletContext, "/resources/public");
File folder = resource.getFile();
File[] listOfFiles = folder.listFiles();
list.addAll(Arrays.asList(listOfFiles));

return list;
}

关于java - 文件路径给出 NullPointer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27085917/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com