POST datas via Angular.post and retrieve it as JSON through servlet - java

I have an interface as so:
export interface Product {
product: string;
quantity: number;
status: string;
}
I post an Array populated with datas of this interface type:
sendDatas(productsArray:Product[])
{
const header: HttpHeaders = new HttpHeaders({'Content-Type': 'application/json'});
const options = {headers : header};
this.http.post<any>("/ssservice", JSON.stringify(productsArray), options).subscribe();
}
I want to retrieve the data sended with Angular in my servlet as JSON (I though using GSON library) and eventually know if that's not too much how to
to finally convert it to a List<List<Object>>type
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
WhichTypeToUse? JSONvalue = request.iDontKnowWhatMethodToUseToGrabValues();
List<List<Object>> convertedValues = HowCanIconvertTheValues(JSONvalue)
}
How can I achieve that? any help is greatly appreciated.

Related

Posting data from Servlet to Rest webservice

I want to submit form data to servlet which is Jersey rest client
and inside this servlet I have to call a Restful Webservice.
I have to pass all form data to that rest Webservice and after that we will get a response object from rest to servlet.
I have to pass this response object directly to JSP page here request and response will be in JSON format.
you can use servlet to send data to web service by sendRedirect("<url>")
Is it really necessary to call REST Class from a Servlet?
If so, the following is the way. But your REST call will be treated as a plain class. To call any method of the Rest class you have to create its object and access its methods.
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String requestURI = req.getRequestURI();
RestClass restClassObj = new RestClass();
String parameter1 = "";
String parameter2 = "";
String parameter3 = "";
String restResponse = "";
if(StringUtils.endsWith(requestURI, "services") || StringUtils.endsWith(requestURI, "services/")){
parameter1 = req.getParameter("parameter1");
parameter2 = req.getParameter("parameter2");
parameter3 = req.getParameter("parameter3");
restResponse = restClassObj.getRestClassMethodResponse(parameter1,parameter2,parameter3);
}
resp.setContentType("application/json");
resp.getWriter().write(restResponse);
}
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req,resp);
}
Now the RestClass is,
public class RestClass {
public RestClass() {
}
public String getRestClassMethodResponse(#FormParam("parameter1") String parameter1, #FormParam("parameter2") String parameter2, #FormParam("parameter3") String parameter3){
//Now write your own logic and return the data to the Servlet class in //JSON format
return jsonResponse;
}
}

Sending json from js to controller with ajax post

