I have a table in html called "messages". columns "message" and "type". I want to add data in this table from java servlet. How can I do that?
Asked
Active
Viewed 7,648 times
0
-
might be a copy of [this post](http://stackoverflow.com/questions/10594919/passing-value-from-servlet-to-html) – Joey May 08 '16 at 11:21
-
explain with more details – Gaurav Mahindra May 08 '16 at 11:56
-
I have a database in mysql. I want to retrieve that data and post it to a html table when a button is clicked. This should include jscript and servlet. How can I do that? – user3049602 May 10 '16 at 15:01
1 Answers
0
Assuming that you have your messages in an array, you can do it like this. Just copy and paste. Cheers! :D
Servlet1.java
package com.test;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet(name = "Servlet1", urlPatterns = {"/"})
public class Servlet1 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String[][] messages = {
{"Message 1", "Type 1"},
{"Message 2", "Type 2"},
{"Message 3", "Type 3"},
};
request.setAttribute("messageList", messages);
request.getRequestDispatcher("/index.jsp").forward(request, response);
}
}
index.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<table id="messages" border="1">
<tr>
<th>Message</th>
<th>Type</th>
</tr>
<c:forEach var="msg" items="${requestScope.messageList}">
<tr>
<td>${msg[0]}</td>
<td>${msg[1]}</td>
</tr>
</c:forEach>
</table>
</body>
</html>

Herupkhart
- 499
- 4
- 23
-
how do I change index.jsp to html file. sorry I am quite new in this – user3049602 May 08 '16 at 13:19
-
you need to use a JSP file in order to utilize the dynamically generated list. a plain HTML file won't work. – Herupkhart May 08 '16 at 13:23
-
if you really need the .html extension, you might as well want to see this post: https://stackoverflow.com/questions/20326451/hide-jsp-extension-or-change-display-name-on-url – Herupkhart May 08 '16 at 13:25
-
its not about extension, I want html file insted of jsp. there is difference isnt it? – user3049602 May 09 '16 at 09:27
-
yep there is, an HTML page cannot generate dynamic content whereas a JSP can. Technically, a JSP is just a Servlet under the hood. – Herupkhart May 09 '16 at 20:26
-
-
If anyone need a proper code for this question just comment below: – user3049602 May 12 '16 at 17:21