摘要:
上一篇讲了idea创建springboot项目,并打包部署到tomcat中,接下来将会继续上次sprintboot项目来调整框架,对前端的整合。(上一篇链接:http://blog.csdn.net/u010775025/article/details/79173526)
一、在application.properties中定义好访问jsp文件的配置
spring.mvc.view.prefix:表示访问jsp的路径前加前缀
spring.mvc.view.suffix:表示访问jsp的路径前加后缀
#jsp page
#new springboot version
spring.mvc.view.prefix=/WEB-INF/jsp/
spring.mvc.view.suffix=.jsp
二、pox.xml中添加jar包依赖
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
<scope>provided</scope>
</dependency>
三、修改后端注解
将@RestController修改为@Controller
package com.jz.springbootdemo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.support.SpringBootServletInitializer;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Date;
import java.util.Map;
@Controller
//@RestController注解相当于@ResponseBody + @Controller合在一起的作用。本来应该到success.jsp页面的,则其显示success.
//@RestController
@SpringBootApplication
public class SpringbootdemoApplication extends SpringBootServletInitializer {
@RequestMapping(value="/hello")
public String hello(){
return "hello word!";
}
@RequestMapping(value="/mqttclient")
public String mqttclient(){
return "mqttclient";
}
@RequestMapping(value="/mqtt")
public String mqtt(){
return "mqtt";
}
public static void main(String[] args) {
SpringApplication.run(SpringbootdemoApplication.class, args);
}
@RequestMapping(value = {"/", "/index"})
public String index(Map<String, Object> model) {
// 直接返回字符串,框架默认会去 spring.view.prefix 目录下的 (index拼接spring.view.suffix)页面
// 本例为 /WEB-INF/jsp/index.jsp
model.put("time", new Date());
model.put("message", "hello");
return "index";
}
}
@RestController和@Controller的区别如下:
@RestController注解相当于@ResponseBody + @Controller合在一起的作用。
1)如果只是使用@RestController注解Controller,则Controller中的方法无法返回jsp页面,配置的视图解析器 InternalResourceViewResolver不起作用,返回的内容就是Return 里的内容。
例如:本来应该到success.jsp页面的,则其显示success.
2)如果需要返回到指定页面,则需要用 @Controller配合视图解析器InternalResourceViewResolver才行。
3)如果需要返回JSON,XML或自定义mediaType内容到页面,则需要在对应的方法上加上@ResponseBody注解
四、将jsp放在webapp/web-inf/jsp路径下,将js,css,image等文件放在resources/static路径下,如下图所示
然后编译idea,运行tomcat,得到如下图所示,访问成功
代码地址:https://github.com/zhangai1989/sprintboot.git