Integrating JavaScript with Java Backend - java

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>

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>

null request response in simple jsp file

I am trying to just set up a very basic jsp file that takes in a query from a url and displays it. I have the following test.jsp file that I run on the server:
<%# 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>Test jsp</title>
</head>
<body>
<% String firstName = (String) request.getAttribute("firstName");
out.println("Hello :" + firstName);%>
</body>
</html>
However, when I type in the following URL, I still get a "null" result (even after refreshing): see Picture.
Note: my ultimate goal is to do have an event at some point that sends a POST request from a java file and display its result in the jsp page. If I understood well from my research, I would have to do it via a Servlet with a DispacherRequest forwarding method. But I first want to understand why the simple aforementioned code isnt working).
Thank you for your help !
You mention that you're trying to display a query parameter from the URL. A query or request parameter is not the same as a request attribute.
To get a query parameter, you would have to use the getParameter() method:
String firstName = request.getParameter("firstName")

Send data from servlet to jsp using ajax [duplicate]

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

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>

Categories