MVC Spring Controller,在HTML文件中显示dbData

时间:2018-06-13 08:34:23

标签: java html database spring model-view-controller

如果我编写Spring MVC Controller,如何在HTML文件中显示DBData。

e.g。我有db.table名为Setting,我想在我的HTML文件中将该表中的ID显示为下拉列表。

C:\spark\Hadoop\bin\winutils.exe chmod 777 C:\tmp\hive
 @Controller
public class CustomChannelController {

    private Setting setting;
    private Diagram diagram;
    private Channel channel;

    @RequestMapping(value = "/customchannel", method = RequestMethod.GET, produces = "application/json; charset=utf-8")
    public @ResponseBody Setting getId() {
        return this.setting;
    }

2 个答案:

答案 0 :(得分:0)

这取决于你如何检索数据......你使用AJAX调用吗?或者在加载页面时你需要它们吗?

让我们看看2个场景 注意:在两种情况下,我们假设您返回的对象列表如下:

public class Option{
  private String value;
  private String text;
  //getter and setter
}

AJAX CALL :为此我假设我们正在使用JQuery;在这种情况下,您将在JS或JSP文件中使用以下内容:

$.ajax({
    url : 'customchannel',
    dataType : 'json',
    contentType : 'application/json; charset=UTF-8',
    type : 'GET',

    success : function(items) {
        $.each(items, function (i, item) {
            $('#selectReportChannel').append($('<option>', { 
                value: item.value,
                text : item.text 
         }));
        });
    },
    error : function(data) {

    }
});


<select id="selectReportChannel" class="form-control">
</select>

页面已加载在这种情况下,您的控制器将呈现HTML页面,您可以执行以下操作:

 @Controller
public class CustomChannelController {

    private Setting setting;
    private Diagram diagram;
    private Channel channel;

    @RequestMapping(value = "/customchannel", method = RequestMethod.GET)
    public ModelAndView getId(Model uiModel) {
    uiModel.add("options", this.setting);
        return new ModelAndView("yourPage", uiModel) ;
    }

然后在HTML页面中,您可以这样使用JSTL:

<table>
    <tr>
        <td>
            <label class="col-md-12 control-label"> <%=language['UI.reportSetting.channel']%> : </label>
        </td>
        <td>
            <select id="selectReportChannel" class="form-control">
                <c:forEach items="${options}" var="option">
            <option value="${option.value}">${option.text}</option>
        </c:forEach>
            </select>
        </td>
    </tr>
</table>

答案 1 :(得分:0)

好的,我找到了解决方案。首先需要创建一个Spring MVC Controller然后创建一个Service,然后将Controller链接到Backbone模型文件。