A stray ant can only move by itself

初识springBoot

spring boot 踩坑
创建简单的web 项目,只实现web 页面展示,不涉及业务处理

  1. idea 新建项目,采用 Spring Initializr 创建项目, 选择 web 依赖

  2. 项目创建成功后
    创建展示层目录: src/main/webapp,
    在 webapp下创建目录 WEB-INF ,
    在WEB-INF 下创建 index.jsp 文件

  3. 配置spring boot 启动器

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    @SpringBootApplication
    public class Applicaion extends SpringBootServletInitializer{
    public static main(String args[]){
    SpringApplication.run(Applicaion.class, args);
    }
    //重写configure 方法
    protected SpringApplicationBuilder configure(SpringApplicationBuilder builder){
    return builder.sources(Applicaion.class);
    }
    }
  1. 配置文件设置 : application.properties
    1
    2
    spring.mvc.view.perfix=/WEB-INF/
    spring.mvc.view.suffix=.jsp
  1. 添加jsp 支持, 如果需要使用EL 表达式, 再添加JSTL 支持,打开pom.xml文件
    1
    2
    3
    4
    5
    6
    7
    8
    9
    <dependency><!--  jsp 支持 -->
    <groupId>org.apache.tomcat.embed</groupId>
    <artifactId>tomcat-embed-jasper</artifactId>
    </dependency>

    <dependency> <!-- jstl 支持 -->
    <groupId>javax.servlet</groupId>
    <artifactId>jstl</artifactId>
    </dependency>
  1. 添加一个 Controller , 注意所在的目录

    import org.springframework.web.bind.annotation.RequestMapping;
        import org.springframework.web.bind.annotation.RestController;
        import org.springframework.web.servlet.ModelAndView;
    
        @RestController
        public class LoginController {
    
            @RequestMapping(value ={ "/", "/index"})
            public ModelAndView index(){
                ModelAndView view = new ModelAndView("index");
                return view;
            }
        }
  2. @RestController 与 @Controller 之间的不同
    @RestController 相当于 @RequestMapping 和 @ResponseBody 结合,

    方法返回值为 String  返回单纯的字符串, 方法返回值为 ModelAndView 为一个页面

    @Controller

    方法返回值为 String  返回一个页面, 方法返回值为 ModelAndView 为一个页面, 返回对象需要在方法上添加@ResponseBody注解
  3. @RequestMapping 路径匹配,
    可在类,方法上添加;
    一个方法匹配多个路径 {“/index”, “/login” } ,使用大括号括起来;
    中间用逗号隔开。

支付宝打赏 微信打赏

赞赏是不耍流氓的鼓励