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.
Related
I have a URL say abc.com/somecontroller?someparam=1 which renders a form. Form on submit sends the form params to /ajaxAction
Is there a way I could get this abc.com/somecontroller?someparam=1 (i.e. the form URL?)
I am more interested in getting the someparam value from the URL of the form.
PS: the above URL abc.com/somecontroller?someparam=1 is dynamically generated, so I can not access it otherwise.
And request.forwardURI will give me /ajaxAction (i.e. the URL of the action in form and not the url of the form itself).
EDIT:
I have no control over form as it is also dynamic and user has hundreds of templates to select from. Each template has different no. of fields.
So if I would prefer some other way to get the URL.
Why don't you use javascript in form and add to ajax request array with GET params? (or with the url of the action which generated form)
You can get them from original request f.e. by this script.
While rendering the GSP of your form, you can do like this:
myaction.gsp
<html>
<body>
<!-- Your content -->
<script>
var paramsString = '${params.collect { k, v-> "$k=$v" }.join("&") }';
</script>
</body>
</html>
So, when you GSP is rendered, the script tag will have something like this (for a URL abc.com/somecontroller?someparam=1&foo=2:
var paramsString = 'someparam=1&foo=2';
Now, in your AJAX code, you can pass that string as the query arguments:
$.ajax({
url: '/ajaxAction?' + paramsString
/* rest of the AJAX code */
});
Now, in your ajax controller action, you can simply do the params.someparam.
EDIT
Well, I just realized that you don't have to any GSP stuff I mentioned above. Simply do the AJAX call like this:
$.ajax({
url: '/ajaxAction' + location.search
/* rest of the AJAX code */
});
The location.search will give you the direct string: ?someparam=1&foo=2
I ended up using flash to store the someparam
In my controller which is being used to render the form at abc.com/somecontroller?someparam=1 I use flash as this:
flash.put("someparam", params.someparam)
This worked as a quick workaround to the issue. I feel this would work well in situations where I have no control over the gsp.
If anyone finds any issue, please comment otherwise I will mark this as the answer.
My problem is kinda weird. I have a JSP page that calls servlet using JQuery/ajax on combobox change. Everything works fine, I get the response but html is displayed as text. Other thing worth mentioning is when I call servlet directly by URL, everything is fine.
Servlet response code:
for(int i=0;i<tabstr.length;i++){
wyjscie.println(i+": "+tabstr[i]+" <br>");
}
JSP ajax call:
$('#com2').change(function() {
$.get('filtr', function(responseText) {
$('#result').text(responseText);
});
});
result is an ID of a DIV inside JSP page. I've done some servlets without ajax in the past and I didn't encounter this problem before. Any idea how to deal with it?
you have to set as html not text try this
$('#result').html(responseText);
I think your server doesn't specify the mime type of the response. So you have to specify it or you can specify dataType in you ajax call.
$.ajax({
url : "myUrl",
dataType : "json",
data : {
param1 : value1,
}
});
ajax api:
dataType: The type of data that you're expecting back from the server. If none
is specified, jQuery will try to infer it based on the MIME type of
the response...
I am new to JQuery. I have a servlet which will fetch data from the database and the result is kept is request and the same result is retrieved in jsp file. Now i have to call the servlet using ajax jquery to load the data. I am doing as below. But it is not loading. Please help me.
$('#myForm #revert').click(function() {
$.ajax({
type: "GET",
url: "./myController",
success: function(msg) {
<span style="color:green;font-weight:bold">Successful</span>');
},
error: function(ob,errStr) {
//Todo
}
});
});
Servlet code:
//Service call gets data and the result is kept in request scope as below
request.setAttribute("myresult", result);
request.getRequestDispatcher("/WEB-INF/myScreen.jsp").forward(request, response);
Thanks!
Ajax is not a normal HTTPRequest,You canot Forward or sendRedirect a Ajax request
Since it is Asynchronous,you need to write the response for Ajax request
PrintWriter out = resp.getWriter();
out.println(resultString);
return;
Please read #Balusc great answer :How to use Servlets and Ajax?
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.
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)
});