原创

打通React+SpringBoot项目

编写后端项目

从IDEA或官网生成Spring Boot项目模板,maven文件如下:

<?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 https://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.6.RELEASE</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.cocohub</groupId>
	<artifactId>spring-demo</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>war</packaging>
	<name>spring-demo</name>
	<description>Demo project for Spring Boot</description>
	<properties>
		<java.version>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>compile</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.junit.jupiter</groupId>
			<artifactId>junit-jupiter-api</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.mybatis.spring.boot</groupId>
			<artifactId>mybatis-spring-boot-starter</artifactId>
			<version>2.3.0</version>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-configuration-processor</artifactId>
			<optional>true</optional>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
				<configuration>
					<excludes>
						<exclude>
							<groupId>org.projectlombok</groupId>
							<artifactId>lombok</artifactId>
						</exclude>
					</excludes>
				</configuration>
			</plugin>
		</plugins>
	</build>
</project>

Web项目配置文件 application.yml :

server:
  port: 8081
  servlet:
    context-path: /
  error:
    path: /error

编写Controller:

@CrossOrigin
@RestController
@RequestMapping("/index")
public class IndexController {

    @GetMapping("/users")
    public List<String> getUserInfo() {
        ArrayList<String> userInfoList = new ArrayList<>();
        userInfoList.add("user1");
        userInfoList.add("user2");
        userInfoList.add("user3");
        System.out.println("获取到用户信息列表");
        return userInfoList;
    }
}

注意:为了解决跨域问题,需要在类上标记注解 @CrossOrigin

我还为应用写了拦截器,当然这不是必须的: 首先是自定义拦截器 RequestInterceptor:

@Component
public class RequestInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
        String path = request.getServletPath();
        if (path.contains("interceptor")) {
            System.out.println("拦截器正在拦截请求:/interceptor请求");
        } else if (request.getRequestURI().contains("/blog")) {
            response.sendRedirect("/newBlog");
            return false;
        } else if (path.contains("/error")) {
            System.out.println("输出错误页面");
        } else if (path.contains("/resources")) {
            System.out.println("输出默认/resources路径下页面");
        } else {
            System.out.println("请求URI: " + path);
        }

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {
        if (response.getStatus() == 404) {
            System.out.println("拦截404状态");
        } else if (response.getStatus() == 500) {
            System.out.println("拦截500状态");
        }
    }
}

然后需要将自定义拦截器加载到WebMvc配置类中:

@Configuration
public class InterceptorConfigurer implements WebMvcConfigurer {
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        RequestInterceptor requestInterceptor = new RequestInterceptor();
        List<String> patterns = new ArrayList<>();
        patterns.add("/**");
//        patterns.add("/interceptor");
//        patterns.add("/interceptor/**");
//        patterns.add("/blog");

        List<String> whiteList = new ArrayList<>();
        whiteList.add("/test");
        whiteList.add("/hello");
        whiteList.add("/hello2");
        whiteList.add("/newBlog");
        whiteList.add("/model/test1");
        whiteList.add("/exception");
        registry.addInterceptor(requestInterceptor).addPathPatterns(patterns).excludePathPatterns(whiteList);
    }

    @Override
    public void addCorsMappings(CorsRegistry registry) {

    }
}

编写前端项目

创建React项目模板,在自定义文件夹中定义组件: 路径如下:./reactlearn/Index.jsx

import React from 'react';

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      data: null
    };
  }

  async componentDidMount() {
    try{
        let myHeaders = new Headers({
            'Access-Control-Allow-Origin': '*',
            'Content-Type': 'text/plain'
        })
        let response = await fetch('http://localhost:8081/index/users',{
            method: 'GET',
            headers: myHeaders,
            mode: 'cors'
        });
        let data = await response.json();
        this.setState({ data:data });
    } catch (error) {
        console.log('Error:', error)
    }
  }

  render() {
    return (
      <div>
        {this.state.data ? this.state.data.map(item => <p >{item}</p>) : <p>Loading...</p>}
      </div>
    );
  }
}

export default MyComponent;

然后在前端项目入口App.js中编写需要引入的组件:

import Index from './reactlearn/Index.jsx';

function HomePage() {
  return (
  <>
    <Index />
  </>
  )
}
export default HomePage;

启动前后端项目

  1. 前端项目需要cd进入到该项目的本地目录,然后启动命令行,执行 npm start
  2. 后端项目则点击IDEA的debug启动模式启动。

结果

点击浏览器刷新按钮,就能看到从后端拿到的userList已经输出到页面上了。

Java
  • 作者:CoCo(联系作者)
  • 发表时间:2024-03-28 19:07:57
  • 更新时间:2024-03-28 19:07:57
  • 版权声明 © 原创不易,转载请注明出处
  • 留言