前后端分离,想用Java写一个简单的接口给前端调用如何才能实现?求个简单的例子,

现在自己已经可以从0到1用SpringBoot项目

2021年1月11日更新

刘建后台管理系统JAVA

我想暴露一个json字符串出来给前端页面

package com.mvc.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;
import com.mvc.bean.NewTotal;
import com.mvc.bean.News;

public class JsonServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 创建多个新闻类,模拟从数据库获取数据,可将此处改为用JDBC从数据库读取数据
        News new1 = new News(110, "日本地震", "日本福田发生了7级地震", "2016-5-16 10:22:20",
                "http://world.huanqiu.com/exclusive/2016-05/8974294.html");
        News new2 = new News(111, "Apple库克第八次访华", "近日库克第八次访华,与滴滴高层会谈", "2016-5-16 10:22:20",
                "http://mobile.163.com/16/0523/09/BNO7SG2B001168BQ.html");
        News new3 = new News(113, "Google I/O大会开幕", "Google开发者大会即将举办,是否推出Android7.0?", "2016-5-16 10:22:20",
                "http://www.ithome.com/html/android/227647.htm");
        News new4 = new News(114, "格力营收下滑400亿", "格里营收下滑400亿,董明珠说我活得好的很", "2016-5-16 10:22:20",
                "http://news.mydrivers.com/1/484/484072.htm");
        News new5 = new News(115, "格力营收下滑400亿", "格里营收下滑400亿,董明珠说我活得好的很", "2016-5-16 10:22:20", "www.baidu.com");
        News new6 = new News(116, "格力营收下滑400亿", "格里营收下滑400亿,董明珠说我活得好的很", "2016-5-16 10:22:20", "www.baidu.com");
        News new7 = new News(117, "格力营收下滑400亿", "格里营收下滑400亿,董明珠说我活得好的很", "2016-5-16 10:22:20", "www.baidu.com");
        News new8 = new News(118, "格力营收下滑400亿", "格里营收下滑400亿,董明珠说我活得好的很", "2016-5-16 10:22:20", "www.baidu.com");
        News new9 = new News(119, "格力营收下滑400亿", "格里营收下滑400亿,董明珠说我活得好的很", "2016-5-16 10:22:20", "www.baidu.com");
        News new10 = new News(120, "格力营收下滑400亿", "格里营收下滑400亿,董明珠说我活得好的很", "2016-5-16 10:22:20", "www.baidu.com");
        News new11 = new News(121, "获取新数据!!!!!!", "格里营收下滑400亿,董明珠说我活得好的很", "2016-5-16 10:22:20", "www.baidu.com");
        News new12 = new News(122, "获取新数据!!!!!!", "格里营收下滑400亿,董明珠说我活得好的很", "2016-5-16 10:22:20", "www.baidu.com");
        News new13 = new News(123, "获取新数据!!!!!!", "格里营收下滑400亿,董明珠说我活得好的很", "2016-5-16 10:22:20", "www.baidu.com");
        News new14 = new News(124, "获取新数据!!!!!!", "格里营收下滑400亿,董明珠说我活得好的很", "2016-5-16 10:22:20", "www.baidu.com");
        News new15 = new News(125, "格力营收下滑400亿", "格里营收下滑400亿,董明珠说我活得好的很", "2016-5-16 10:22:20", "www.baidu.com");
        News new16 = new News(126, "格力营收下滑400亿", "格里营收下滑400亿,董明珠说我活得好的很", "2016-5-16 10:22:20", "www.baidu.com");
        News new17 = new News(127, "格力营收下滑400亿", "格里营收下滑400亿,董明珠说我活得好的很", "2016-5-16 10:22:20", "www.baidu.com");
        News new18 = new News(128, "格力营收下滑400亿", "格里营收下滑400亿,董明珠说我活得好的很", "2016-5-16 10:22:20", "www.baidu.com");
        News new19 = new News(129, "格力营收下滑400亿", "格里营收下滑400亿,董明珠说我活得好的很", "2016-5-16 10:22:20", "www.baidu.com");
        News new20 = new News(130, "格力营收下滑400亿", "格里营收下滑400亿,董明珠说我活得好的很", "2016-5-16 10:22:20", "www.baidu.com");

        String page = req.getParameter("page");
        // 将数据添加到数组
        List<News> newslist = new ArrayList<News>();
        if (page == null || page.equals("0")) {
            newslist.add(new1);
            newslist.add(new2);
            newslist.add(new3);
            newslist.add(new4);
            newslist.add(new5);
            newslist.add(new6);
            newslist.add(new7);
            newslist.add(new8);
            newslist.add(new9);
            newslist.add(new10);
        }
        else {
            newslist.add(new11);
            newslist.add(new12);
            newslist.add(new13);
            newslist.add(new14);
            newslist.add(new15);
            newslist.add(new16);
            newslist.add(new17);
            newslist.add(new18);
            newslist.add(new19);
            newslist.add(new20);
        }

        // 将数据封装到新闻总计类
        NewTotal nt = new NewTotal(newslist.size(), newslist);

        // 调用GSON jar工具包封装好的toJson方法,可直接生成JSON字符串
        Gson gson = new Gson();
        String json = gson.toJson(nt);

        // 输出到界面
        System.out.println(json);
        resp.setContentType("text/plain");
        resp.setCharacterEncoding("gb2312");
        PrintWriter out = new PrintWriter(resp.getOutputStream());
        out.print(json);
        out.flush();
        // 更多Json转换使用请看JsonTest类
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }

}
<?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>

    <groupId>activemq.apache</groupId>
    <artifactId>graduation03</artifactId>
    <version>1.0-SNAPSHOT</version>

    <dependencies>

        <!-- webSocket -->
        <dependency>
            <groupId>javax</groupId>
            <artifactId>javaee-api</artifactId>
            <version>7.0</version>
        </dependency>


        <!-- MySql 5.5 Connector -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.45</version>
        </dependency>

        <!-- config -->
        <dependency>
            <groupId>com.typesafe</groupId>
            <artifactId>config</artifactId>
        </dependency>
        <dependency>
            <groupId>com.github.racc</groupId>
            <artifactId>typesafeconfig-guice</artifactId>
        </dependency>

        <dependency>
            <groupId>org.fusesource.stompjms</groupId>
            <artifactId>stompjms-client</artifactId>
            <version>1.18</version>
        </dependency>

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.31</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/jstl/jstl -->
        <dependency>
            <groupId>jstl</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>

    </dependencies>

