I have a servlet to which I am posting data from ajax(jquery) call.
$('form').submit(function() {
var URL = "ProjectHandler";
var dataString=$(this).serialize();
$.ajax({
type: "POST",
url: URL,
data: dataString,
// dataType: json,
success: function(data)
{
alert(data.error);
}
});
return false;
});
I have commented dataType beacause when I uncomment it, it doesnt make ajax call, rather, the form is submitted with default mode i.e. the servlet is loaded
JAR's I have added to the project 1. json-lib-2.2.2-jdk15.jar 2. apache-commons-lang.jar 3. ezmorph-1.0.jar
first it threw exception filenotfound which was part of apache-commons package so included apache commons, after that I got exception of filenotfound which was part of ezmorph-1.0.jar, so I added that also. Now I am getting
java.lang.ClassNotFoundException: org.apache.commons.logging.LogFactory
Code in servlet doPost:
response.setContentType("application/json");
PrintWriter out = response.getWriter();
JSONObject json = new JSONObject();
json.put("error", true);
json.put("errorDesc", "wrong title");
out.print(json);
I hope I have cleared the scenario, any help would be appreciated.
Thanks
It looks like you are missing the commons-logging.jar. Add it to your classpath.
Can you drop json-lib? If yes do it! Honestly there is no reason to use this library...the fact that it requires you to add tons of dependencies prooves it.
I would suggest you try Genson library http://code.google.com/p/genson/. It has the advantage to be easy to use but powerfull, extensible, all in one and fast.
It would allow you to deserialize/serialize directly to pojos, no need to use all those JsonObject/Arrays... You can also directly use its streaming API if you need something close to manual json in term of performances.
Related
in my project i would want to implement a plugin for JMeter.
So currently I am stuck at sampler - postprocessing step.
#Override
public void postProcessSampler(HTTPSamplerBase sampler, SampleResult result)
{
super.postProcessSampler(sampler, result);
String postData = sampler.getPropertyAsString(HTTPSamplerBase.ARGUMENTS);
// ...
// apply some operations to postData
// ...
//
// try to write it back to sampler : approach1
// sampler.removeProperty(HTTPSamplerBase.ARGUMENTS);
// sampler.addNonEncodedArgument(HTTPSamplerBase.ARGUMENTS, postData, "");
// Fails
}
So at the postprocessing step i would like to change the request body, whcih is usually stored in HTTPSamplerBase.ARGUMENTS property. However, somehow i cannot set anything to this field. Redefining it with another string gives me a class cast error. If I try operating with strings, then i get invocation exception...
So my question is, what is the correct way to change the sampler's post body?
Regards and thank you
Try out HTTPSamplerBase.getArguments() function instead, example code:
sampler.getArguments().removeAllArguments();
sampler.addNonEncodedArgument("foo","bar","");
sampler.setPostBodyRaw(true);
Also be aware that for this form of post-processing you don't even need to come up with a plugin, all can be done via JSR223 PostProcessor and Groovy language. The above code should work just fine
I'm new to JAX-RS and having a number of issues (which oddly make me miss SOAP). Here is a snippet of my code. The getMergedPDFReport method should take a file and return a file after some processing. After which I would worry about the client
#GET
#Produces("application/pdf")
#Path("merge-service")
public Response getMergedPDFReport(#QueryParam(ApiParameters.WORD_DOCUMENT) File wordDocument,
#QueryParam(ApiParameters.MERGE_FIELDS)Object[] fieldNames,
#QueryParam(ApiParameters.MERGE_VALUES) Object [] fieldValues) {
ResponseBuilder builder =null;
try {
File product = DocumentUtil.generatePDF(wordDocument, fieldNames, fieldValues);
builder = Response.ok(product);
builder.header("Content-Disposition", "attachment; filename=\\\"report.pdf\\\"");
} catch (Exception e) {
e.printStackTrace();
}
return builder.build();
}
I get a warning on my server log that says "No injection source found for a parameter of type public javax.ws.rs.core.Response". I can't seem to know why.
2. Am I using the #QueryParam annotation right? Should I be using it for types of File, and arrays? I saw a lot of debates online over #BeanParam, #MatrixParam and #QueryParam. Since I didn't know what the first two do, I decided to Keep It Simple.
Any help would be appreciated.
I think you can't use queryParam for files. You must use a #Consumes with a multipart form.
Check this :
http://www.javatpoint.com/jax-rs-file-upload-example
I am unable to get the string response from the java function to the ajax call. I am using structs2 . I have wrote a java function that returns a string. the function works properly. but there are some unknown error in the ajax call.
following is my jquery ajax call
<pre>
function saveMyId(){
$.ajax({
url : contextPath+'/action/setMyId',
data: {
myCode:$("#myCode").val(),
myId:$("#myId").val()
},
type : 'post',
async: false,
success : function(data) {
alert(data);
if(data=="success"){
$( "#dialog" ).dialog("close");
$('#myId_Validator').text("");
}
else{
$("#myId").val("");
$("#myId_Validator").val("ID Already exists. Please Choose different one")
}
},
error: function (request, status, error) {
alert("Something went wrong. Please try again later");
}
});
and my java function is
public String setMyId() throws SQLException {
IdAllocationVO idAllocationVO = new IdAllocationVO();
MyIdServices myIdServices = new MyIdServices();
logger.debug("set My Id , myCode :"+this.myCode);
idAllocationVO.setMyCode(myCode);
idAllocationVO.setMyId(myId);
int response= myIdServices.getMyIdCount(myId);
System.out.println("response:"+response);
if(response==0){
myIdServices.setSenderId(idAllocationVO);
return "success";
}
else{
return "fail";
}
}
I am using structs 2
and the structs.xml tag is
<action name="setMyId" class="com.id.myIsservice.struts.IdAction" method="setMyId">
</action>
The function setMyId() is working correctly. I have checked everything by printing each line. But my issue is the ajax call gets the result as an error. so it alerts the error message "Something went wrong. Please try again later". Why it is so?
there are three steps you can try to use for finding the reason:
1、If your ajax call is correct?
firebug or other page dubugger can show you~
2、When the 1st step is correct, check the java function to see if it gets the request from page and responses the right result to page
IDE debug tools will help you~
3、Check what results are got by page
through firebug you can see the response details, like 'status' and others..., findout if the string has been got~
PS:
I see, your java code throw exceptions directly without using try/catch. It's not a good way for users' use~ I suggest you to add try/catch code, with whith maybe help you find error quicker~
Good Evening, I try to do a checkbox which embedded in a JSP page. I use document.getElementByID("checkbox") in the JSP javascript function. How to pass the variables in the javascript function to another java file without passing it through url for security concern?
This is Checkbox Function:
var checkbox = document.getElementById("chbx");
function foo(){
if(checkbox.checked=true){
//passThisVariableToAnotherJavaFile-isChecked
}
else {
//passThisVariableToAnotherJavaFile-isNotChecked
}
};
This is Java File:
public class CheckBoxEvent{
if(isChecked) {
//then whatever
} else if (isNotChecked) {
//then no whatever
}
}
I am a newbie is this jsp stuff, I used to be doing this in PHP but everything mixed-up in my mind when there is a HashMap appear in the java file. Well, need some hints and help.
Thank You
How to pass the variables in the javascript function to another java file without passing it through url for security concern?
You have two options here and in both the cases you need to send the value to the server for processing :
An AJAX POST or GET request. This looks more appropriate to your requirement. You can get an example here.
Submit the form using POST.
Read here When do you use POST and when do you use GET?
In both the cases , there will be a Servlet/JSP/Controller handling the request in the server. You can call the methods in your Custom Java class with the request parameters.
when you do var checkbox = document.getElementById("chbx"); you are doing it at client side. Now if you want to propagate this value to server side i.e to some java class(most of the cases it will be servlets) then you have two options:-
1)Make an AJAX call. (You can also use jquery here to make AJAX call).Here is
the small example, you can find ample on google
$.ajax({
type: 'GET',
dataType: 'json',
url: servlerURL,
success: function(reply) {
},
error: function (xhr, textStatus, errorThrown) {
}
});
or
2)Submit the form
I'm used to do ROR, but I need to make a RESTfull WebService in a Java environnement. So I decided to try it with Play! since it really look like a great idea.
So I'm trying to find a way to add JSON to my already existing firstapp done following those instruction : http://www.playframework.org/documentation/2.0.3/JavaTodoList
What I want is something working similarly to ROR. At least, I want to be able to ask for JSON support by :
calling a .json URL
using "Accept: application/json" Header
So I tried some dirty thing like that :
JsonNode json = request().body().asJson();
if(json != null) {
return ok(Json.toJson(Task.all()));
}
return ok(
views.html.index.render(Task.all(), taskForm)
);
And it's obviously not working right now...
I need to detect wich type the client is requiring. I saw some people were adding dirty routes like that :
POST /bars BarController.index()
GET /bars.json BarController.indexJSON()
But it will clearly not support client using header to specify json request...
So, what I need is some kind of way to find out if there is any Header specifing content-type or Accept application/json. If it is so, BarController.index() would return BarController.indexJSON()...
All in all, it would be pretty much similar to ROR wich do :
respond_to do |format|
format.html # index.html.erb
format.json { render json: #bars }
end
All in all :
Does anyone have gone through the same reasoning than me and had reach an end ?
So I resolved my problem by using to function in controller, like this :
public static Result index()
public static Result indexJSON()
Then I added routes :
GET /tasks controllers.TaskController.index()
GET /tasks/json controllers.TaskController.indexJSON()
I would have preferred task.json but it wouldn't have allowed /tasks/:id.json ...
And for Header support, you need to check in your classic function if there is no header :
public static Result index() {
if (request().getHeader(play.mvc.Http.HeaderNames.ACCEPT).equalsIgnoreCase("application/json") || request().getHeader(Http.HeaderNames.CONTENT_TYPE).equalsIgnoreCase("application/json")) {
return indexJSON();
}
else {
return ok(
views.html.index.render(Task.all(), taskForm)
);
}
}
End that's all folks !
Does anybody have a better solution ? I don't like this one very much... Because I'm going to repeat many code ...