【问题标题】:Populate Form in JSP page from Java从 Java 中填充 JSP 页面中的表单
【发布时间】:2013-03-06 12:05:37
【问题描述】:

我正在尝试根据 Java 的结果找到一种在 JSP 页面中填充“表单”的方法。

这是我的 Javascript 代码:

$('#uSystemList').change(function() {
    $.get("/live-application/systemById", {systemid: $("#uSystemList").val()}, displayChangedSystemResults, "html");
});

function displayChangedSystemResults(html){
    $('#systemForm').empty();
    $('#systemForm').append(html);
}

形式:

<form:form id="systemForm" method="post" action="/live-application/systemSave" commandName="systemForm">
<tr>
    <td valign="top"><form:select path="uSystemList" id="uSystemList"> </form:select> </td>
</tr>
<tr>
    <td valign="top"><form:input path="fSystemName"/></td>
</tr>
</form:form>

还有 Java 方面:

@RequestMapping(value = "/systemById", method = RequestMethod.GET)
public void getSystemById(@RequestParam("systemid") String systemid, OutputStream outputStream) throws IOException {
    StringBuilder refreshHtml = new StringBuilder();
    try {
        String html = new String();
        if (!systemid.equals("")) {
            System system = service.getSystemById(systemid));

            html = html + "<input type='text' value='" + system.getName() + "' id='fSystemName' />";
        } 
        refreshHtml.append(hostHtml);
        outputStream.write(refreshHtml.toString().getBytes());
        outputStream.flush();
    } catch (Exception e) {
        outputStream.flush();
    }
}

作为测试,我只想填充表单的fSystemName 字段,但当它返回displayChangedSystemResults 函数时没有任何反应。谁能发现我做错了什么?

【问题讨论】:

  • form:select 可能应该以&gt; 结束,而对于form:input 则缺少/&gt;
  • 抱歉,这是一个错误,因为我从中删除了很多代码。我现在要编辑...

标签: java html ajax spring jsp


【解决方案1】:

更简单的实现方式是设置要显示的Request Attribute的值 并在 JSP 中访问它。

在服务器端

调整方法签名以包含 Spring 模型

public void getSystemById(@RequestParam("systemid") String systemid, Model model , OutputStream outputStream) throws IOException {

而在请求处理方法中你可以这样做

System system = service.getSystemById(systemid));
model.addAttribute("fSystemName", system.getName());

然后使用JST lib在JSP中显示

为了使用 JSTL,请将以下 jars 添加到您的 /WEB-INF/lib

编辑


    <tr>
 <td valign="top"><input type="text" value="${fSystemName}"></input></td>
    </tr>

编辑 2

你不应该直接处理输出流,你应该让 spring 为你做。 理想情况下,您的方法应该返回一个 view name ,spring 会自动解决

查看下面的简单教程。这应该会让你朝着正确的方向前进

Spring 3 MVC Hellow World

【讨论】:

  • 感谢您的回答,它只是在 JSP 端说“标签(表单:输入)必须为空”
  • 谢谢 - 仍然没有发生任何事情。我需要对模型做些什么吗?把它返还?您的方法返回类型为 void,所以我假设不是,但请告诉我是否需要做一些事情才能让它“刷新”?
  • 我确实检查了编辑,但它仍然没有设置系统名称字段...有什么想法吗?
猜你喜欢
  • 2017-02-07
  • 2013-08-25
  • 2015-07-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-07-27
  • 2011-03-24
  • 1970-01-01
相关资源
最近更新 更多