</project>
阅读 28.8k
10 个回答

楼上有人提到了 SpringBoot,我这里就抛砖引玉,写个 demo 给题主。

  • 添加 Maven 依赖
<!-- 基于 SpringBoot 1.5.9 -->
<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.9.RELEASE</version>
    <relativePath/>
</parent>
<dependencies>
<!-- 添加 Web 依赖 -->
 <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
 </dependency>
 <!-- lombok 支持 -->
 <dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
 </dependency>
 </dependencies>
 <!-- 添加构建工具 -->
 <build>
    <plugins>
      <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
      </plugin>
    </plugins>
</build>
  • 定义目录结构

假设需要定义的项目的目录结构如下:

src
  `-- main
    `-- java
        `-- com.example
            |-- dto
            |   `-- News.java
            |-- controller
            |   `-- NewsEndpoint.java
            `-- application
                `-- Application.java
    
  • News.java

需要用 JSON 传给前端的 News 对象定义如下:

@Getter
@Setter
@ToString
public class News implements Serializable {

    /**
     * 新闻主键
     */
    private int nid;

    /**
     * 新闻标题
     */
    private String newsTitle;

    /**
     * 新闻内容
     */
    private String newsContent;

    /**
     * 新闻日期
     */
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", locale = "zh", timezone = "GMT+8")
    private Date newsDate;

    public News(int nid, String newsTitle, String newsContent, Date newsDate) {
        this.nid = nid;
        this.newsTitle = newsTitle;
        this.newsContent = newsContent;
        this.newsDate = newsDate;
    }

}
  • NewsEndpoint.java
@RestController
public class NewsEndpoint {

    @GetMapping("/news")
    public List<News> getNewsList() {

        List<News> newsList = new ArrayList<>(3);

        News news1 = new News(1, "title1", "content1", new Date());
        News news2 = new News(2, "title2", "content2", new Date());
        News news3 = new News(3, "title3", "content3", new Date());

        newsList.add(news1);
        newsList.add(news2);
        newsList.add(news3);

        return newsList;

    }
}
  • Application.java
@SpringBootApplication(scanBasePackages = "com.example")
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

到这里,一个简单的返回 JSON 格式的 Endpoint 已经写好了。默认情况下,启动该项目(运行 Application.class),前端通过调用 http://<你的主机ip地址>:8080/news 可以获得如下返回结果:

调用 News Endpoint

你也没说要简单到什么地步啊...

快速开发那就上 Spring Boot,网上大把例子。

撇开各种框架不谈,单单使用JSP+Servlet可以这么做:

1.新建一个JSP页面,专门用于承载你返回的JSON数据,类似下面这样:

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
${json}

2.相关的Servlet执行完毕之后,可以在response中设置一个名为json的属性,属性值就是你要返回的json格式数据,完了将请求转发到第一步的JSP页面;

// 输出到界面

    System.out.println(json);
    resp.setContentType("text/plain");
    resp.setCharacterEncoding("gb2312");
    PrintWriter out = new PrintWriter(resp.getOutputStream());
    out.print(json);
    out.flush();
    
    
   改成response.getWriter.wirter(yourVariable); // 这样前端访问你的servelt不就可以获取到你的yourVaribale了吗,接下来的就是前端多json 对象的解析了

springboot或者 resteasy+netty都可以很快速的搭建起rest服务

这个不是百度Google之类的就可以解决的吗……最简单当然spring boot

推荐我们开发的Dgate,支持mock功能,目前只支持返回json格式,使用groovy DSL语法产生配置,只需简单几下就可以生成一个mock的json给客户端使用,如果你懂一些groovy会用的更顺手。

你是担心跨域调用吗,前端用node代理就行了。

Servlet写个地址就可以了呀

   json的话 可以使用Jackson插件 可以将对象转换为json类型  对于SpringMVC 只需要加上@ResponesBady就可以自动将对象转换成json 响应给前端 如果存在跨域 可以使用jsonp来处理
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
宣传栏