繁体   English   中英

使用Java Servlet从html表单加载数据,更新数据库并在表的同一页上显示数据

[英]Load data from html form, update database and display data on the same page in table using java servlet

我需要协助。 我有一个包含Java Servlet和html表单的小应用程序。 用户以html形式放置一些数据,然后单击“提交”按钮后,java servlet将数据放入其post方法中(将其加载到数据库中)。 到现在一切正常。 我正在使用Java servlet和tomcat。 我现在想做的是在html的同一页上的表中显示数据。 我发现,这可以通过ajax get方法实现。 但是不知何故我做对了。 这里是我的应用程序的简化代码:Java Servlet:

@WebServlet(name = "MyServlet", urlPatterns = { "/MyServlet" })
public class MyServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse    response) throws ServletException, IOException {
response.setContentType("text/html");
// getting the values submitted by the user from the html form
String name = request.getParameter("name");
String surname = request.getParameter("surname");
// here goes some logic to load data in the database
// data from database is recieved as an array and is then converted to 
// json 
// here I can only print the whole json retrieved from DB 
// and it is displayed on another page with myurl/MyServlet
 response.setContentType("application/json");
 PrintWriter out = response.getWriter();
 response.setCharacterEncoding("UTF-8");
 out.println(json);

}
public void doGet(HttpServletRequest request, HttpServletResponse   response) throws IOException{
// nothing happens here
}

在我的html表单中,我有以下内容(仅在这里最重要):

<form action="MyServlet" method="post">
<input class="form-control" type="text" name="name" id="name">
<input class="form-control" type="text" name="surname" id="surname">
<input type="submit" class="btn btn-info" id="MyS"value="MyServlet">
<table class="table" id="table">
<tr>
    <th>name</th>
    <th>surname</th>
</tr>

用户输入存储在数据库中,一切正常。 问题是,我没有响应,我想将用户提供的所有数据显示在一个表中,应该在每次提交后将其更新,并将用户保持在同一页面上(实际上不知道如何处理)。做这个)。 从数据库中,我得到一个可以转换为JSON的数组,所有这些信息都应显示在表中。 我试图写一些像这样的ajax.get(我是JavaScript中的真正的新人):

<script>
<script type="text/javascript">
$("#MyS").click(function() {

}
$.ajax({
    url: "/MyServlet",
    type: "POST",
    dataType: '{json: json}',
    data: myvalue,

    success: function(data) {  
        $('#table').append(data);
    },
});
</script>

但是,表或某处没有数据显示。 我很高兴得到一些提示,我做错了什么以及应该如何正确完成? 提前致谢。

使用以下行执行它,并告诉我您在浏览器控制台中得到的响应:

$.ajax({
    url: "/MyServlet",
    type: "POST",
    dataType: '{json: json}',
    data: myvalue,
    success: function(data) 
    {  
        console.log( data ); // logs this on success
        $('#table').append(data);
    },
    **error: function (textStatus, errorThrown) 
    {
        console.log( textStatus ); // log this on error
        console.log( errorThrown );
    }**
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM