Pass and Get Json String to Spring Controller - java

I want to pass and Get Json String From Controller.
I want to call controller by passing json String and also want to get json String at Controller.
Is there any way to do this.
I have 2 values in my url parameter :: api=asdf23&&jsonstr={"name":"myname","age":"20"}
How can i get these two parameters at controller
#RequestMapping(value = "/GetJSON", method = RequestMethod.GET, produces = "application/json")
public #ResponseBody String GetJSON(
HttpServletRequest request, HttpServletResponse response,
#RequestParam(value = "api") String apiKey,
#RequestParam(value = "jsonstr") String json)
throws ParseException {
System.out.println("JSON :: "+json);
return json;
}

I would recommend not using URL parameter to pass the whole JSON object, rather use POST method and put JSON in the body. However, if you have reasons to use GET with json as url parameter, take help from this link to encode Http URL properly.
For your case, your JSON object will look like this:
api%3Dasdf23%26jsonstr%3D%7B%22name%22%3A%22myname%22%2C%22age%22%3A%2220%22%7D

Create a pojo having 2 properties name and age
public class Test{
private String name;
private Integer age;
//getter and setters
}
then modify your controller to accept json in requestbody and change the request method to post
#RequestMapping(value = "/GetJSON", method = RequestMethod.POST, produces = "application/json")
public #ResponseBody String GetJSON(
HttpServletRequest request, HttpServletResponse response,
#RequestParam(value = "api") String apiKey,
#RequestBody Testjson testJson)
throws ParseException {

api=asdf23**&&**jsonstr={"name":"myname","age":"20"}
You only need one &

you can also use gson 2.2.2 jar
RequestMapping(value = "/GetJSON", method = RequestMethod.GET)
public #ResponseBody String GetJSON(
HttpServletRequest request, HttpServletResponse response,
#RequestParam(value = "api") String apiKey)
throws ParseException {
Gson gson=new Gson();
Emp emp=new Emp();
String json =gson.tojson(emp);
System.out.println("JSON :: "+json);
return json;
}`

Pass the JSON HTTP Request
using the body as a POST request.
using url encode.
below just for example :
jsonstr={"name":"myname","age":"20"}
url :80/GetJSON?jsonstr=%7B%22name%22%3A%22myname%22%2C%22age%22%3A%2220%22%7D
for more information on URL encoding refer below
Percent-encoding, also known as URL encoding, is a mechanism for
encoding information in a Uniform Resource Identifier (URI) under
certain circumstances. Although it is known as URL encoding it is, in
fact, used more generally within the main Uniform Resource Identifier
(URI) set, which includes both Uniform Resource Locator (URL) and
Uniform Resource Name (URN). As such, it is also used in the
preparation of data of the application/x-www-form-urlencoded media
type, as is often used in the submission of HTML form data in HTTP
requests.
https://en.wikipedia.org/wiki/Percent-encoding

Related

Spring Boot not recognize controller with send request parameters

The spring boot do not recognize my controllers only if i send more parameters on request. For example:
If i send normal GET request the spring boot recognize my controller:
http://localhost/idp/oauth/123/authorize
If i send GET request with extras parameters the spring boot do not recognize my controller:
http://localhost/idp/oauth/123/authorize?scope=public_profile
I need receive the request exactly for second example (with parameter scope), but the spring boot do not recognize the controller and redirect to /error.
code:
#Controller
#RequestMapping("/idp/oauth")
public class OAuthController {
#RequestMapping(value = "/{clientId}/authorize", method = RequestMethod.GET)
public String authorizeGet(
HttpServletRequest request,
HttpServletResponse response,
#PathVariable String clientId,
Model model) {
// ...
}
#RequestMapping(value = "/{clientId}/authorize", method = RequestMethod.POST)
public String authorizePost(
HttpServletRequest request,
HttpServletResponse response,
#PathVariable String clientId,
Model model) {
// ...
}
}
Since you are passing extra param with name "scope" Spring will search for #RequestParam in methods
It can't find any, thus the error
You need to modify your method to add all #RequestParam
You can also add optional fields if they are not mandatory with required = false
#RequestMapping(value = "/{clientId}/authorize", method = RequestMethod.GET)
public String authorizeGet(
HttpServletRequest request,
HttpServletResponse response,
#PathVariable String clientId,
#RequestParam(value = "scope") String scope,
#RequestParam(required = false, value = "optionalParam") String optionalParam,
Model model) {
// ...
}
You missed #RequestParam in the controller method definition.
More on #RequestParam

How to handle that can not get form data by using RequestMapping

I implement a controller as the following:
#RequestMapping(value = "/export", method = RequestMethod.POST)
public #ResponseBody ResponseEntity<Object> Export(HttpServletRequest req, HttpServletResponse response, String type,String text) {
........
}
When posting the text(form param) which the length is small(about 20k) from client, the controller works ok and can get form params(data and type).
But 'type' and 'text' are null in service side, when text(form param) is very long(more than 200k) from client.
Who know how to handle it.
Form params can be read from request as req.getParameter("type").
change your method as below since you are already using req and resp in the method signature
public #ResponseBody ResponseEntity<Object> Export(HttpServletRequest req, HttpServletResponse response){
String type = req.getParameter("type");
String text = req.getParameter("text");
}
You could use the Spring MVC annotation as follows.
public #ResponseBody void export(#PathVariable final String whatEver,
#RequestParam("type") final String type, #RequestParam("text") final String text,
final HttpServletRequest request)

#RequestBody is always empty in Spring

The JSONObject is always coming as empty for the method below.
#RequestMapping(value = "/package/{id}", method = RequestMethod.PUT)
#ResponseStatus(HttpStatus.OK)
#ResponseBody
public SPackage updatePackage(#PathVariable String id, #RequestBody JSONObject
sPackage) {
}
and my ajax is like this. I am ways getting the object as empty map on the server side
var jsonObject= {"customerName":$('#customerName').val()}
var jsonData = JSON.stringify(jsonObject);
$.ajax({
type: "PUT",
url: "http://localhost:8081/someproj/package/" + $('#id').val(),
dataType: "json",
data: jsonData,
async: false,
contentType: "application/json; charset=utf-8",
beforeSend : function() {
openModal();
},
success: function(data) {
closeModal();
$('#success').show();
console.log(data);
}
});
I guess spring doesn't know to convert your json to JSONObject, the best thing would be to accept a POJO object which has similar structure to your json,
#RequestMapping(value = "/package/{id}", method = RequestMethod.PUT)
#ResponseStatus(HttpStatus.OK)
#ResponseBody
public SPackage updatePackage(#PathVariable String id, #RequestBody YourJsonPOJO
sPackage) {
}
Are you sure there're no exceptions occurring in your Spring code. When converting from JSON to custom object in Spring, you need to specify a custom class that has same fields & format as the JSON coming in. Otherwise, Spring doesn't know who to convert HTTP POST data into a Java object.
In your case, you could do define a POJO like this:
public class MyRequestObj {
private String customerName;
// add more fields for any other keys from JSON
}
And put this in your Controller class:
#RequestMapping(value = "/package/{id}", method = RequestMethod.PUT)
#ResponseStatus(HttpStatus.OK)
#ResponseBody
public SPackage updatePackage(#PathVariable String id, #RequestBody MyRequestObj
myRequestObj) {
String customerName = myRequestObj.getCustomerName();
}
Of course, if you only want to pass in the customer name as a String to your Controller, then you could also pass it as query string (append ?customerName=someCustomer) and you can retrieve it in Spring as:
#RequestMapping(value = "/package/{id}", method = RequestMethod.PUT)
#ResponseStatus(HttpStatus.OK)
#ResponseBody
public SPackage updatePackage(#PathVariable String id, #RequestParam("customerName") String customerName) {
}
You can use this workaround:
#RequestBody Map<String, String> json
That way you can continue using Jackson HttpMessageConverter and work with custom objects in payload.
You can check extended explanaition why this happens at answer here
#RequestBody gives empty JsonObject when making a POST Request

How to get a string sent in body of a request inside a Spring restful webservice?

I have a spring web service method where i want to get a string as a parameter. The string is sent in body of the request. My web service class is:
#Controller
#RequestMapping(value = "/users/{uid}/openchart")
public class OpenChartWebService {
#RequestMapping(method = RequestMethod.POST)
#ResponseBody
public String saveABC(#PathVariable("uid") Long uid,
#RequestBody String myString) {
System.out.println("sent string is: "+myString);
return "something";
}
}
My request in body is :
{
"name":"Ramesh"
}
But this is not working. This shows "Bad Request" HTTP error(400). How to send a string in a body and how to get a string sent in a body inside webservice method?
As #Leon suggests, you should add the media type to your request mapping, but also make sure you have Jackson on your classpath. You'll also want to change your #RequestBody argument type to something that has a "name" property, rather than just a String so that you don't have to convert it after.
public class Person {
private name;
public getName() {
return name;
}
}
If your data object looked like the above, then you could set your #RequestBody argument to Person type.
If all you want is a String, then perhaps just pass the value of "name" in your request body rather than an object with a name property.

RequestMapping with multiple values with pathvariable - Spring 3.0

#RequestMapping(value = {"/userDetails", "/userDetails/edit/{id}"}, method = RequestMethod.GET)
public String userDetails(Map Model,****) {
//what goes here?
}
What will be my arguments to the userDetails method? And how do I differentiate /userDetails and /userDetails/edit/9 within the method?
Ideally we can get pathvariable by using annotation #PathVariable in method argument but here you have used array of url {"/userDetails", "/userDetails/edit/{id}"} so this will give error while supply request like localhost:8080/domain_name/userDetails , in this case no id will be supplied to #PathVariable.
So you can get the difference (which request is comming through) by using argument HttpServletRequest request in method and use this request object as below -
String uri = request.getRequestURI();
Code is like this -
#RequestMapping(value = {"/userDetails", "/userDetails/edit/{id}"}, method=RequestMethod.GET)
public String userDetails(Map Model,HttpServletRequest request) {
String uri = request.getRequestURI();
//put the condition based on uri
}

Categories

Resources