基于vue和springmvc前后端分离,json类接口调用介绍

版本要求:spring-3.2.9.RELEASE、vue-2.9.2、axios-0.17.1,其中axios作为http client供vue访问springmvc的接口。

1,maven配置

<!-- spring -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-aop</artifactId>
    <version>3.2.9.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-beans</artifactId>
<version>3.2.9.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>3.2.9.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-core</artifactId>
    <version>3.2.9.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-expression</artifactId>
    <version>3.2.9.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-web</artifactId>
    <version>3.2.9.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>3.2.9.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>3.2.9.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jdbc</artifactId>
    <version>3.2.9.RELEASE</version>
</dependency>

    <!-- mybatis -->
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>servlet-api</artifactId>
        <version>2.5</version>
    </dependency>

<!-- apache commons -->
<dependency>
    <groupId>commons-lang</groupId>
    <artifactId>commons-lang</artifactId>
    <version>2.5</version>
</dependency>

<dependency>                                                        
    <groupId>log4j</groupId>      
    <artifactId>log4j</artifactId>
    <version>1.2.16</version>     
</dependency>

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.9.0</version>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-core</artifactId>
    <version>2.9.0</version>
</dependency>

2,spring配置,spring-app.xml

<?xml version="1.0" encoding="UTF-8"?>
<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:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
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.2.xsd 
        http://www.springframework.org/schema/tx 
        http://www.springframework.org/schema/tx/spring-tx-3.2.xsd 
        http://www.springframework.org/schema/aop 
        http://www.springframework.org/schema/aop/spring-aop-3.2.xsd 
        http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context-3.2.xsd
        http://www.springframework.org/schema/mvc 
        http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">

    <context:component-scan base-package="spring.mvc.controller" />
    <mvc:annotation-driven />   
</beans>

3.编写控制类

package spring.mvc.controler;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import spring.mvc.model.User;

@Controller
@Scope("prototype")
@RequestMapping(value="/test")
public class HelloWorldController {
    @RequestMapping(value="/users/{userName}", method=RequestMethod.GET)
    public @ResponseBody User findUser(@PathVariable("userName") String userName) {
        User user = new User();
        user.setUserName(userName);
        user.setSex("男");
        return user;
    }

    @RequestMapping(value="/users/add", method=RequestMethod.POST)
    public @ResponseBody Long createUser(@RequestBody User user) {
        user.setId(System.currentTimeMillis());
        userMapper.insert(user);
        return user.getId();
    }
}

4.编写实体类

package spring.mvc.model;
public class User {
    private Long id;
    private String userName;
    private String sex;

    public User() {
    }

    public Long getId() {
        return id;
    }
    public void setId(Long id) {
        this.id = id;
    }
    public String getUserName() {
        return userName;
    }
    public void setUserName(String userName) {
        this.userName = userName;
    }
    public String getSex() {
        return sex;
    }
    public void setSex(String sex) {
        this.sex = sex;
    }   
}

5,编写跨域filter,如果vue容器和springmvc服务容器分开部署,则在springmvc返回消息中增加Access-Control-Allow-Origin为*。

package spring.mvc.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;

public class CorsFilter implements Filter{

    @Override
    public void destroy() {
        // TODO Auto-generated method stub

    }

    @Override
    public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2)
            throws IOException, ServletException {
        // TODO Auto-generated method stub
        HttpServletResponse httpServletResponse = (HttpServletResponse) arg1;
        httpServletResponse.setHeader("Access-Control-Allow-Origin", "*");
        arg2.doFilter(arg0, httpServletResponse);
    }

    @Override
    public void init(FilterConfig arg0) throws ServletException {
        // TODO Auto-generated method stub

    }

}

6,假设springmvc服务部署在tomcat,应用名称为springmvc

web.xml配置如下
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
    http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
    <welcome-file-list>
        <welcome-file>index.html</welcome-file>
    </welcome-file-list>

    <servlet>
        <servlet-name>springMVC</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath*:/spring-app.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>springMVC</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>default</servlet-name>
        <url-pattern>*.html</url-pattern>
    </servlet-mapping>

    <filter>
        <filter-name>corsFilter</filter-name>
        <filter-class>spring.mvc.filter.CorsFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>corsFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
</web-app>

7,vue_hello.html编写,注意{host}和{port}按实际情况设置

<script src="https://cdn.jsdelivr.net/npm/vue"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

<div id='app99'>
    <p>{{message}}</p>
    <button v-on:click="findUser">查询用户</button>
</div>

<script type="text/javascript">

var app99 = new Vue({
    el: '#app99',
    data: {
        message: 'user'
    },
    methods: {
        findUser: function() {
            axios.get('http://{host}:{port}/springmvc/test1/users/1')
            .then(response => {
                console.log(response.data);
                this.message = response.data;
            })
            .catch(error => {
                console.log(error);
                this.message = error;
            })
        }
    }
})

</script>

8,启动tomcat,然后用浏览器打开vue_hello.html,页面显示如下

user
查询用户

点击“查询用户”按钮,页面显示如下
{ "id": null, "userName": "1", "sex": "男" }
查询用户

10,至此,基于vue和springmvc,可实现前后端分离,两者之间通过http+json交互数据。