springboot2.0学习笔记

经过对springboot的多日学习,其中遇到很多问题,现总结出来以备后查。

1、SpringBoot主启动类所能扫描到的范围

      SpringBoot主启动类默认只会扫描自己所在的包及其子包下面,例如主启动类包在com.meander.boot下面,而自定义的LoginController类放在了com.meander.web.controller中,LoginController是无法访问的,解决办法:可以将@SpringBootApplication指定扫描包@SpringBootApplication(scanBasePackages = "com.meander.web")

如需扫描多个包,可以采用如下方式@SpringBootApplication(scanBasePackages = {"com.meander.sys.**.*","com.meander.web"})

package com.meander.boot;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication

public class StartMeanderWebApplication {
    public static void main(String[] args) {
        SpringApplication.run(StartMeanderWebApplication.class, args);
    }
}

2、使用intelliJ idea开发工具,通过maven多模块构建springboot web工程:

  如何使用idea创建maven多模块此处省略...

 主要讲讲其中web子模块:

  2.1 首先在maven父pom.xml文件中添加相关依赖:

pom.xml:
<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-web</artifactId>
</dependency>

<!--使用jasper解析jsp -->
<dependency>
   <groupId>org.apache.tomcat.embed</groupId>
   <artifactId>tomcat-embed-jasper</artifactId>
   <scope>provided</scope>
</dependency>
<!-- jstl标签库 -->
<dependency>
   <groupId>javax.servlet</groupId>
   <artifactId>jstl</artifactId>
</dependency>

2.2 配置resources/application.properties

spring.mvc.view.prefix=/WEB-INF/pages/
spring.mvc.view.suffix=.jsp

2.3 编写的FrontController:
import org.springframework.stereotype.Controller;
@Controller
public class FrontController {
    @RequestMapping("/toHome")
    public String toHome() {
        System.out.println("前置控制器");
        return "front/home";
    }

2.4 编写简单的home.jsp

<%@ page language="java" contentType="text/html;charset=UTF-8" isELIgnored="false" %>
<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
  <h1>Welcome to spring boot world!</h1>
</body>
</html>

maven多模块项目大体结构如下:

执行如下启动类

package com.meander.boot;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication(scanBasePackages = "com.meander")

public class StartMeanderWebApplication {
    public static void main(String[] args) {
        SpringApplication.run(StartMeanderWebApplication.class, args);
    }
}

打开浏览器访问http://127.0.0.1:8080/toHome报404,如图:

        尝试如果把web子模块src/main/webapp目录放到工程meander-boot目录下,jsp就能访问到。这是因为idea默认路径是工程的路径而不是模块的路径 所以导致多模块无法定位到/WEB-INF/pages/index.jsp,而独立的模块工程路径就是模块路径  故可以定位,解决办法如下下图,点击idea的“Edit Configurations”,弹出的界面,指定工作路径working directory为模块的即可,或手工选择web模块路径(meander-web)

猜你喜欢

转载自blog.csdn.net/kongtong2004/article/details/83857482