首页 > 编程语言 >java springboot 2.x 环境搭建

java springboot 2.x 环境搭建

时间:2022-10-28 14:37:54浏览次数:52  
标签:java springboot boot System springframework org println import 搭建


环境:
java version 1.8
Apache Maven 3.2.2 
ide:idea
springboot:2.1.3.RELEASE

创建步骤:
1 file=>new=>mudule...
2 选择 Spring Initializr:module sdk 选择 1.7,其他默认。下一步
3 填写一些包信息,packaging 选择 war,java version 选择 1.7;下一步
4 找到 web 节点,勾选 web 复选框,生成一个 web 项目;(这步很关键,可以生成一个 ServletInitializer 类);下一步
5 选择生成路径,点击 finish,完成一个 springboot 项目创建;

测试:

​http://localhost:8081/res/imgs/s.jpg​

​http://localhost:8081/v/index.html​

​http://localhost:8081/index​

项目结构:
├── main
│   ├── java
│   │   ├── aop
│   │   │   └── BaseInterceptor.java    //拦截器,控制访问权限
│   │   ├── configs
│   │   │   └── WebMvcConfig.java   //web配置,可以配置拦截器、静态资源映射、视图路由映射等
│   │   ├── controller
│   │   │   └── HeloController.java  //控制器
│   │   └── main
│   │       ├── MainApplication.java    //主程序入口
│   │       └── ServletInitializer.java //tomact 部署支持
│   └── resources
│       ├── application.properties  //应用程序配置,可配置域名、端口号等
│       ├── res     //资源目录
│       │   ├── imgs
│       │   │   └── s.jpg 
│       │   └── css
│       ├── static
│       ├── templates
│       └── views   //页面目录
│           ├── error.html
│           └── index.html
└── test

 

pom.xml 文件

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.3.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>my-layui</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>my-layui</name>
<description>Demo project for Spring Boot</description>

<properties>
<java.version>1.8</java.version>
</properties>

<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!--热部署支持-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
<scope>true</scope>
</dependency>
</dependencies>

<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<!--fork : 如果没有该项配置,肯定devtools不会起作用,即应用不会restart -->
<fork>true</fork>
</configuration>
</plugin>
</plugins>
</build>

</project>


application.properties


server.port=8081

BaseInterceptor.java


package aop;

import org.springframework.stereotype.Component;
import org.springframework.util.ResourceUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;

@Component
public class BaseInterceptor implements HandlerInterceptor {
public BaseInterceptor(){
System.out.println("BaseInterceptor 完成");
}

/**
* true=有权限,false=无权访问
* @param request
* @param response
* @param handler
* @return
*/
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
//登录验证
if (request.getRequestURI().startsWith("/admin")) {
response.sendRedirect(request.getContextPath()+"/login"); //跳转到登录页
return false;
}
System.out.println("pre = "+request.getRequestURI());
File path = new File(ResourceUtils.getURL("classpath:").getPath());
if(!path.exists())
path = new File("");
System.out.println("物理路径 = "+path.getAbsolutePath());

return true;
}

@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex){
System.out.println("after = "+request.getRequestURI());
}

}

WebMvcConfig.java


package configs;

import aop.BaseInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
public WebMvcConfig(){
System.out.println("加载 WebMvcConfig");
}
/**
* 基础拦截器
*/
@Resource
private BaseInterceptor baseInterceptor;

/**
* 配置静态访问资源
* @param registry
*/
@Override
public void addInterceptors(InterceptorRegistry registry) {
List<String> staticDirs = Arrays.asList("/views/**", "/res/**");
//告知拦截器:/static/admin/** 与 /static/user/** 不需要拦截 (配置的是 路径)
registry.addInterceptor(baseInterceptor)
.excludePathPatterns(staticDirs);
System.out.println("addInterceptors() 完成");
}
/**
* 添加静态资源文件,外部可以直接访问地址
* @param registry
*/
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
//第一个方法设置访问路径前缀(可以设置多个虚拟目录,映射到同一个物理目录)
//第二个方法设置资源路径
registry.addResourceHandler("/res/**","/r/**","/src/**")
.addResourceLocations("classpath:/res/");
registry.addResourceHandler("/views/**","/v/**","/pages/**")
.addResourceLocations("classpath:/views/");
System.out.println("addResourceHandlers() 完成");
}

