一个简单的Java Spring Web Demo

生成脚手架

https://start.spring.io/

参数如图:

start

功能列表

  • web服务
  • 注解使用
  • 登录
  • 鉴权
  • 多模块
  • 使用了spring的自动装配
  • 拦截器使用

建立子app、common模块

使用idea->file->module

 1# app
 2name:app
 3language:java
 4build system:gradle
 5jdk:sdk17
 6parent:demo
 7
 8# common
 9name:common
10language:java
11build system:gradle
12jdk:sdk17
13parent:demo

创建成功后,根目录src可以删除

创建demo文件

demo01/app/src/main/java/org/example/Main.java

 1package org.example;
 2
 3import org.springframework.boot.SpringApplication;
 4import org.springframework.boot.autoconfigure.SpringBootApplication;
 5
 6@SpringBootApplication
 7public class Main {
 8    public static void main(String[] args) {
 9        SpringApplication.run(Main.class, args);
10    }
11}

demo01/app/src/main/java/org/example/rest/HelloController.java

 1package org.example.rest;
 2
 3import org.example.rest.annotation.LoginRequired;
 4import org.example.utils.Utils;
 5import org.springframework.web.bind.annotation.GetMapping;
 6import org.springframework.web.bind.annotation.RequestMapping;
 7import org.springframework.web.bind.annotation.RestController;
 8
 9@RestController
10@RequestMapping("/api")
11public class HelloController {
12    @GetMapping("/hello")
13    public String helloWorld(){
14        Integer i = Utils.add(1);
15        Integer b = Utils.del(3);
16        return "hello,world~" + i + "-" + b;
17    }
18
19    @GetMapping("/user")
20    @LoginRequired
21    public String user(){
22        return "用户中心,需要登录";
23    }
24}

demo01/app/src/main/java/org/example/rest/annotation/LoginRequired.java

 1package org.example.rest.annotation;
 2
 3
 4import java.lang.annotation.ElementType;
 5import java.lang.annotation.Retention;
 6import java.lang.annotation.RetentionPolicy;
 7import java.lang.annotation.Target;
 8
 9/**
10 * 在需要登录验证的Controller的方法上使用此注解
11 */
12@Target({ElementType.METHOD})// 可用在方法名上
13@Retention(RetentionPolicy.RUNTIME)// 运行时有效
14public @interface LoginRequired {
15}

demo01/app/src/main/java/org/example/configs/WebConfig.java

 1package org.example.configs;
 2
 3import org.example.interceptor.AuthorityInterceptor;
 4import org.example.interceptor.LoginInterceptor;
 5import org.springframework.beans.factory.annotation.Autowired;
 6import org.springframework.context.annotation.Configuration;
 7import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
 8import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
 9
10/**
11 * 和springmvc的webmvc拦截配置一样
12 * @author BIANP
13 */
14@Configuration
15public class WebConfig implements WebMvcConfigurer {
16    @Autowired
17    private LoginInterceptor loginInterceptor;
18    @Autowired
19    private AuthorityInterceptor authorityInterceptor;
20    @Override
21    public void addInterceptors(InterceptorRegistry registry) {
22        // 拦截所有请求,通过判断是否有 @LoginRequired 注解 决定是否需要登录
23        registry.addInterceptor(loginInterceptor).addPathPatterns("/**");
24        registry.addInterceptor(authorityInterceptor).addPathPatterns("/**");
25    }
26
27}

demo01/app/src/main/java/org/example/interceptor/AuthorityInterceptor.java

 1package org.example.interceptor;
 2
 3import jakarta.servlet.http.HttpServletRequest;
 4import jakarta.servlet.http.HttpServletResponse;
 5import org.example.rest.annotation.LoginRequired;
 6import org.springframework.stereotype.Service;
 7import org.springframework.web.method.HandlerMethod;
 8import org.springframework.web.servlet.HandlerInterceptor;
 9
10import java.lang.reflect.Method;
11
12@Service
13public class AuthorityInterceptor implements HandlerInterceptor {
14    @Override
15    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
16        // 如果不是映射到方法直接通过
17        if (!(handler instanceof HandlerMethod)) {
18            return true;
19        }
20        // ①:START 方法注解级拦截器
21        HandlerMethod handlerMethod = (HandlerMethod) handler;
22        Method method = handlerMethod.getMethod();
23        // 判断接口是否需要登录
24        LoginRequired methodAnnotation = method.getAnnotation(LoginRequired.class);
25        // 有 @LoginRequired 注解,需要认证
26        if (methodAnnotation != null) {
27            // 这写你拦截需要干的事儿,比如取缓存,SESSION,权限判断等
28            System.out.println("AuthorityInterceptor====================================");
29            return true;
30        }
31        return true;
32    }
33}

demo01/app/src/main/java/org/example/interceptor/Const.java

 1package org.example.interceptor;
 2
 3/**
 4 * @author     BianP
 5 * @explain 常量类
 6 */
 7public class Const {
 8    // 不验证URL anon:不验证/authc:受控制的
 9    public static final String NO_INTERCEPTOR_PATH =".*/((.css)|(.js)|(images)|(login)|(anon)).*";
10}

demo01/app/src/main/java/org/example/interceptor/LoginInterceptor.java

 1package org.example.interceptor;
 2
 3
 4import jakarta.servlet.http.HttpServletRequest;
 5import jakarta.servlet.http.HttpServletResponse;
 6import org.springframework.stereotype.Service;
 7import org.springframework.web.servlet.HandlerInterceptor;
 8
 9@Service
10public class LoginInterceptor implements HandlerInterceptor {
11    /**
12     * 在请求处理之前进行调用(Controller方法调用之前)
13     * 基于URL实现的拦截器
14     * @param request
15     * @param response
16     * @param handler
17     * @return
18     * @throws Exception
19     */
20    @Override
21    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
22        String path = request.getServletPath();
23        if (path.matches(Const.NO_INTERCEPTOR_PATH)) {
24            //不需要的拦截直接过
25        } else {
26            // 这写你拦截需要干的事儿,比如取缓存,SESSION,权限判断等
27            System.out.println("LoginInterceptor====================================");
28        }
29        return true;
30    }
31}

demo01/common/src/main/java/org/example/utils/Utils.java

 1package org.example.utils;
 2
 3public class Utils {
 4    public static Integer add(Integer a) {
 5        return a + a;
 6    }
 7
 8    public static Integer del(Integer a) {
 9        return a  - 1;
10    }
11}

项目地址

https://github.com/java-sig/demo

发布日期:2023-05-30 14:32 字数:487 用时 3分钟
tags:Java Spring