How would I pass a form value to a servlet - java

I am fairly new to programming so please bear with me .
I am trying to get values from a form ( in a JSP ) using javascript and do a post request to a servlet . My form has 6 values and I get the values in javascript using
var value 1 = document.getElementByID(" value of a element in the form).value
var value 2 = document.getElementByID(" value of a element in the form).value
etc
my question is I am using a POST request using the javascript Ajax call . How do I combine all these disparate values into a single element which I could then read and assign to a POJO using the POJO'S setter methods in the servlet . I cannot use a JSON because my project cannot use an external library such as Jersey. Any pointers to this would be appreciated .

There are more elegant ways to do this, but this is the most basic. You'll want to combine your javascript variables into a standard post body.
var postData = 'field1=' + value1;
postData += '&field2=' + value2;
postData += '&field3=' + value3;
/* You're concatenating the field names with equals signs
* and the corresponding values, with each key-value pair separated by an ampersand.
*/
If you're using the raw XMLHttpRequest facilities, this variable would be the argument to the send method. If using jQuery, this would be your data element.
In your servlet, you get the values from the HttpServletRequest object provided by the container.
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
MyObject pojo = new MyObject();
pojo.setField1(request.getParameter("field1"));
pojo.setField2(request.getParameter("field2"));
pojo.setField3(request.getParameter("field3"));
/* Now your object contains the data from the ajax post.
* This assumes that all the fields of your Java class are Strings.
* If they aren't, you'll need to convert what you pass to the setter.
*/
}

Related

How can I get the URL paramter dynamically in Java?

A url is hit from browser now I want to get that url in my dataBean to extract its parameters for some checks.
How can I get that URL dynamically in that particular databean?
for instance :
someone hit
https://someAddress/AjaxForm?id=someid
I need to capture this url and get value of Id. How to do it?
you can do something likewise,
request.getRequestURL() // gives your current URL
where request is an instance of HttpServletRequest.
UPDATED :
If you are trying to find parameter which are comes along with URL, then
rather then do above mentioned my trick,
directly do likewise,
request.getParameter("id");
String url=request.getRequestURL()
String id=request.getParameter("id");
To get the parameter from url
request.getParameter("id");
And to insert it, in javascript add the parameter by attaching it to url
var url=baseurl+"?id="+id;
in the doGET method you write
String idValue=request.getParameter("id");
so the method will look like this
protected void doGET(HTTPServletRequest request,HTTPServletResponse response){
//some code here
String idValue=request.getParameter("id");//idValue will hold the value you passed in URL
//some more code here
}

Get JSON data from JAVA component to XWiki apache velocity

What is the best way to get JSON data from a java component in xwiki runnung apache. In my java
component I'm compiling JSONObjects and JSONArrays, I would like to return
this data to my velocity script in JSON format, is this possible?
something like:
{{velocity wiki="false"}}
#if("$!request.outputSyntax" != '')
$response.setContentType('application/json')
#end
#set($map = {})
#set ($rightIN = ${request.rightIN})
#set ($spacenameIN = ${request.spacenameIN})
#set($disgard =$map.add($services.getjsondata.javacomp($spacenameIN,$rightIN)))
$jsontool.serialize($map)
{{/velocity}}
and the Java:
public JSONObject javacomp(String spacenameIN, String rightIN ){
JSONObject obj = new JSONObject();
try {
obj.put("spacenameIN ", spacenameIN );
obj.put("rightIN", rightIN );
} catch (JSONException e) {
e.printStackTrace();
}
return obj;
}
At the end I would like to access this json object as a data return from an
ajax call. Is this possible?
I'm currently returning strings, but this is very inefficient how can I return objects?
In your code above, the Java component returns a JSONObject but then, in Velocity, you try to add that object directly to a map, not specifying any key.
So your velocity code should be changed to:
#set ($map = $services.getjsondata.javacomp($spacenameIN, $rightIN))
...since the JSONObject instance is pretty much a map.
After that, it's perfectly fine to serialize that map to JSON with:
$jsontool.serialize($map)
At the end I would like to access this json object as a data return
from an ajax call. Is this possible?
Sure, just remember to also set the content type of your result in Velocity, so that your ajax call properly interprets the Velocity result as JSON, and not as regular text. To do that you need to do:
#set ($discard = $response.setContentType('application/json'))
I'm currently returning strings, but this is very inefficient how can
I return objects?
Your Java component (script service) always returns objects to the Velocity side (they both execute on the server). It' your choice if those objects are strings or any other data type. You do not really need to handle the JSON serialization in the Java component (you just need to be careful that they are serializable types that $jsontool can handle when it will be called on the Velocity side). On the Velocity side, you do something with those objects and serialize them to JOSN (which is text/strings in the end because that's what the AJAX call needs since JavaScript is executed on the client side).
Additionally, I would suggest you avoid JSONObject altogether and use a regular Map to pass your results to the Velocity side.

