Send data from servlet to jsp using ajax [duplicate] - java

This question already has answers here:
How should I use servlets and Ajax?
(7 answers)
Closed 2 years ago.
Here I am sending data from servlet to jsp using ajax request.But i didn't get any value from servlet on my client side.This is my code
Servlet
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String s="msg";
System.out.print("Servlet");
response.setContentType("text/plain");
PrintWriter out=response.getWriter();
out.print(s);
out.flush();
out.close();
}
jsp
<%# 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 content="text/html;charset=utf-8" http-equiv="Content-Type">
<meta content="utf-8" http-equiv="encoding">
<title>Insert title here</title>
<script src="js/jquery-1.11.1.js" type="text/javascript"></script>
<script type="text/javascript">
function poll() {
setTimeout(function () {
$.ajax({
type: 'POST',
url: 'http://localhost:8080/ajaxtest/testajax',
success: function (data) {
alert(data); //DatO ANY PROCESS HERE
//document.getElementById("testid").value=data;
//document.write(data)
},
complete: poll
});
}, 5000);
}
</script>
</head>
<body onload="poll()">
<form><input type="text" name="test" id="testid" value=""></form>
</body>
</html>
output:
Am getting empty alert box and "No element found" on the browser debugging tool.

Your code is working fine for me. Check if you have your jquery.js accessed properly from jsp and also check your web.xml for correct servlet mapping.
best to include below line for jquery.js , one less thing to bother about:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

You should set the data, before putting alert box. currently alert box is not getting any data

Related

How to modify html to jsp display page for servlet response

I am trying to build a site that displays report results based on a date range inputted by the user. First I built the front-end "aesthetics" part of it in HTML/CSS/JS using dummy json data to retrieve the results. Now I am trying to eliminate the json and actually integrate it with the backend, which I have no experience with so am struggling a bit.
Right now I have a Java servlet written, and it works alright. I'm writing the ResultSet from the database query by doing response.getWriter().write(""); Now from what I've seen the next step is to display the results by appending to the URL, but the code that formats and displays it properly is just a div currently. What is the proper way to do this/modify the code?
Sorry if this is a badly written question, I'm not totally sure of all the terminology or best practices, although I'm trying to learn.
EDIT: Currently on the html page I have
$('#gen-report').click(function(){
$("#auction-report").fadeIn({ duration: 400 });
}
In the auction-report div is all of my formatting & elements (charts, displays, etc.) Is there a way to make use of this code instead of having to start my jsp page from scratch?
Put parameters in servlet to request, then invoke forward from request.getRequestDispatcher.
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setAttribute("now", LocalDate.now());
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/view/test.jsp");
dispatcher.forward(request, response);
}
Now you have access to params which you put in request. Here jsp:
<%# page language="java" contentType="text/html; charset=windows-1255"
pageEncoding="windows-1255"%>
<!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=windows-1255">
<title>Test</title>
</head>
<body>
<h2>Date</h2>
<%= request.getParameter("now") %>
</body>
</html>

Integrating JavaScript with Java Backend

Trying to find the best way to make a quasi java-javascript web application. I want to write a java servlet (for the controller and backend) with a jQuery front end. What's the best approach to having these two communicate with each other? I'm used to coding in both but never worked on them together.
Can anybody help me out? I suppose a start would be having a Java Servlet call from jQuery code and getting a response back from the servlet.
Thanks!
Create REST backend using one of JAX-RS implementations (Jersey, RESTeasy etc.). Writing web service with plain old Servlet API is tedious.
You can start learning JAX-RS from here.
Take a look at jQuery's ajax function. Here is a simple example:
// Servlet
#SuppressWarnings("serial")
public class AjaxHandler extends HttpServlet {
#Override
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException, ServletException {
resp.setContentType("text/plain");
resp.getWriter().print("Hello jQuery!");
}
}
// View.jsp
<%# 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">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<title>Insert title here</title>
</head>
<body>
<script>
$(document).ready(function() {
$.ajax({
url : '/AjaxHandler', // servlet mapping ("web.xml")
success : function(responseText) {
$('#ajaxHandlerResponse').text(responseText);
}
});
});
</script>
Servlet's message: <span id="ajaxHandlerResponse"></span>
</body>
</html>

How can I set a session variable in a servlet and get it in a JSP?

