【Java】spring boot 创建后 请求404

问题

按照网上教程maven创建spring boot 项目后 新建index.html文件 jquery GET请求 要不就是404要不就是failed

创建:@RequestMapping("/hi")

jquery请求:url: "http://localhost:8888/hi",

【Java】spring boot 创建后 请求404

参考如下:https://blog.csdn.net/webzhuc...

回答

请求页面是需要加入模板引擎的 你请求的是页面 还是restful接口

没看到你的代码,我大胆猜测问题可能出现在步骤3. 测试Spring Boot应用,他的这个demo中出于便利性考虑,main和Ctrl合并到一个类中了,我这里给出分离的写法:

/**

* 这是Spring Boot应用的入口类

*/

@SpringBootApplication

public class DemoApplication{

public static void main(String[] args){

SpringApplication.run(DemoApplication.class, args);

}

}

在该入口类的同级或以下创建一个DemoCtrl类,具体如下:

@Controller

@RequestMapping("/")

public class DemoCtrl{

/**

* web rounter

*/

@RequestMapping("/hi")

public String hello(ModelMap map){

return "index";

}

}

然后在resource下的template目录下创建你的index.html文件,启动项目,应该就可以看到hello spring boot了

更新一下,这里有个点需要注意一下,@RestController和@Controller面向Web的时候的区别。
如果你使用@RestController注解的话你应该使用如下类似操作:

@RequestMapping("hi")

public ModelAndView hello(){

return new ModelAndView("index");//改index.html 文件在template目录下

}

如果使用的是@Controller注解的话,按照第一种方式便可以正确的映射到view了。

再次更新
如果是Spring MVC的话,在没有配置默认的view引擎的时候,需要把view文件写全,如下:

/**

* web rounter

*/

@RequestMapping("/hi")

public String hello(ModelMap map){

return "index.jsp"; // 这里以jsp为例

}

以上是 【Java】spring boot 创建后 请求404 的全部内容, 来源链接: utcz.com/a/88948.html

回到顶部