ReactJS +Spring MVC前後端分離 RESTful 交互

After building your project and after the prototype

We may want to find a way to find a connection of React front to the Java API back side. So here is an example of RESTful usage of Spring MVC and how we use it.

1. Java Spring MVC RESTful

It is not too complex to configure a Spring MVC controller.

@RestController
public class SearchController {

    BasicInfoService basicInfoService = new BasicInfoService();
    JiraInfoService jiraInfoService = new JiraInfoService();
    CommitInfoService commitInfoService = new CommitInfoService();
    GitBlameInfoService gitBlameInfoService = new GitBlameInfoService();

    @RequestMapping(value="/api/BasicInfo",method = RequestMethod.GET)
    public BasicInfoVO basicInfoSearch(@RequestParam String classPath){
        System.out.println(classPath);
        return basicInfoService.getBasicInfo(classPath);
    }

    @RequestMapping(value="/api/JiraInfo",method = RequestMethod.GET)
    public JiraInfoVO jiraInfoSearch(@RequestParam String location){
        System.out.println(location);
        return jiraInfoService.getJiraInfo(location);
    }

    @RequestMapping(value="/api/CommitHistory",method = RequestMethod.GET)
    public List<CommitHistoryVO> commitHistorySearch(@RequestParam String location){
        return commitInfoService.getCommitHistory(location);
    }

    @RequestMapping(value="/api/GitBlameInfo",method = RequestMethod.GET)
    public GitBlameInfoVO gitBlameInfoSearch(@RequestParam String location,@RequestParam String line){
        return gitBlameInfoService.getBlameData(location,line);
    }

    @RequestMapping(value = "/api/ClassTeamMapping",method = RequestMethod.POST, produces = "application/json")
    public List<String> getGitClassTeamMapping(@RequestBody List<String> classes){
        List<String> re = new ArrayList<String>();
        for(int i = 0;i<classes.size();i++){
            String className = classes.get(i);
            List<String> classTeamInfos = basicInfoService.getClassTeamInfoByClassName(className);
            for(int j = 0; j< classTeamInfos.size();j++){
                re.add(classTeamInfos.get(j));
            }
        }
        return re;
    }


}

All we need do is to add @RestController beside the class clarification. And in the @RequestMapping part we can add the route off the REST api, method as well.
The return value can be transfer to JSON object automatically. This Spring MVC RESTful framework will transfer an object into json.
And here is a config of spring-dispatcher-servlet.xml

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">

    <!-- 掃描controller(controller層注入) -->
    <context:component-scan base-package="com.successfactors.classexceptionanalyze.controller"/>

    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="defaultEncoding" value="UTF-8"/>
        <property name="maxUploadSize" value="2000000"/>
    </bean>

    <mvc:resources mapping="/static/**" location="/static/"/>

    <mvc:default-servlet-handler />

</beans>

By all these configuration, we can easily get the RESTful content we need.

2. REACT Http call

Here is an example of REACT use superagent to call a http request to its back side.

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import BasicInfo from './BasicInfoPanel'
import JiraInfo from './JiraInfoPanel'
import ClassCommitHistory from './ClassCommitHistoryPanel'
import ExceptionAnalyze from './ExceptionLineAnalyzePanel'
import request from 'superagent'
import {apis} from './common'

export default class Report extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      classPath: this.props.params.classPath,
      lineNumber: this.props.params.lineNumber
    }
  }

  render() {
    return (
      <div>
        <div className="row">
          <div className="col-md-10 col-md-offset-1">
            <h1 align="center">Class Exception Report</h1>
          </div>
        </div>

        <div className="col-lg-6">
          <BasicInfo info={this.state.basicInfo}/>

          <JiraInfo info={this.state.jiraInfo}/>

          <ClassCommitHistory info={this.state.commitHistory}/>
        </div>
        <div className="col-lg-6">
          <ExceptionAnalyze info={this.state.exceptionAnalyze}/>
        </div>
      </div>
    );
  }

  componentDidMount() {
    request.get(apis.basicInfo(this.state.classPath)).end((err, resp) => {
      if (err) {
        return;
      }
      if (resp.error) {
        return;
      }

      const result = resp.body;
      console.log(result);
      if (result) {
        this.setState({basicInfo: result});
        this.inqueryJiraInfo(result.location);
        this.inqueryCommitHistoryInfo(result.location);
        this.inqueryGitBlameInfo(result.location, this.state.lineNumber);
      }

    })

  }

  inqueryGitBlameInfo(location, line) {
    request.get(apis.gitblameInfo(location, line)).end((err, resp) => {
      if (err) {
        return;
      }
      if (resp.error) {
        return;
      }
      const result = resp.body;
      console.log(result);
      if (result) {
        this.setState({exceptionAnalyze: result});
      }

    })
  }

  inqueryJiraInfo(location) {
    request.get(apis.jiraInfo(location)).end((err, resp) => {
      if (err) {
        return;
      }
      if (resp.error) {
        return;
      }
      const result = resp.body;
      console.log(result);
      if (result) {
        this.setState({jiraInfo: result});
      }

    })
  }

  inqueryCommitHistoryInfo(location) {
    request.get(apis.commitInfo(location)).end((err, resp) => {
      if (err) {
        return;
      }
      if (resp.error) {
        return;
      }
      const result = resp.body;
      console.log(result);
      if (result) {
        this.setState({commitHistory: result});
      }

    })
  }

}

// =======================================

We can take a look at this method.
After the render() method is first called, the componentDidMount() method will be called automatically. And here comes the http request method:

request.get(API).end((err,resp) => {
  if(err){
    /** **/
  }
  if(resp.error){
    /** **/
  }
  const result = resp.body;
  if(result){
    /** Your method **/
  }
})

By this function we will get the information we need and update the state of component so it will render the front side again.

That’s how we use http request and react to separate front and back side.

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章