I'm having trouble sending a json object from javascript to java controller,
Ajax:
var xmlHttp = getXmlHttpRequestObject();
if(xmlHttp) {
var jsonObj = JSON.stringify({"title": "Hello","id": 5 });
xmlHttp.open("POST","myController",true);
xmlHttp.onreadystatechange = handleServletPost;
xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlHttp.send(jsonObj);
}
function handleServletPost() {
if (xmlHttp.readyState == 4) {
if(xmlHttp.status == 200) {
alert(window.succes);
}
}
}
What I tried in Java:
public void process(
final HttpServletRequest request, final HttpServletResponse response,
final ServletContext servletContext, final TemplateEngine templateEngine)
throws Exception {
String jsonObj = request.getParameter("jsonObj");
}
They all are null.
I tried reading related posts and multiple ways of sending the data but same result. I don't know how to use Jquery for ajax, so I'm looking for a js solution mainly.
Can someone tell me what I'm missing? As I spent about three hours trying to figure it out
To get your JSON sent with a POST request, you have to read the body of the request in a doPost method. Here's one way to do it :
protected void doPost(HttpServletRequest hreq, HttpServletResponse hres)
throws ServletException, IOException {
StringWriter sw = new StringWriter();
IOUtils.copy(hreq.getInputStream(), sw, "UTF-8");
String json = sw.toString();
And then you'll have to parse the JSON. This may be done for example using Google gson.
Supposing you have a class Thing with public parameters id and title, this would be
Gson gson = new GsonBuilder().create();
Thing thing = gson.fromJson(json, Thing.class);
int id = thing.id;
String title = thing.title;
Of course there are other solutions than gson to parse JSON but you have to parse it.
I think you are confusing URL parameters with request body. To get json string from request you need read it from request.getReader().
I have figured it out.
The Json should be sent like this:
xmlHttp.send("jsonObj="+jsonObj);
instead of
xmlHttp.send(jsonObj);
In order to receive it as parameter.

Aspectj: get Response body (HTML Text) from HttpServletRresponse

I m trying to use aspectJ to intercept HttpServlet.do*(request, response) and get the HTML text ( need to extract the title and maybe store the html to a file).
What is the best way to access the response body (html text) once I have a reference to the HttpServletResponse?
Here is my staring code.
public aspect HttpRequestHandlerAspect {
pointcut getRequest(HttpServletRequest request, HttpServletResponse response)
: execution(protected * javax.servlet.http.HttpServlet.*(HttpServletRequest, HttpServletResponse))
&& args(request, response);
Object around(HttpServletRequest request, HttpServletResponse response) : getRequest(request, response) {
Object ret = proceed(request, response);
// now how do I access the HTML response text ( and get the title of the page) in here?
}
}
This might not be the precise answer for your question, but try extracting the response as suggested here: How can I read an HttpServletReponses output stream?
You don't have to create a filter, only an HttpServletResponseWrapper which you pass to
proceed(request, wrapper).
Object around(HttpServletRequest request, HttpServletResponse response): getRequest(request, response) {
MyHttpServletResponseWrapper wrapper = new MyHttpServletResponseWrapper(response);
Object ret = proceed(request, wrapper);
// The MyHttpServletReponseWrapper class captures everything and doesn't forward to the original stream, so we have to do this
response.getWriter().write(wrapper.toString());
// use wrapper.toString() to access response
}

Fetching JSON object from Servlet Java

I want to create an application that will fetch a JSON object from a servlet to deserialize it, and then use its variables to do other things.
My servlet has the following code in the doPost:
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
ObjectOutputStream os;
os = new ObjectOutputStream(response.getOutputStream());
String s = new String("A String");
Gson gson = new Gson();
String gsonObject= gson.toJson(s);
os.writeObject(gsonObject);
os.close();
}
Now, while the servlet is running, I can access it via a browser, if I post same code in the doGet method, that would download a servlet file, which is not what I want.
What should I use in my second application that would connect to the servlet, fetch the object, so that I can manipulate it later?
Thanks in advance.
You need few changes in your servlet :
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String s = new String("A String");
String json = new Gson().toJson(s);
this.response.setContentType("application/json");
this.response.setCharacterEncoding("UTF-8");
Writer writer = null;
try {
writer = this.response.getWriter();
writer.write(json);
} finally {
try {
writer.close();
}
catch (IOException ex) {
}
}
}
If its downloading the servlet file instead of showing it in the browser , most probably you have not set the content type in the response. If you are writing a JSON string as the servlet response , you have to use
response.setContentType("text/html");
response.getWriter().write(json);
Please note the order , its "text/html" and not "html/text"
IfI understood the question correctly then you can use, java.net.HttpURLConnection and java.net.URL objects to create a connection to this servlet and read the JSON streamed by the above JSON servlet in your second servlet.

Java AJAX Variable Passing

I have a java file by which I want to pass map something like : { id: 5, GPA: 5} to my jsp file using AJAX. I am using following code for this:
In my JAVA file:
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception {
JSONObject jsonResult = new JSONObject();
jsonResult.put("id", "5");
jsonResult.put("GPA", "5");
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(jsonResult.toString());
}
In jsp file:
--some extJS code--
Ext.Ajax.request({
url :'assertion.htm',
method : 'POST',
params: {
existingRule : nameField.getRawValue()
},
scope : this,
success: function ( response ) {
alert(response.responseText);
}
response.responseText is printing entire jsp file instead of printing id:5, GPA:5
Can anyone help me in this?
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception {
JSONObject jsonResult = new JSONObject();
jsonResult.put("id", "5");
jsonResult.put("GPA", "5");
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(jsonResult.toString());
}
This won't compile, you are missing a return statement.
This seems to be a Spring MVC controller, judging by the ModelAndView return type. My guess is that you are returning a JSP view instead of the JSON Object you want to return. See this previous question of mine for how to return a JSON Object from Spring MVC.
Your function does not return anything and this is correct so change it to void:
protected void handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception {
JSONObject jsonResult = new JSONObject();
jsonResult.put("id", "5");
jsonResult.put("GPA", "5");
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(jsonResult.toString());
}

Categories