Spring启动项目找不到静态文件

时间:2018-03-16 02:39:49

标签: spring-boot static controller file-exists

最近,当我尝试在静态文件here is my project structure.

中编写内容时遇到问题

当我输入“localhost:8080 / data / user.json”时,我可以获取该文件。但是,当我尝试在索引html中编写内容时,会发生FileNotFound错误。 我的控制器是:

    @Controller
    public class UserController {

        UserService userService = new UserServiceImpl();

        @RequestMapping("/")
        public String getIndex(){
        return "/index.html";
      }

      @RequestMapping(value = "/register", method = RequestMethod.POST)
      @ResponseBody
      public Response<Boolean> register(String user, String password)throws         IOException{
         System.out.println("Get Register");
         System.out.println("user" + "  " + user);
         System.out.println("password" + " " + password);

        return userService.saveUser(user, password);
    }

}

FileTool类:

     public class FileTool {

    public static boolean writeFile(String filePath, String content) throws IOException{
        try {
            File file = new File(filePath);
            FileWriter writer = new FileWriter(file);
            PrintWriter printWriter = new PrintWriter(writer);
            printWriter.write(content);
            System.out.println(content);
            printWriter.println();
            writer.close();
            printWriter.close();
            return true;
        }catch (IOException ex){
            ex.printStackTrace();
        }

        return false;
    }
}

我应该如何在util中的工具中编写真实路径。 我写了路径“data / user.json”,错误:

java.io.FileNotFoundException: data/user.json (No such file or directory)
at java.io.FileOutputStream.open0(Native Method)
at java.io.FileOutputStream.open(FileOutputStream.java:270)
at java.io.FileOutputStream.<init>(FileOutputStream.java:213)
at java.io.FileOutputStream.<init>(FileOutputStream.java:162)
at java.io.FileWriter.<init>(FileWriter.java:90)
at com.utag.phase1.util.FileTool.writeFile(FileTool.java:12)
at com.utag.phase1.dao.UserDaoImpl.saveUser(UserDaoImpl.java:20)
at com.utag.phase1.service.Impl.UserServiceImpl.saveUser(UserServiceImpl.java:19)
at com.utag.phase1.controller.UserController.register(UserController.java:41)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:209)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:136)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:102)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:870)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:776)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:991)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:925)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:978)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:881)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:661)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:855)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:109)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:81)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:200)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:496)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:803)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:790)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1459)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)

的index.html:

    <!DOCTYPE html>
    <html>
   <input type="text" id="username" name="username" />
   <input type="password" id="password" name="password"/>
   <input type="button" id="btn" value="login"/>
   <input type="button" id="btn2" value="register"/>
   <script src="http://code.jquery.com/jquery-latest.js"></script>
   <script type="text/javascript">
       $(function () {
           $("#btn").click(function () {
              var user = $('#username').val();
              var password = $('#password').val();
              $.ajax({
                type:"GET",
                url:"/login",
                dataType:"json",
                data : {
                user: user,
                password: password
            },

            success : function (data) {
                if(data.success){
                   alert("Success!");
                }else
                    alert("Error!");
            },
            error : function () {
                alert("Network warning");
            }
        });
    });

        $("#btn2").click(function () {
            var user = $('#username').val();
            var password = $('#password').val();
            $.ajax({
                type:"POST",
                url:"/register",
                dataType:"json",
                data : {
                    user: user,
                    password: password
                },
                success : function (data) {
                    if(data.success){
                        alert("Success!");
                    }else
                        alert("Error!");
                },
                error : function () {
                    alert("Network warning");
                }
            });
        });
}
);

1 个答案:

答案 0 :(得分:0)

如果您想从资源中读取数据,请输入正确的代码

    //Get file from resources folder
    ClassLoader classLoader = getClass().getClassLoader();
    File file = new File(classLoader.getResource(fileName).getFile());

或者你可以参考这个链接

How do I load a file from resource folder?