Springboot中使用jsp的设置和问题
jsp的基本使用
-
先在main下创建webapp->WEB-INF,在里面创建jsp页面:
-
在pom.xml文件中的dependencies标签内加入以下依赖
<!--用于编译jsp--> <dependency> <groupId>org.apache.tomcat.embed</groupId> <artifactId>tomcat-embed-jasper</artifactId> <scope>provided</scope> </dependency> <!-- servlet依赖 --> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <scope>provided</scope><!--只参与编译测试,不参与打包,避免冲突--> </dependency> <!-- jstl依赖 --> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> </dependency>
-
在yml中加入下面的配置
spring: mvc: view: #Spring boot视图配置 prefix: /WEB-INF/ suffix: .jsp # static-path-pattern: /static/** #静态文件访问配置 类路径下;例:/static/hello.html 或 /static/login.css # 默认值为 classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/
-
通过以上配置,再写controller来请求jsp页面,只会通过controller来请求jsp页面,直接访问的不会
@Controller public class helloController { @RequestMapping("/main") public String main() { return "main"; } @RequestMapping("index") public String index() { return "mmm/index"; } }
关于使用jsp页面打成jar包启动访问不了的问题
-
要在pom文件中build标签进行以下配置
<resources> <!-- 打包时将jsp文件拷贝到META-INF目录下 --> <resource> <!-- 指定resources插件处理哪个目录下的资源文件 --> <directory>src/main/webapp</directory> <!--这里必须是META-INF/resources--> <targetPath>META-INF/resources</targetPath> <includes> <include>**/**</include> </includes> <filtering>false</filtering> </resource> </resources>
-
在pom文件插件中,将maven插件修改版本,高版本不兼容
<plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <version>1.4.2.RELEASE</version><!--maven打包插件,版本高了不兼容,所以用这个--> <configuration> <!--启动类--> <mainClass>com.wu.supermarket.SupermarketApplication</mainClass> </configuration> </plugin>
修改后打包成jar时就会将jsp一起打包进jar