How to send integer as parameter to servlet using $.ajax get? - java

I need to obtain an attribute from my Model project from my web application using java, but i need to send and integer as a parameter as well. I read the JQuery API Doc, but I'm very new to AJAX and JQuery and I still find it difficult to understand.
This is my code:
$(document).ready(function () {
// Locate HTML DOM element with ID "somebutton" and assign the following function to its "click" event...
$.get('ServletControlB', function (responseText) { // Execute Ajax GET request on URL of "someservlet" and execute the following function with Ajax response text...
$('#divnombre').text(responseText); // Locate HTML DOM element with ID "somediv" and set its text content with the response text.
});
});
This is my ServletControlB doGet function:
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
int x; // x = parameter recieved from AJAX
//data is an instance from the Model class
String text = data.getNews().getNewsInPosition(x).getTitle(); //I send correct postition to my ArrayList
response.setContentType("text/html"); // Set content type of the response so that jQuery knows what it can expect.
response.setCharacterEncoding("UTF-8");
response.getWriter().write(text);
}
How can I solve this problem? Is there a better way to approach this problem?

Try to use data object of jquery.get() like,
$(document).ready(function () {
$.get('ServletControlB',{id:1}, //<-- data object having id as key
function (responseText) {
$('#divnombre').text(responseText);
});
});
And in java use,
int x = Integer.parseInt(request.getParameter("id"));

You can parse the request parameter received as String to an Integer.
String x = request.getParameter("yourParameterName"); //get the parameter as String
int x1 = Integer.parseInt(x); //set the parameter here

As you are sending a GET request from jquery, so append query param in URL:
$.get('ServletControlB?yourparam=paramValue', function (responseText)
and you can retrieve in servlet doGet as mentioned here:
String yourParamValue = request.getParameter("yourparam");

$(document).ready(function () {
// Locate HTML DOM element with ID "somebutton" and assign the following function to its "click" event...
$.get('ServletControlB?x=' + valueOfX, function (responseText) { // Execute Ajax GET request on URL of "someservlet" and execute the following function with Ajax response text...
$('#divnombre').text(responseText); // Locate HTML DOM element with ID "somediv" and set its text content with the response text.
});
});
in your controller do the following
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
int x = request.getParameter("x").toString() ;
//data is an instance from the Model class
String text = data.getNews().getNewsInPosition(x).getTitle(); //I send correct postition to my ArrayList
response.setContentType("text/html"); // Set content type of the response so that jQuery knows what it can expect.
response.setCharacterEncoding("UTF-8");
response.getWriter().write(text);
}

I think you will have to change your front end like below.
$.get('ServletControlB',{ param: '1' }, function (responseText) {
$('#divnombre').text(responseText);
});

Related

Render HTML response from remote call to the client

I have a working servlet wich originates back from this template:
http://www.objectdb.com/tutorial/jpa/eclipse/web/servlet
So the basic rountrip works.
I added a new feature where I POST data to the servlet, construct a call/request out of the data to a remote http server, retrieve the response-html-string (the content of the website I requested) and want to show this HTML String now as response to my original POST call.
I tried it like this:
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,
IOException {
boolean showDetails = Boolean.valueOf(request.getParameter("showDetails"));
if (showDetails) {
String details = detailsLoader.loadDetails(String.valueOf(request.getParameter("value1")),
String.valueOf(request.getParameter("value2")));
response.getWriter().println(details);
response.getWriter().flush();
response.getWriter().close();
return; // <----------------- if showDetails then this is the end of doPost
}
// Display the list of guests:
doGet(request, response);
}
When I press the link that creates the POST event I see in the logfile, that "loadDetails" has succesfully loaded the content from the remote server, but the browser window does not refresh. Why?
PS: a simple redirect to the other side is not possible for technical reasons.
Try making a ajax request to your servlet which gives to html content as string sent it back to ajax call and set it to innerHTML of a div element.
I changed to use GET instead of POST and I used a separate Servlet for this kind of call. This solved my problem.
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String details = detailsLoader.loadDetails(String.valueOf(request.getParameter("value1")),
String.valueOf(request.getParameter("value2")));
response.getWriter().println(details);
response.getWriter().flush();
response.getWriter().close();
}

Server Sent Event HTML5 error(the resource from this url is not text)

I wrote this Servlet:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
response.setContentType("text/event-stream;charset=UTF-8");
response.setHeader("Cache-Control","no-cache");
PrintWriter printWriter=response.getWriter();
printWriter.write("Hello!");
}
and also this java script in index.jsp:
<script>
var resource = new EventSource("/servlet");
resource.onmessage = function (e) {
document.getElementById("container").innerHTML = e.data;
}
</script>
in order to create demo on server-sent events in html5. I inspected the jsp page in firefox and I got this error: the resource from this url is not text and nothing shows up. by the way request status is 200, OK. What is wrong with that?
Try to change the response header
response.setContentType("text/event-stream");

How to redirect/forward request to another jsp page in servlet called by $.ajax() function