Returning multiple sets of data using JSON with Java and JQuery

I want to send sets of data from servlet to the jsp using JSON. To elaborate, what exactly I want to do is take multiple rows from the database and print their values in jsp. I done with the part of DB connectivity and fetching of data. But I could not find a way to forward them to jsp using JSONObject. Each row has multiple attributes(column values). Please help me solve the problem.
What I'm doing is:
Collection <JsonObject> c=new ArrayList();
JsonObject j[] = null;
for(int i=0;i<uid_list.size();i++){//uid_list contains all the user_id's from the database
j[i].add("uid", j[i]);
j[i].add("fname", j[i]);
j[i].add("lname", j[i]);
j[i].addProperty("uid", uid_list.get(i).toString());
j[i].addProperty("fname", fname_list.get(i).toString());
j[i].addProperty("lname", lname_list.get(i).toString());
c.add(j[i]);
}
Also, is there any difference between JsonObject and JSONObject? The latter could not be recognized in servlet and by using JsonObject the put method is not recognized.
Aside from your code trying to insert into an uninitialized array, there are many JSON library for Java. You need to provide more details which one you're using
Also if your objective is just passing the JSON string into the browser, you might not even need jsp, you can just write the string version of the JSON object directly into the HttpResponse
Firstly, the JspnObject array has to be instantiated before it is used. Therefore, this means the following:
JsonObject j[] = new JsonObject[noOfObjects to be iterated]

How should I send the response in Servlet to Front end?

I have written a Servlet something like this
public class ServletUtil extends HttpServlet {
private static final long serialVersionUID = 1571172240732862415L;
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String acInfo = request.getQueryString();
someDao dao = new someDao();
ArrayList<String> resultAutoComplete=dao.someResults(acInfo);
out.close();
}
}
I have an auto complete Object/wizard in front end and as the user types in it is making Ajax call to back end to grab the list of results. So I have written a Servlet and I am pulling the user input and getting my results from DAO layer.
My question here is how should I send this list(resultAutoComplete) to Front end in the Servlet?
I'd expect you to serialise this in some fashion such that the client understands it. e.g. perhaps using JSON or similar.
I note that your response content type is text/html. So why not simply write each element of your list to your Writer out, separated by (say) a <li> element (with the appropriate unordered/order list entities surrounding this)
Try this,
for (String str : resultAutoComplete)
{
out.println(str);
}
By serializing it to a String and writing it to out...
Seriously though, I wouldn't code at the low level Servlet spec. For this kind of return-this-pojo call I would use Spring 3's RESTful service libraries, or something similar.
No json! instead of going through a list in javascript, return a completed <li> lists and replace innerHTML of <ul>.The reason to do so is to give a better performance. Unless you want to do something more flexible, leave things to the back-end.
When do json, you gotta parse string into json object and then loop through and generate html, that's just an extra step. Keep things simple, plus, parsing string could be costly.
If you don't loop through the list and instead do out.println the list object, you would likely see the address. also, you need to generate html, so:
StringBuilder sb = new StringBuilder();
for(String option: options){
sb.append("<li>").append(option).append("</li>");
}
out.println(sb);

How to send parameters from a servlet

I am trying to use a RequestDispatcher to send parameters from a servlet.
Here is my servlet code:
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String station = request.getParameter("station");
String insDate = request.getParameter("insDate");
//test line
String test = "/response2.jsp?myStation=5";
RequestDispatcher rd;
if (station.isEmpty()) {
rd = getServletContext().getRequestDispatcher("/response1.jsp");
} else {
rd = getServletContext().getRequestDispatcher(test);
}
rd.forward(request, response);
}
Here is my jsp, with the code to read the value - however it shows null.
<h1>response 2</h1>
<p>
<%=request.getAttribute("myStation") %>
</p>
Thanks for any suggestions.
Greener
In your servlet use request.setAttribute in the following manner
request.setAttribute("myStation", value);
where value happens to be the object you want to read later.
and extract it later in a different servlet/jsp using request.getAttribute as
String value = (String)request.getAttribute("myStation")
or
<%= request.getAttribute("myStation")%>
Do note that the scope of usage of get/setAttribute is limited in nature - attributes are reset between requests. If you intend to store values for longer, you should use the session or application context, or better a database.
Attributes are different from parameters, in that the client never sets attributes. Attributes are more or less used by developers to transfer state from one servlet/JSP to another. So you should use getParameter (there is no setParameter) to extract data from a request, set attributes if needed using setAttribute, forward the request internally using RequestDispatcher and extract the attributes using getAttribute.
Use getParameter(). An attribute is set and read internally within the application.
In your code,
String test = "/response2.jsp?myStation=5";
You are adding myStation=5 as query string.As the query string parameters are stored
as request parameters in Request Object.
Therefore you can use ,
It works fine.Thanks.

Categories