This question already has answers here:
How should I use servlets and Ajax?
(7 answers)
Closed 1 year ago.
I am trying to create a web application using the MVC design pattern. For the GUI part I would like to use JavaScript. And for the controller Java Servlets.
Now I have never really worked with JavaScript, so I'm having a hard time figuring out how to call a Java Servlet from JavaScript and how to get the response from the Servlet.
Can anybody help me out?
So you want to fire Ajax calls to the servlet? For that you need the XMLHttpRequest object in JavaScript. Here's a Firefox compatible example:
<script>
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
var data = xhr.responseText;
alert(data);
}
}
xhr.open('GET', '${pageContext.request.contextPath}/myservlet', true);
xhr.send(null);
</script>
This is however very verbose and not really crossbrowser compatible. For the best crossbrowser compatible way of firing ajaxical requests and traversing the HTML DOM tree, I recommend to grab jQuery. Here's a rewrite of the above in jQuery:
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
$.get('${pageContext.request.contextPath}/myservlet', function(data) {
alert(data);
});
</script>
Either way, the Servlet on the server should be mapped on an url-pattern of /myservlet (you can change this to your taste) and have at least doGet() implemented and write the data to the response as follows:
String data = "Hello World!";
response.setContentType("text/plain");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(data);
This should show Hello World! in the JavaScript alert.
You can of course also use doPost(), but then you should use 'POST' in xhr.open() or use $.post() instead of $.get() in jQuery.
Then, to show the data in the HTML page, you need to manipulate the HTML DOM. For example, you have a
<div id="data"></div>
in the HTML where you'd like to display the response data, then you can do so instead of alert(data) of the 1st example:
document.getElementById("data").firstChild.nodeValue = data;
In the jQuery example you could do this in a more concise and nice way:
$('#data').text(data);
To go some steps further, you'd like to have an easy accessible data format to transfer more complex data. Common formats are XML and JSON. For more elaborate examples on them, head to How to use Servlets and Ajax?
The code here will use AJAX to print text to an HTML5 document dynamically
(Ajax code is similar to book Internet & WWW (Deitel)):
Javascript code:
var asyncRequest;
function start(){
try
{
asyncRequest = new XMLHttpRequest();
asyncRequest.addEventListener("readystatechange", stateChange, false);
asyncRequest.open('GET', '/Test', true); // /Test is url to Servlet!
asyncRequest.send(null);
}
catch(exception)
{
alert("Request failed");
}
}
function stateChange(){
if(asyncRequest.readyState == 4 && asyncRequest.status == 200)
{
var text = document.getElementById("text"); // text is an id of a
text.innerHTML = asyncRequest.responseText; // div in HTML document
}
}
window.addEventListener("load", start(), false);
Servlet java code:
public class Test extends HttpServlet{
#Override
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException{
resp.setContentType("text/plain");
resp.getWriter().println("Servlet wrote this! (Test.java)");
}
}
HTML document
<div id = "text"></div>
EDIT
I wrote answer above when I was new with web programming. I let it stand, but the javascript part should definitely be in jQuery instead, it is 10 times easier than raw javascript.
I really recommend you use jquery for the javascript calls and some implementation of JSR311 like jersey for the service layer, which would delegate to your controllers.
This will help you with all the underlying logic of handling the HTTP calls and your data serialization, which is a big help.
Sorry, I read jsp not javascript. You need to do something like (note that this is a relative url and may be different depending on the url of the document this javascript is in):
document.location = 'path/to/servlet';
Where your servlet-mapping in web.xml looks something like this:
<servlet-mapping>
<servlet-name>someServlet</servlet-name>
<url-pattern>/path/to/servlet*</url-pattern>
</servlet-mapping>
function callServlet()
{
document.getElementById("adminForm").action="./Administrator";
document.getElementById("adminForm").method = "GET";
document.getElementById("adminForm").submit();
}
<button type="submit" onclick="callServlet()" align="center"> Register</button>
var button = document.getElementById("<<button-id>>");
button.addEventListener("click", function() {
window.location.href= "<<full-servlet-path>>" (eg. http://localhost:8086/xyz/servlet)
});
Related
I get the JSONOject from my bean in my helper class.
Inside helper
public JSONObject init() throws Exception{
// initializations codes are here
JSONObject json = JSONObject.fromObject(bean);
return json;
}
Then I need to access above JSONObject inside a jsp calling through ajax request when loading the jsp(to assign javascript variable like bellow)
inside jsp
$(document).ready(function(){
var VAR_JSON = // need to get the JSON through AJAX
});
previously I had a code like this.
<script type="text/javascript">
var VAR_JSON = <%=helper.init()%>
</script>
how can I achive this by AJAX ?
thanks in advance..!!
First of all, stop thinking JSP. The JSP is (part of) what executes on your server when a request is being handled. That in turn returns a response to the browser (usually a webpage); your JavaScript (and therefore your AJAX request) run in the user's browser on that webpage, not in your JSP.
jQuery provides a function specifically designed for getting JSON through an AJAX request; it's called jQuery.getJSON(). You'd use it something like this:
<script type="text/javascript">
$(document).ready(function() {
var VAR_JSON;
function yourFunction() {
// do something with VAR_JSON here
}
$.getJSON('yoururl.do', function(response) {
VAR_JSON = response;
yourFunction();
});
});
</script>
It's important to note that you can't do var VAR_JSON = $.getJSON() because the function is asynchronous, and therefore doesn't return the JSON (it returns something else - see the documentation linked above). You instead need to provide a callback function that will execute when the asynchronous request returns a successful response, which will then set your variable and call another function that uses it.
Also note that you won't need to call something like JSON.parse() because jQuery does that for you; you've told it you're expecting JSON back so it parses that string to get the resulting object or array, which is then in turn passed as an argument to the callback function.
I am building an Android app and I want to post a html form that looks like this:
<form onsubmit="ShoutBox.postShout(); $('shout_data').value = ''; return false;">
Shout: <input type="text" id="shout_data" size="50"> -
<input type="submit" value="Shout Now!" id="shouting-status"></form>
I am using Jsoup in the rest of the application and I would preferably use it for this aswell.
I know about the .data(name, value) method, but since the html text and button don't have name attributes, that's not working. I can extract the field by using the ids and fill the field with: Element.val(String val); But I don't know how to post the form after that. Can anyone help me?
This is the JavaScript code for posting it:
postShout: function() {
message = $("shout_data").value;
if (message == "") {
return false;
}
$("shouting-status").value = ShoutBox.lang[0];
postData = "shout_data="+encodeURIComponent(message).replace(/\+/g, "%2B");
new Ajax.Request('xmlhttp.php?action=add_shout', {method: 'post', postBody: postData, onComplete: function(request) { ShoutBox.postedShout(request); }});
},
The post is not done via a form submit and post variables but via JavaScript and an XML HTTP request. JSoup is incapable to execute JavaScript. You need a browser that you can remote control. To do this headless in Java HTMLUnit is a good choice.
I'm on a jsp page and I am doing an ajax call to a servlet which in return provides full html code to be displayed on page. It works fine but looks cluttered in servlet file to have multiple printWriter.write(...) lines with html code in it. It becomes hard to maintain as I have to create a large html code via servlet. Is there any other proper/better way to do this? I have cmobination of write html lines and logic in servlet and it will be hard to separate them.
The ajax call in jsp page:
$.ajax({
type: 'POST',
url: 'myServlet',
data: requestData,
dataType: "text",
}).done(function(responseData) {
$(divId).html(responseData);
});
Some code from servlet class:
.....
String username = user.getName();
if (username != null && !username.trim().isEmpty())
username = username.substring(0, username.indexOf(" "));
else
username = "";
printWriter.write("<span id=\"username_"+i+"\" style=\"display: none;\">"+ username +"</span>");
printWriter.write("<form action=\"\" method=\"post\" name=\"userClickForm_"+i +"\" id=\"userClickForm_"+i +"\">");
printWriter.write(" <input type=\"hidden\" name=\"userId\" value=\""+userId +"\"/>");
printWriter.write("</form>");
......
The main reason of mixing html code and business logic is I have to provide div id based on conditions and loop structure.
You should use some form of template or transformation technology. Since you're using jQuery and JSPs this can be either a server-side JSP or a client-side jQuery template plugin.
Early JSP MVC patterns take this form:
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// read inputs
String foo = request.getParameter("foo");
// perform business logic
SomeResults results = new SomeDataSource().lookupDatabase(foo);
// place results into scope
request.setAttribute("results", results);
// dispatch to JSP to render results
request.getRequestDispatcher("result.jsp")
.forward(request, response);
}
This approach can be used with an AJAX call.
Alternatively, you can respond with JSON or XML data and parse this in the JavaScript, then use a JavaScript template engine to do something similar to the logic performed in the JSP.
You can avoid that by using MVC framework like STRUTS or SPRING.
Use xml rather than html on servlet and on jsp use success attribute of ajax call using jquery.... In my case its working, bt i have used type as 'GET'.
$.ajax({
url: ,
data: ,
type: ,
dataType: 'xml',
async: true,
success:function(xmlDoc)
{
var message = xmlDoc.getElementsByTagName("message");
message = message[0].firstChild.data;
}
});
And in Servlet use::
res.getWriter().write("<response><message>abcdefg</message></response>");
You should use JSP's. It will be on different pair of servlet/jsp request, not the request initiating ajax call.
I am new to Java EE programming. Following my understanding on jsp. Corret me if I am wrong
- JSP pages are converted to servlet first then to html and resulted html page is displayed in browser.
Now suppose jsp page is displayed in browser i.e now it is html page and I have a java List which have names or some sort of data that I want to print on the currently loaded page. I can get the List object using ajax but the how will I display it on html as html cant render java collections.
Correct me wherever I misunderstood the flow or basic concepts.
Thanks.
You could use ajax (using jQuery would be easy) to make a call to your Servlet
function callMe(){
$.ajax({
type: "POST",
url: "/someServlet",
data: { param1: "val1" , param2: "val2" }
}).done(function( data) {
//TODO
});
}
Now on Servlet, in doPost(), Use Gson to generate JSON representation for your collection
String parameter1 = request.getParameter(param1);
String parameter2 = request.getParameter(param2);
//call to service to generate the collection
//for example List<Employee>
List<Employee> employees = someService(parameter1, parameter2);
//using google's gson
Gson gson = new Gson();
String json = new Gson().toJson(employees);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(json);
Now we have response in javascript function as a array of javascript objects, So modify it to
}).done(function( data) {
//some processing for display
var len = data.length
for (var i=0; i<len; ++i) {
var employeeFirstName = data[i].firstName;
var employeeLastName = data[i].lastName;
//set it to some DIV, or do the processing you want
}
}
});
Also See
How to call a java method from jsp by clicking a menu in html page?
You need to send the contents of your list as text to the user's browser (which is what normally happens).
A convenient format for transferring the contents of the list between the browser and the server is JSON, due to its simple readability with JavaScript and easy generation on the server.
You can then display the returned text in whatever way you like using JavaScript.
A JSP is compiled into a java servlet class, which can handle HTTP requests. When the servlet is deployed to an application server HTTP requests are passed to the servlet for handling: an HTTP response is generated which normally contains some HTML, a status code, etc.
So it's the java code in the servlet which loops over your list and presumably generates the appropriate HTML to render that list in a browser.
Whether or not it's an AJAX request or not doesn't really matter. Rather than rendering a full HTML page, the AJAX request would probably be handled by a different servlet, which generates only a partial page - perhaps just the <ul><li>...</li></ul> to render your list. The javascript in your HTML page can then take care of updating the user interface by replacing the old version of the list.
I want to send a JSP page which consists of some divs and table as part of AJAX response from spring framework, is there any way to send JSP as a response of AJAX call
Sending JSP by AJAX makes no sense, it is basically the HTML generated by a JSP that is sent over to the browser through AJAX, as rightly pointed out by the lost.
You do not need any server-side coding for this. All you need is to write some JavaScript on client-side to receive your HTML asynchronously. For this, I would recommend using some JavaScript framework like jQuery, otherwise, it would make your life hell.
Assuming that the page you want to access by AJAX has the link http://domain:port/mypage.htm. First you need to include jQuery in your base JSP (JSP in which former page has to load by AJAX):
<script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery.js"></script>
Then you need to call jQuery's AJAX function:
$(document).ready(function(){
$.ajax({
type:"GET",
url: "http://domain:port/mypage.htm",
success: function(data) {
// Now you have your HTML in "data", do whatever you want with it here in this function
alert(data);
}
});
});
Hope it helps!
Yes, there's no magic to this though. In your Java AJAX handler just return a forward or redirect to the JSP page you want. The response will then be available as the responseText in your AJAX callback.
You can use JSP to generate just the elements you need as a sort of incomplete HTML fragment then returns this from your server-side handler. Then in your JavaScript callback you can insert the fragment into your existing HTML like this
element.innerHTML = resp.responseText
//element is the parent you want to insert to
//resp is the parameter supplied to your callback