I am using $.ajax() function to call servlet in my application and i am forwarding request to anothor jsp page and setting request attribute.....I just want to know is it good approach to forward request and setting request parameter in ajax based servelt?
Here is my sample code.....
var id= $("#id").val();
$("#add-btn").click(function(e) {
e.preventDefault();
var dataString ='action=insert'+'&id='+id
console.log(dataString);
$.ajax({
type: "POST",
url: "RecordHandler",
data: dataString,
success: function(data){
console.log('Add');
$('body').html(data);
$('body').prepend('<div style="width:100%;text-align:center;"><h3 style="color:green" >Record Added Succesfully</h3></div>')
}
});
});
and here is my servlet code......
private static String UserRecord = "/list.jsp";
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
String redirect = "";
String action = request.getParameter("action");
if (action.equalsIgnoreCase("insert")) {
String id= request.getParameter("id");
int uid = Integer.parseInt(id);
RecordBean record = new RecordBean();
record.setId(uid);
dao.addRecord(record);
redirect = UserRecord;
request.setAttribute("records", dao.getAllRecords()); //Is it good approach to set request attribute in ajax based servlet?
System.out.println("Record Added Successfully");
RequestDispatcher view = request.getRequestDispatcher(redirect);//Is it good approach to redirect request in ajax based servlet?
view.forward(request, response);
}
How to do it using ajax without refreshing page......
even i use window.location.herf="list.jsp" in ajax success method it is refreshing page
When you call a servlet via AJAX, you stay on the same page by definition, regardless of the headers sent by the server.
If you want to change the page, you must do it with javascript, in the success handler function for the $.ajax(..) call.
You can read the Location response header and set the window.location.href to that value. See here for other options.

transfer data to a servlet from a jsf page

I have an input in my jsf page like this
<html:inputText id="ResponseOK" value="#{bean.ResponseOK}" binding="#{bean.ResponseOKInput}" />
I want to get the value in a servlet (by request.getParameter ("ResponseOK")) when i click on a command button
<html:commandButton value="Valider" action="#{bean.callServlet}"/>
which call a function
public void callServlet()
{
String url = "http://localhost:8080/TestOne/Timers"; //servlet
FacesContext context = FacesContext.getCurrentInstance();
try {
context.getExternalContext().redirect(url);
}catch (Exception e) {
e.printStackTrace();
}
finally{
context.responseComplete();
}
}
Unfortunately, in my servlet the variable Ok , return only null
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String Ok = request.getParameter("ResponseOK");// return null
System.out.println(timerOk);
}
thank you very much
In order for you to be able to get a property from the request, the input must have the name attribute:
<html:inputText id="ResponseOK" value="#{bean.ResponseOK}" binding="#{bean.ResponseOKInput}" name="ResponseOK"/>
UPDATE:
I'm not too familiar with the JSF framework but i think your problem is the action button.
This button is not a submit button so the value of the input is not being sent to the request.
When calling a GET request, you need to pass the parameter in URL itself, so you need the url to look like:
http://localhost:8080/TestOne/Timers?ResponseOK=value
So you need to transfer the value of the ResponseOK input to the callServlet method.
Hope that helps.

How to pass a value of a variable from a java class to the jsp page

I have 2 files named Admin.java and index.jsp.
In Admin.java through a function I retrieve the value of the varible named res. This variable needs to be passed to a JSP page.
The Admin.java is in C:\Users\praveen\workspace\SemanticWeb\src\controller whereas the index.jsp is in C:\Users\praveen\workspace\SemanticWeb\WebContent.
The code of Admin.java is:
public Admin()
{
super();
}
protected void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException
{
if (action.equals("login"))
{
String userName="";
String password="";
userName = request.getParameter("username");
password = request.getParameter("password");
response.setCharacterEncoding("UTF-8");
SemanticSearch semsearch = new SemanticSearch(request.getSession());
semsearch.loadData(REALPATH + RDFDATASOURCEFILE1);
String res=semsearch.searchForUser(userName, password);
System.out.println("The value of res been passed is "+res);
request.setAttribute("rest", res);
return;
}
The code of index.jsp is
function login(user, pass)
{
$.ajax({
type:"GET",
url: "Admin?action=login",
dataType: "text",
data: { username: user, password: pass },
success: function(response){
}
within the
function(response)
{
......
}
I need to access the value of res passed by Admin.java. I am not able to get any proper help for my code on the Internet. Please can someone help me with this.
From your code,
request.setAttribute("rest", res);
You shouldn't set it as request attribute. Setting request attributes is only useful if you're forwarding to a JSP file. You need to write it straight to the response yourself. Replace the line by
response.getWriter().write(res);
This way it'll end up in the response body and be available as variable response in your JS function.
See also:
How to update current page by Servlet/Ajax?
Seems like you're doing AJAX, so I'd say your response would need to be encoded in an AJAX-compatible way (JSON, XML, ...).
If you do AJAX-encoding, your function might look like this:
function(response)
{
var toplevel = response.<your_top_level_element>;
}
Edit:
We're using JSON Simple for JSON encoding.
Our Java backend then looks like this (simplified version without error checking):
public String execute()
{
JSONObject jsonResult = new JSONObject();
jsonResult.put( "result", "ok");
return jsonResult.toJSONString();
}
And in the Javascript function:
function(response)
{
var result = response.result; //now yields "ok"
}
If this is an ajax request, you can forward the request into another jsp page rather than return. With this
getServletContext().getRequestDispatcher("/ajax.jsp").forward(request, response);
create the jsp page(ajax.jsp) on your webcontent and add this sample code.
<p>${rest}</p>
<!-- Note: You can actually design your html here.
You can also format this as an xml file and let your js do the work.
//-->
Another way is replace your System.out.println with this
PrintWriter out = response.getWriter();
out.print("The value of res been passed is "+res);
but I guess this is a bad practice. See example here.

Categories