Wicket http post, get raw data from servletrequest? - ajax

I try do POST some data to a Wicket WebPage. This works fine if the data is in a form. However, I want to post the data with jQuery's ajax-post. I am unable to get this data in my Page-constructor.
This is my jquery command:
$.ajax({
type: "post",
cache: false,
url: "http://localhost:8888/testjson",
data: JSON.stringify({"aap":"noot"),
contentType: 'application/json',
success: function(ydata){alert("aap");},
failure: function(errMsg) {alert(errMsg);},
contentType: false,
dataType: "json"
});
The /testjson is a mounted WebPage.
public TestJsonApiPage( PageParameters pp )
{
try
{
byte[] data = IOUtils.toByteArray( ( (ServletWebRequest) TestJsonApiPage.this.getRequest() ).getContainerRequest().getInputStream() );
}
catch ( IOException e )
{
// TODO Auto-generated catch block
e.printStackTrace();
}
This is the constructor. What I see happening is that the inputstream is empty. However, when debugging, I see the raw data that I posted in HttpServletRequest in the newWebRequest in my WicketApplication
tl;dr How to get the raw post data in Wicket Page?

It seems Page does something to the post-parameters.
The solution for my problem is to use a Resource.
public class MyResource extends AbstractResource
#Override
protected ResourceResponse newResourceResponse( Attributes attributes )
{
ResourceResponse resourceResponse = new ResourceResponse();
resourceResponse.setContentType( "text/json" );
resourceResponse.setTextEncoding( "utf-8" );
HttpServletRequest request = (HttpServletRequest) attributes.getRequest().getContainerRequest();
try
{
this.json = IOUtils.toString( request.getInputStream() );
}
catch ( IOException e )
{
e.printStackTrace();
}
resourceResponse.setWriteCallback( new WriteCallback()
{
#Override
public void writeData( Attributes attributes ) throws IOException
{
OutputStream outputStream = attributes.getResponse().getOutputStream();
Writer writer = new OutputStreamWriter( outputStream );
writer.write( MyResource.this.json );
writer.close();
}
} );
return resourceResponse;
}

Related

How to code an Android Volley JSONArrayRequest PUT returning JSON Object

I am using android volley JSONArrayRequest with PUT to create a new version of an item on my remote server using the following code
JsonArrayRequest jsonRequest = new JsonArrayRequest
( Request.Method.PUT
, ServerItemUpdateUrl + RemoteId + "/" + VersionNumber
, jsonArray
, new Response.Listener<JSONArray>()
{
#Override
public void onResponse(JSONArray response)
{
Log.d(TAG,"Comms Success :" + response.toString());
}
}
, new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error)
{
Log.i(TAG,"Comms Error :" + error.toString());
}
}
)
{
#Override
public String getBodyContentType()
{
return ServerItemContentType ;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError
{
Map<String, String>
params = new HashMap<String, String>();
params.put("Authorization", AuthorizationPrefix + token);
params.put("Content-Type", ServerItemContentType);
return params;
}
};
ServerHttpRequestQueue.add(jsonRequest);
However the server returns a JSON object (basically confirming where the data has been put) and this causes a com.android.volley.ParseError with org.json.JSONException, perhaps not surprisingly as it is expecting a JSON array to be returned. I have tried setting the listener to null and this does not remove the error.
Please can someone tell me how I can change Response.Listener to accept a JSON Object?
Many thanks
To do this you need to use the code below in order to override the default Array parsing response behaviour and allow it to parse an object. This code is inserted inside the anonymous inner class shown in the OP, i.e. after "return params;}"
protected Response<JSONArray> parseNetworkResponse (NetworkResponse response)
{
try {
String jsonString = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
Log.i(TAG, "Comms Response " + jsonString);
return Response.success(new JSONArray("["+jsonString+"]"), HttpHeaderParser.parseCacheHeaders(response));
}
catch (UnsupportedEncodingException e)
{
return Response.error(new ParseError(e));
}
catch (JSONException je) {
return Response.error(new ParseError(je));
}
};
Note the enclosing "[" and "]" which effectively translate the string from a representation of a json object to one representing a json array with a single element containing the returned json object.
Tested and working.

Issue with spring boot post call. Unable to call controller from client side

I am bit new to spring boot and I have developed the following logic:
Here is my requirement. Just I wanted to upload images to tomcat server for that I have tried this logic with spring boot
#SpringBootApplication
public class MyApplication {
public static void main(String[] args) throws IOException {
new File(UploadController.uploadDir).mkdirs();
SpringApplication.run(MyApplication.class, args);
}
}
#RestController
public class UploadController() {
#RequestMapping("/test")
public String get(Model model) {
return "abc";
}
#RequestMapping(value = "/upload", method = RequestMethod.POST)
public String uploadFiles(#RequestParam("uploadedFiles") MultipartFile[] uploadedFiles) throws IOException {
for(MultipartFile f : uploadedFiles) {
File file = new File(uploadDir + f.getOriginalFilename());
f.transferTo(file);
}
return "redirect:/";
}
}
Here, get request is working fine. Here is the code for get
public static String get() throws IOException {
HttpURLConnection conn = null;
BufferedReader br = null;
try {
URL url = new URL("http://localhost:8080/test");
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
if (conn.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
}
br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
return br.readLine();
} catch (MalformedURLException e) {
throw new IOException(e.getMessage());
} catch (IOException e) {
throw new IOException(e.getMessage());
} finally {
if (null != conn) {
conn.disconnect();
}
if (null != br) {
br.close();
}
}
}
But I am not sure how can I call post method. I tried with same logic with POST as request type. BUt not able to upload the images. Can anyone post me the code for upload from client side?
With JSP and Javascript, code will look like below:
JSP code:
<input name="media[]" type="file" id="xmlTemplate" multiple>
Javascript code:
var data = new FormData();
jQuery.each($('input[name^="media"]')[0].files, function(i, file) {
data.append("uploadedFiles", file);
});
var json = '{' + .... + ']}';//Some JSON I was also passing alongwith files
data.append('estimateInfo', new Blob([json], {
type: "application/json"
}));
$.ajax({
type : "POST",
processData: false,
dataType: 'json',
data: data,
cache: false,
contentType: false,
url: 'createEstimates',
success: function(result) {
},
error: function(result) {
}
});
Controller code:
#RequestMapping(value = "/createEstimates", method = RequestMethod.POST, consumes = { "multipart/form-data" })
#ResponseBody
public EstimateResponse createEstimates(HttpServletRequest request,
#RequestPart("estimateInfo") EstimateInfo estimateInfo, #RequestPart("uploadedFiles") MultipartFile... files) {
}
If you want to send from Java client, then you can refer to Upload Files Programmatically

Spring HttpRequestHandler + XMLHttpRequest

i have a problem HttpRequestHandler does not receive any data when i send post data by javascript. i want to receive value of content, but it does not work.
Here is javascript code:
function utils_saveElementAndGetId(url,content) {
var xhr = new XMLHttpRequest()
xhr.open("post", url, false);
xhr.send(content);
if (xhr.status != 200) {
alert(xhr.status + ': ' + xhr.statusText)
} else {
return xhr.responseText
}
}
here is code of HttpRequestHandler:
public class HeaderServlet implements HttpRequestHandler {
private static final Logger log = LoggerFactory.getLogger(HeaderServlet.class);
TemplateDao templateDao;
HeaderElementDao headerElementDao;
CheckboxElementDao checkboxElementDao;
#Autowired
public HeaderServlet(TemplateDao templateDao, HeaderElementDao headerElementDao, CheckboxElementDao checkboxElementDao) {
this.templateDao = templateDao;
this.headerElementDao = headerElementDao;
this.checkboxElementDao = checkboxElementDao;
}
public void handleRequest(HttpServletRequest req,
HttpServletResponse resp)
throws ServletException, IOException {
String content = req.getParameter("content");
HeaderElement headerElement = new HeaderElement(content);
Long templateId = (Long) req.getSession().getAttribute("id");
Template template = templateDao.get(templateId);
headerElement.template = template;
headerElementDao.create(headerElement);
template.headerElements.add(headerElement);
templateDao.saveOrUpdate(template);
resp.setStatus(200);
resp.setContentType("text/plain");
resp.getOutputStream().println(headerElement.getId());
resp.flushBuffer();
}
}
I have solved the problem , the problem was in javascript side , i have just forgot to add xhr.setRequestHeader("Content-Type",
"application/x-www-form-urlencoded");

Spring:Writing image from GridFS to jsp view

I am using GridFS to store images. Now I want to write stored image to spring view page directly I have tried a lot, but not succeded. I can write image to my local system by using
gfs.writeTo("my location of local directory");
but how can I write same image to JSP view in spring? Any help is appreciated.
This is worked for me
Serve method:
#Override
public void serveImage(String imageId , HttpServletResponse response ) {
InputStream is = null;
ApplicationContext ctx = new AnnotationConfigApplicationContext(MongoDBConfiguration.class);
GridFsOperations gridOperations = (GridFsOperations) ctx.getBean("yourBeanName");
List<GridFSDBFile> result = gridOperations.find(new Query().addCriteria(Criteria.where("_id").is(imageId)));
for (GridFSDBFile file : result) {
try {
response.setHeader("Content-Disposition", "inline; filename=image.jpg");
response.setContentType("image/jpg");
response.setContentLengthLong(file.getLength());
is = file.getInputStream();
IOUtils.copy(is, response.getOutputStream());
response.flushBuffer();
} catch (java.nio.file.NoSuchFileException e) {
response.setStatus(HttpStatus.NOT_FOUND.value());
} catch (Exception e) {
response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
}
}
}
Html code:
<image>
<source th:src="#{/get/${imageId}}" type="image/jpg">
</image>
Controller class:
#RequestMapping(value = "/get/{imageId}", method = RequestMethod.GET)
public void handleFileDownload(#PathVariable String imageId, HttpServletResponse response) {
try {
vaskService.serveImage(imageId, response);
} catch (Exception e) {
response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
}
}

sending Json from servlet to javascript [duplicate]

This question already has answers here:
How should I use servlets and Ajax?
(7 answers)
Closed 2 years ago.
I am trying to send an json object array from a servlet to javascript .where I all get the array and parse .
my ajax call the servlet appropriately but unable to recieve the json array at the javascript end
please help
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException {
System.out.println("Post!!");
response.setContentType("application/json");//since sendign jsonArray toString
PrintWriter out = response.getWriter();
try {
Marker marker=new Marker( 40.72318,-74.03605);//
JSONArray arrayObj=new JSONArray();
arrayObj.add(marker);
System.out.println(marker.toString());
out.print(arrayObj);
} finally {
out.flush();
out.close();
}
}
This is my ajax call in javascript where I am trying to get the json object array form the servlet.
$.ajax({
url:'test',
dataType:'json',
type:'POST',
success:function(data){
<%System.out.println(" success");%>
console.log(data);
alert('got json hopefully');
alert(data);
//
},
error:function(jxhr){
<%System.out.println(" faliure");%>
console.log(jxhr.responseText);
}
});
This worked for me, below is ajax code.
$.ajax({
type : 'POST',
url : "URL",
data: {array: array},
success : function(response)
{
alert("Success "+response.message);
},
error : function(response)
{
alert("Error"+response.message);
console.log('Error');
}
});
Servlet:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
String[] array = request.getParameterValues("array[]");
request.setCharacterEncoding("utf8");
response.setContentType("application/json");
ArrayList<String> message = new ArrayList<String>();
message.add("response message goes here");
PrintWriter writer = response.getWriter();
JSONObject obj = new JSONObject();
obj.put("message",message);
response.setStatus(200);
//System.out.println(obj.get("message"));
writer.append(obj.toString());
writer.close();
}
For more details refer here
This is how I make requests to the servlet and respond back with json. I use google GSON library for java and I advise you use it too. https://code.google.com/p/google-gson/
$.ajax({
url: 'servletName', //the mapping of your servlet
type: 'POST',
dataType: 'json',
data: $('#someForm').serialize(),
success: function(data) {
if(data.isValid){
//maybe draw some html
}else{
//data is not valid so give the user some kind of alert text
}
}
This is the servlet
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String someInput = request.getParameter("someInput");
Map map=new HashMap();
if(someInput!=null){ //or whatever conditions you need
map.put("isValid",true);
map.put("someInput",someInput);
}else{
map.put("isValid", false);
}
write(response,map);
}
private void write(HttpServletResponse response, Map<String, Object> map) throws IOException {
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(new Gson().toJson(map)); //this is how simple GSON works
}
I hope this is clear. If not, ask me in the comments.

Resources