/**
* 可以直接指定一些页面路由映射规则
* @param registry
*/
@Override
public void addViewControllers(ViewControllerRegistry registry) {
//第一个方法设置访问路径前缀
//第二个方法设置资源路径
registry.addViewController("/error")
.setViewName("/views/error.html");
registry.addViewController("/index")
.setViewName("/views/index.html");
System.out.println("addViewControllers() 完成");
}
}

HeloController.java


package controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

@RestController
public class HeloController {
@RequestMapping("/")
public String hello() {
System.err.println("HeloController.hello();");
return "hello word!," + new Date();
}
@RequestMapping("/login")
public String login() {
System.err.println("HeloController.login();");
return "需要登录后访问," + new Date();
}
@RequestMapping("/admin")
public String admin() {
System.err.println("HeloController.admin();");
return "管理员操作页," + new Date();
}
}

MainApplication.java


package main;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.ComponentScans;

/**
* springboot 主项目,应用程序入口
*/
@SpringBootApplication
//spring 注入扫描的包,默认只扫面 MainApplication 同级的包
@ComponentScans(value = {@ComponentScan(basePackages = {"aop","configs","controller"})})
public class MainApplication {

public static void main(String[] args) {
System.out.println("springBoot 准备启动...");
SpringApplication.run(MainApplication.class, args);
System.out.println("springBoot 已启动...");
}

}

ServletInitializer.java

package main;

import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;

/**
* //tomcat 启动入口
*/
public class ServletInitializer extends SpringBootServletInitializer {

@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
System.out.println("tomcat 启动入口注册");
return application.sources(MainApplication.class);
}

}

 

标签:java,springboot,boot,System,springframework,org,println,import,搭建
From: https://blog.51cto.com/u_4518216/5804846

相关文章

  • java-字符串拼接几种方法的性能比较
    java-字符串拼接几种方法的性能比较一、测试方法:String.format();MessageFormat.format();StringBuilder();二、测试结果:性能:StringBuilder>MessageFormat>String三......
  • 力扣907(java)-子数组的最小值之和(中等)
    题目:给定一个整数数组arr,找到min(b) 的总和,其中b的范围为arr的每个(连续)子数组。由于答案可能很大,因此返回答案模10^9+7。 示例1:输入:arr=[3,1,2,4]输......
  • java-floyd最短距离算法
    java-floyd最短距离算法publicstaticvoidmain(String[]args){MatrixDGmatrixDG=newMatrixDG();System.out.println("初始化邻接矩阵");matrixDG.print......
  • Java-五种线程池,四种拒绝策略,三类阻塞队列
    Java-五种线程池,四种拒绝策略,三类阻塞队列(常用)三类阻塞队列:   //1有界队列   workQueue=newArrayBlockingQueue<>(5);//基于数组的先进先出(FIFO)队列,支持公......
  • java-并发集合-阻塞队列 LinkedBlockingQueue 演示
    java-并发集合-阻塞队列LinkedBlockingQueue演示packageme.grass.demo.concuronte;importjava.util.Date;importjava.util.concurrent.CountDow......
  • java-并发集合-并发hash表 ConcurrentHashMap 演示
    java-并发集合-并发hash表 ConcurrentHashMap演示packageme.grass.demo.concurrent;importjava.util.Date;importjava.util.concurrent.Concurr......
  • java-并发集合-并发队列 ConcurrentLinkedQueue 演示
    java-并发集合-并发队列ConcurrentLinkedQueue演示目标:模拟5个线程同时并发读取“并发队列”,并使用CountDownLatch类协助计算消费耗时。pack......
  • 使用jvmti dll |so 加密java class jar包
    dll代码 //dllmain.cpp:定义DLL应用程序的入口点。#include"pch.h"#include<iostream>#include<jni_md.h>#include<jni.h>#include<jvmti.h>#include......
  • Java集合
    List和Set的区别:List:有序,按对象进入的顺序保存对象,可重复,允许多个Null元素对象,可以使用Iterator取出所有元素,再逐一遍历,还可以使用get(intindex)获取指定下标的元素......
  • LNMP+LAMP环境搭建
    LNMP+LAMP环境搭建一、LNMP环境1.Linux-介绍操作系统:CentOS7.964位Nginx版本:Nginx1.20.1MySQL版本:MySQL5.7.36(5.5.68-MariaDB)PHP版本:PHP7.0.33......