I'm learning java and try to pass some variable from servlet to jsp page. Here is code from servlet page
#WebServlet("/Welcome")
public class WelcomeServlet extends HttpServlet
{
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
HttpSession session = request.getSession();
session.setAttribute("MyAttribute", "test value");
// response.sendRedirect("index.jsp");
RequestDispatcher dispatcher = request.getRequestDispatcher("index.jsp");
dispatcher.forward(request, response);
}
}
And simple jsp
<%# 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>My Index page</title>
</head>
<body>
Index page
<br />
<%
Object sss = request.getAttribute("MyAttribute");
String a = "22";
%>
<%= request.getAttribute("MyAttribute"); %>
</body>
</html>
Whatever I do attribete at jsp is null.
What is wrong at this simple code?
you are getting if from request not session.
It should be
session.getAttribute("MyAttribute")
I suggest you to use JavaServer Pages Standard Tag Library or Expression Language instead of Scriplet that is more easy to use and less error prone.
${sessionScope.MyAttribute}
or
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<c:out value="${sessionScope.MyAttribute}" />
you can try ${MyAttribute}, ${sessionScope['MyAttribute']} as well.
Read more
Oracle Tutorial - Using JSTL
Oracle Tutorial - Expression Language
You set an attribute in a session. You have to retrieve it from a session:
Object sss = session.getAttribute("MyAttribute");
And since you are dispatching the request, you actually don't need a session. You can set the attribute in a request object in your servlet:
request.setAttribute("MyAttribute", "test value");
Then read it as you are already doing in you JSP.
You should avoid scriptlets because they are java code in HTML, they break MVC pattern, they are ugly, odd and deprecated.
Simply replace :
<%
Object sss = request.getAttribute("MyAttribute");
String a = "22";
%>
with simply using EL ${MyAttribute}
But if you want to stick with scriptlets, you should get the attribute from the proper scope which is session in your case.

Print a value using JSP and Expression Language (EL)

I have a servlet, and I want to print some data from the servlet with a JSP file, and I have to use compulsory the Expression Language.
I have this code in the servlet:
String saludo="hi";
req.setAttribute("exito",saludo);
And I have this in my JSP file:
${exito}
And I also tried with this:
${requestScope.exito}
But when I try to see it with my browser (Google Chrome), instead of seeing hi, I see
${exito}
What am I doing wrong?
When you are sending information to the JSP you need to dispacth the current request to the JSP, I try the above code and I don't have any problem, this is my code:
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String saludo="hi";
req.setAttribute("exito",saludo);
req.getRequestDispatcher("MyPage.jsp").forward(req, resp);
}
And this is the code for MyPage.jsp
<%# 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>Title</title>
</head>
<body>
${exito}
</body>
</html>

Sending dynamically generated javascript file

Background:
I have a servlet in which I am dynamically generating javascript and putting into a variable script. Then I set the response content type as text/javascript and send the script over to the client:
resp.setContentType("text/javascript");
resp.getWriter().println(script);
Problem:
The browser does download the javascript file but it doesn't recognize the functions inside the file. If I create a static javascript file and use it instead, it works fine.
Question:
What should be done so that browser treats response from the servlet as a regular javascript file?
Thank you for help.
It should work fine. I suspect that you're just including it the wrong way or calling the function too early or that the response content is malformed.
I just did a quick test:
<!DOCTYPE html>
<html lang="en">
<head>
<title>SO question 6156155</title>
<script src="javaScriptServlet"></script>
<script>test()</script>
</head>
<body>
</body>
</html>
with
#WebServlet(urlPatterns={"/javaScriptServlet"})
public class JavaScriptServlet extends HttpServlet {
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/javascript");
response.getWriter().write("function test() { alert('peek-a-boo'); }");
}
}
and I get
How do you refer to this servlet from your browser ?
If you want to include this with a HTML page (existing one), you should refer to it from the tag of your page.
Ex.
<html>
<head>
<script type='text/javascript' src='URL_TO_YOUR_SERVLET'></script>
</head>
</html>
Or if you want it to be executed as part of a Ajax call, just pass the response to eval function.
Or else, if you just want to send the output and get it executed in browser, you need to send the HTML segment as well. Then include your JS with in the body tags, as a script tag.
ex. Your servlet sends the following, using content type 'text/html' :
<html>
<body>
<script type='text/javascript'>
<!-- write your generated JS here -->
</script>
</body>
</html>
You could always write the script 'in-line' to the web page.
I think this way is better.
<%# page language="java" contentType="text/javascript; charset=UTF-8" pageEncoding="UTF-8"%>
alert('Pure JavaScript right here!');
Set content type in JSP:
contentType="text/javascript; charset=UTF-8"

Categories