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());
}
Related
Not sure how to solve this, need some help here.
Ajax call brings user information to servlet, I save user object in HttpSession and control goes back to Ajax from where i redirect control to next JSP page via controller servlet. However, if i try to retrieve object from HttpSession it is null .. not sure how to solve this issue.
here is my code for firstservlet:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// get values from http request
// persist "user" object to database
HttpSession session = request.getSession(); //
session.setAttribute("user", user); //setting session variable
Gson gson = new Gson();
JsonElement jsonElement = null;
jsonElement = gson.toJsonTree("/nextservlet");
response.setContentType("text/plain");
PrintWriter out=response.getWriter();
}
here is my Javascript / AJAX code to redirect request to nextservlet
$.ajax({
type: 'POST',
url: ‘firstservlet’,
dataType: 'json',
contentType: 'application/json',
data: JSON.stringify(quiz),
success: function(result) {
//result = /nextservlet
window.location.href = result;
},
error:function(data,status,er) {
console.log("Error:",er);
}
});
and finally control comes to nextservlet - where i would like to process data and then show new JSP page.
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/plain");
response.setCharacterEncoding("UTF-8");
HttpSession session = request.getSession();
User user = session.getAttribute(“user”); //<--- this is NULL
LOG.warning("User id is : " + user.getId()); //<--- hence error here
RequestDispatcher dispatcher = request.getRequestDispatcher
("/anotherpage.jsp");
dispatcher.forward(request, response);
}
is issue because i am using -> window.location.href = result to send request to nextservlet .. and it goes to doGet??
I am not sure it but I see in Ajax
url: ‘firstservlet’,
type: 'POST'
and control goes to doGet method of nextservlet. It should be nextservlet of post method so use method doPost.
18.12.22
i'm not sure... but try it
success: function(result) {
// result = /nextservlet
var form = document.createElement('form');
form.action = result;
form.method = 'GET'
form.submit();
}
18.12.26
Javascript
$.ajax({
type: 'POST',
url: '/firstservlet',
dataType: 'json',
contentType: 'application/json',
data: JSON.stringfy(quiz),
success: function(result) {
console.info(result);
var form = document.createElement('form');
form.action = result;
form.method = 'GET';
document.body.appendChild(form);
form.submit();
},
error: function(data, status, err) {
console.log("Error: ", err);
}
});
Servlet
HttpSession session = request.getSession();
session.setAttribute("test", "test");
Gson gson = new Gson();
JsonElement jsonElement = gson.toJsonTree("/nextservlet");
response.setContentType("text/plain");
PrintWriter out = response.getWriter();
out.print(gson.toJson(jsonElement));
It can read session attribute in doGet Method try it.
I want to change the view from the HTML list to JSON data.
This my code in controller:-
private void listFeedback(HttpServletRequest request, HttpServletResponse response)
throws SQLException, IOException, ServletException {
Feedback p = new Feedback();
int seller_id = Integer.parseInt(request.getParameter("seller_id"));
List<Feedback> feedbacks = p.all(seller_id);
String format = request.getParameter("format");
if(format == "json"){
String json = new Gson().toJson(feedbacks);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(json);
RequestDispatcher dispatcher = request.getRequestDispatcher("feedbacks/demo.jsp");
dispatcher.forward(request, response);
}
request.setAttribute("feedbacks", feedbacks);
RequestDispatcher dispatcher = request.getRequestDispatcher("feedbacks/list.jsp");
dispatcher.forward(request, response);
}
But, It can be still viewed like before, nothing got to change at all. I wish it to be redirected to demo.jsp so that it can have a JSON view. Would anyone help me doing the same?
UPDATE
I just forget to put else in there
so, this the right code
else{
request.setAttribute("feedbacks", feedbacks);
RequestDispatcher dispatcher = request.getRequestDispatcher("feedbacks/list.jsp");
dispatcher.forward(request, response);
}
Thank you so much for answering my question.
It looks format value is null or not json. If the code present inside if executed, you would end up having error (The next lines of code, you are forwarding to another jsp).
"Cannot forward after response has been committed"
Make the below changes to make it work:
you would not need to forward while you wanted to return the JSON. just add below code inside if
if("json".equals(format)){
String json = new Gson().toJson(feedbacks);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(json);
return; // return from here or change to if-else
}
The whole code:
private void listFeedback(HttpServletRequest request, HttpServletResponse response)
throws SQLException, IOException, ServletException {
Feedback p = new Feedback();
int seller_id = Integer.parseInt(request.getParameter("seller_id"));
List<Feedback> feedbacks = p.all(seller_id);
String format = request.getParameter("format");
if("json".equals(format)){
String json = new Gson().toJson(feedbacks);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(json);
return;// return from here or change to if-else
}
request.setAttribute("feedbacks", feedbacks);
RequestDispatcher dispatcher = request.getRequestDispatcher("feedbacks/list.jsp");
dispatcher.forward(request, response);
}
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.
I have to write a controller in my project using servlets. I've done it before but I've never worked with AngularJS, so I did it via request.setAttribute() and request.getParameter() and put Java code inside of a JSP page. But now frontend developer used AngularJS and I have to return him a JSON object. And I have no idea how to do it. Here's the code of abTestCtrl.js:
app.controller("abTestCtrl", function($scope, $location, $http) {
$scope.title = "no title";
$scope.description = "no description";
$scope.getParam = $location.search()['id'];
if($scope.getParam === undefined)$scope.getParam = 0;
//$scope.getParam=2;
//path: localhost8080/UIUM.../servlet-name.java
//with two ids
//web.xml: serverlet mapping for the path
if($scope.getParam==='0'||$scope.getParam === 0){
var saveButton = document.getElementById("saveButton");
saveButton.classList.remove("hidden");
}
else{
$http.get('http://localhost:8080/UIUM_IMT4003/ABTestController', {command:'getTestCaseInfo', testcaseID:$scope.getParam}).
success(function(data, status, headers, config) {
// this callback will be called asynchronously
// when the response is available
console.log('request succesful');
console.log(data);
console.log(status);
console.log(headers);
console.log(config);
}).
error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
console.log('request not succesful');
});
}
and my processRequest() code from the servlet:
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, ClassNotFoundException {
response.setStatus(HttpServletResponse.SC_OK);
response.setContentType("application/json; charset=UTF-8");
//PrintWriter printout = response.getWriter();
JSONObject jObject = null;
RequestDispatcher view = null;
TestcaseRepository testcaseRepo = new TestcaseRepository();
String command = request.getParameter("command");
if(command == null)
{
view = request.getRequestDispatcher("/testcases.jsp");
view.forward(request, response);
}
if(command.equals("getTestCaseInfo")){
String testcaseId = request.getParameter("testcaseID");
Testcase testcase = testcaseRepo.getTestcaseById(testcaseId);
jObject = new JSONObject();
jObject.put("id", testcaseId);
jObject.put("title", testcase.getTestcaseName());
jObject.put("testscenario", testcase.getTestcaseDescription());
// printout.print(jObject);
// printout.flush();
jObject.write(response.getWriter());
}
Can you please help me to process this request and finally return this poor JSON!
BTW, Servlet doesn't recognize command parameter. It gets null. But there is such parameter in AngularJS function.
Try using the javax.json.JsonObject as follow:
JsonObject jo=Json.createObjectBuilder()
.add("id", testcaseId)
.add("title", testcase.getTestcaseName())
.add("testscenario", testcase.getTestcaseDescription()).build();
Then set the response content type to json and send your json object in the response:
response.setContentType("application/json");// set content to json
PrintWriter out = response.getWriter();
out.print(jo);
out.flush();
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.