Servlet与JSP通信的最佳方式

The best way for Servlet and JSP communication

以下场景:

我的 Servlet 中有一个 java.sql.ResultSet rs。现在我想制作图表(使用纪元https://fastly.github.io/epoch/getting-started/)。

图表js需要数据格式如下:

var data = [ { label: 'Layer 1', values: [ {x: 0, y: 0}, {x: 1, y: 1}, {x: 2, y: 2} ] }, { label: 'Layer 2', values: [ {x: 0, y: 0}, {x: 1, y: 1}, {x: 2, y: 4} ] } ];

现在,我的 ResultSet 看起来像这样:

x,y

x,y

...

ServletJSP 之间应该如何沟通?我应该只将 ResultSet obejct 发送到 JSP 并在那里转换还是应该在 Servlet 中转换?

我至少会将 ResultSet 中的数据提取到 Collection(例如 List)中,然后在 JSP 中使用它(使用 JSTL)。

但如果这是一个选项,我会认真考虑完全放弃 JSP 并将 servlet 重新实现为 REST 服务,您可以从客户端的 Javascript 调用(和 return 数据作为 JSON 直接来自 servlet)。

编辑:要扩展第二个选项,您可以将数据转换为 JSON 字符串(手动或使用像 Jackson - see here for an example 这样的库),然后将该字符串放入servlet 响应。

然后您可以从 Javascript 调用 servlet。我不知道您使用的是什么框架,但您可以使用几行 jquery(参见 jquery.get()

在我看来,Servlet 永远不应该引用 ResultSet。您应该将此逻辑封装到一个可以测试、模拟、拦截等的服务中。

例如

public class Series {
    private String label;
    private List<Point> points;

    // getters and setters
}

public class Point {
    private double x;
    private double y;

    // getters and setters
}

public interface ChartService {
    List<Series> getAverageRainfall(Date from, Date to);
}

public class ChartServiceImpl implements ChartService {
    public List<Series> getAverageRainfall(Date from, Date to) {
        // here is where you might reference java.sql.ResultSet
    }
}

这可以很容易地变成一个 http 端点,returns json 使用 spring 或类似的意思,你实际上不需要自定义 servlet。