springboot web应用使用jsp
2017-07-25 本文已影响1322人
二月_春风
直接看demo,加入依赖:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.4.RELEASE</version>
<relativePath/>
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
我们知道使用jsp,一般都将jsp页面放在webapp下的WEB-INF文件夹下,定义controller类,此时不能使用@RestController注解,只能使用@Controller,因为使用@RestController注解返回的只能是json类型的数据。
package com.zhihao.miao;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
@Controller
public class LoginController {
@PostMapping("/login")
public String login(@RequestParam("username")String username,@RequestParam("password")String password){
if("miaozhihao".equals(username)&&"123456".equals(password)){
return "success";
}
return "fail";
}
@GetMapping("/login")
public String loginIndex(Model model){
model.addAttribute("username", "miaozhihao");
return "login";
}
@GetMapping("/admin")
public String admin(Model model){
model.addAttribute("admin", "miaozhihaoer");
return "admin/index";
}
}
配置文件中配置相应的jsp的文件目录及后缀,
spring.mvc.view.prefix=/WEB-INF/jsp/
spring.mvc.view.suffix=.jsp
定义响应的jsp文件,
启动类进行启动,
package com.zhihao.miao;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class,args);
}
}
在main下面建立webapp文件夹,webapp文件夹下建立WEB-INF文件夹,具体的
总结:
- 在springboot里面使用jsp,需要另外加入tomcat-embed-jasper的依赖
- 需要在配置文件中,配置如下两个配置项
spring.mvc.view.prefix=/WEB-INF/jsp/
spring.mvc.view.suffix=.jsp
- 方法的返回值,是jsp的路径加文件名字,最后,不能使用@RestController注解,要使用@Controller。