I am working on a project which has just one page(index.jsp) and initial load of the page an Ajax request is being sent and JSON data is retrieved. The AJAX call sent to my Servlet and Servlet returns JSON data,and i have only one Servlet. I am trying to send the some data to my JSP page to populate, so This is how i am writing my Servlet......
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out =response.getWriter();
String queryString = request.getQueryString();
ResourceBundle props = ResourceBundle.getBundle("jira");
XmlMerge xmlMerge = new XmlMerge();
String mergeFiles=xmlMerge.getJsonData();
out.println(mergeFiles);
out.close();
//Debug Statement
System.out.println(xmlMerge.getTodo());
// *THIS IS THE WAY I AM SEND DATA TO JSP PAGE.*
request.setAttribute("todo", xmlMerge.getTodo());
request.getRequestDispatcher("/index.jsp").forward(request, response);
}
and in my index.jsp
<%=(String)request.getAttribute("todo")%>
I am trying to output the result.
What is going wrong?
I just performed this change and it displays what you need:
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
request.setAttribute("todo", "10");
request.getRequestDispatcher("/index.jsp").forward(request, response);
}
This is the generated index.jsp:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%=(String)request.getAttribute("todo")%>
</body>
</html>
There might be something wrong with your getTodo().. I don't know how it works but maybe this could help:
...
XmlMerge xmlMerge = new XmlMerge();
String todo = xmlMerge.getTodo();
...
request.setAttribute("todo", todo);
UPDATE:
PrintWriter out = response.getWriter();
out.println(...);
out.close();
This is your problem... you are getting the resource and close it. This might cause an illegal state exception issue..
You "don't need" the dispatcher to the index.jsp.. if you don't use a dispatcher but you want to render your page you can use something like this:
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
response.getWriter().write("<html><body>"+getSomething()+"</body></html>");
}
Why isn't index.jsp a default call? because there might not even exists an index.jsp file and it may be the call for another servlet. You can have a configuration that maps the call to index.jsp to a servlet.
http://tutorials.jenkov.com/java-servlets/web-xml.html
I still don't know what is the purpose of using out.println but if you wanted it to be displayed in the jsp you can send it as argument as the "todo":
request.setAttribute("mergeFiles", mergeFiles);
And then print it in the jsp as the "todo".
Related
This question already has answers here:
How to transfer data from JSP to servlet when submitting HTML form
(4 answers)
Closed 4 years ago.
I want to display the text from the text area of an html into a servlet using a button to connect them. The problem is that i dont know how to take the information from the text area to display in the servlet.
This is my method so far:
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<h1>Display content here </h1>");
//Here I want to have the text area content displayed.
out.println();
}
}
Here is my html:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Sample</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
</head>
<body>
<div>
<p>show content of text area when clicking the button</p>
<p></p>
<form action="MyServlet" method="GET">
<textarea name= "name" rows="1" cols="30"></textarea>
<p></p>
<button type="submit" href="MyServlet.do">Get content</button></form>
</div>
</body>
</html>
You're supposed to send your parameter as a GET method of HTTP protocol.
So, you need to implement doGet method of the servlet api.
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try
{
response.setContentType("text/html");
String name = request.getParameter("name") ;
PrintWriter out = response.getWriter();
out.println("<h1>Display name of your text area here: </h1>");
//Here I want to have the text area content displayed.
out.println(name);
out.println();
out.flush();
}
catch(Exception ex)
{
ex.printStackTrace();
}
finally
{
out.close();
}
}
I have the following problem. First of all, I'm send request from jsp to servlet, then I'm doing some operation, and put some data to request, and forward to the same page for rendering new data. But after forwarding, my jsp page doesn't update. Can anyone say me, what I'm doing wrong?
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>File Viewer</title>
<link href="${pageContext.request.contextPath}/resources/css/bootstrap.min.css" rel="stylesheet">
<script src="${pageContext.request.contextPath}/resources/js/bootstrap.min.js"> </script>
<script src="${pageContext.request.contextPath}/resources/js/jquery-1.8.0.min.js"> </script>
<script type="text/javascript">
function showFolderRequest(fileName) {
$.post( "ftp?fileName="+fileName, function( data ) {
});
}
</script>
</head>
<body>
<div class="container-fluid">
<div class="col-md-9 list-group" style="float: none; margin: 20px auto;">
<div class="list-group-item active" style="background-color: darkcyan;">
Ftp server: /
</div>
<c:forEach items="${requestScope.files}" var="fileEntity">
<p class="list-group-item" onclick="showFolderRequest('${fileEntity.name}')">
${fileEntity.name}
</p>
</c:forEach>
</div>
</div>
</body>
</html>
This is my servlet
#WebServlet("/ftp")
public class FileServlet extends HttpServlet {
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
}
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
FileManager fileManager = FileManager.getInstance();
String requestedFileName = req.getParameter("fileName");
req.setAttribute("files", fileManager.getAllFilesByPath(requestedFileName));
getServletContext().getRequestDispatcher("/test.jsp").forward(req, resp);
}
}
The problem is that you're firing an ajax request. When handling ajax requests, you need to be aware of some things:
You cannot forward not redirect from your servlet. This is an asynchronous request from the browser and it won't get any content from a forwarding or redirection from the server.
Expression Language (those things inside ${}) and JSP tags like JSTL run on server side when processing the JSP and rendering the HTML. Any ajax request wont update any EL nor any JSP tag content since this code it is not run on server. So, any new attribute you set here won't matter until you fire a non-ajax request.
The only way you can get any data from the server is by writing a response that contains the desired data. Usually, you would write a JSON response, but you can even write an XML or a plain text response, it will depend on your design. Then, in the browser side (Javascript), you handle the data from the response and display some text, update values in your current HTML, and on.
From this case, you can write a list of the desired files into a JSON string and write that string in the server response, then manage it accordingly in client side. This is just a bare example of how to achieve it using Jackson library to convert Java code into JSON string.
In servlet:
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
FileManager fileManager = FileManager.getInstance();
String requestedFileName = req.getParameter("fileName");
//not really sure what retrieves, I'm assuming it is a Lis<FileEntity>
//edit this accordingly to your case
List<FileEntity> files = fileManager.getAllFilesByPath(requestedFileName);
String json = new ObjectMapper().writeValueAsString(files);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(json);
}
In JavaScript:
<script type="text/javascript">
function showFolderRequest(fileName) {
$.post( "ftp?fileName="+fileName, function( data ) {
//logs the whole JSON string response into browser console
//supported in Chrome and Firefox+Firebug
console.log(data);
//parsing the JSON response
var files = JSON && JSON.parse(data) || $.parseJSON(data);
//since it is an array, you need to traverse the values
for (var fileEntity in files) {
//just logging the files names
console.log(fileEntity.name);
}
});
}
</script>
I'm getting a ping result in my servlet.I'm trying to redirect it to another jsp file.
the jsp file for output opens.But nothing shows in it.
This is my servlet main code
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String ip = request.getParameter("ip");
response.setContentType("text/html");
PrintWriter out = response.getWriter();
// out.println("The ip address is:"+ip+"\n");
String result = pingTest(ip);
out.println(result);
String redirect = "Output.jsp";
RequestDispatcher view = request.getRequestDispatcher(redirect);//Is it good approach to redirect request in ajax based servlet?
view.forward(request, response);
}
This is my output.jsp page
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Ping Check Result</title>
</head>
<body>
</body>
</html
Do I need to add anything in output.jsp?
In your servlet:
request.setAttribute("result", result);
request.getRequestDispatcher("/WEB-INF/Output.jsp").forward(request, response);
In your JSP:
<pre>The data from servlet: ${result}</pre>
your servlet must be :
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String ip = request.getParameter("ip");
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("The ip address is:"+ip+"\n");
String result = pingTest(ip);
out.println(result);
RequestDispatcher view = request.getRequestDispatcher();
view.forward(request, response);
}
This is my JSP File. It has 3 text fields and a submit button..
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="buttontoserv" method="post">
<input type="text" name="name"/><br>
<input type="text" name="group"/>
<input type="text" name="pass"/>
<input type="submit" value="submit">
</form>
</body>
</html>
This is my web.xml
<?xml version="1.0" encoding="utf-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">
<servlet>
<servlet-name>ButtontoServ</servlet-name>
<servlet-class>pack.exp.ButtontoServServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ButtontoServ</servlet-name>
<url-pattern>/buttontoserv</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>
This is the servlet under pack.exp package with file name ButtontoServServlet.java
package pack.exp;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.*;
#SuppressWarnings("serial")
public class ButtontoServServlet extends HttpServlet
{
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
String name = request.getParameter("name");
String group = request.getParameter("group");
String pass = request.getParameter("pass");
System.out.println("Name :"+ name);
System.out.println("group :"+ group);
System.out.println("pass :"+ pass);
}
}
When I am deploying it to the google app engineit is throwing this error
"Error: HTTP method GET is not supported by this URL"
I also tried on tomcat and the error says
"HTTPO 405 Method not allowed. The website cannot display the page HTTP 405
Most likely cause: •The website has a programming error."
As your servlet has only doPost method. So, you can't get access the servlet with URL. Your URL should be for JSP page where action="buttontoserv" is assigned. When you click the submit button of JSP page than it will forwarded to /buttontoserv servlet.
To solve your problem, you should include a doGet method on Servlet or forward to Servlet with form submit from JSP page.
public class ButtontoServServlet extends HttpServlet {
protected void processRequest(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
String name = request.getParameter("name");
String group = request.getParameter("group");
String pass = request.getParameter("pass");
System.out.println("Name :"+ name);
System.out.println("group :"+ group);
System.out.println("pass :"+ pass);
}
#Override
protected void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
#Override
protected void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
}
Make sure you type the url to the jsp file instead of the servlet. Also try overriding the doGet method too like:
protected void doGet (HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
doPost(request, response);
}
I have doPost in a servlet -
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
request.getSession().setAttribute("sysMsg","now we gonna to break line \n");
// forward to printLine.jsp page
dispather.forward(request, response) ;
}
And jsp page (says , printLine.jsp) -
<html>
<head>
<title></title>
</head>
<body>
<font size="30" color="Red">${sysMsg} </font>
</body>
</html>
I want that in printLine.jsp the printing of sysMsg finally break line ... For that in put \n in the end of sysMsg when set him in the servlet , but this way didn't work .
Try <br/> instead
request.getSession().setAttribute("sysMsg","now we gonna to break line <br/>");