I want to use Domino as a backend, and html/jquery as a frontend for my web application. So I have:
$.ajax({
type: 'POST',
url: 'mydb.nsf/xpage.xsp',
contentType: 'application/json; charset=utf-8',
data: {
f1: "hello",
f2: "hello again"
},
success: function (response) {
console.log("SUCCESS");
},
error: function (error) {
console.log(error);
}
});
In Domino:
public static String doGet(HttpServletRequest req, HttpServletResponse res) throws JsonException, IOException, NotesException {
return doPost(req, res);
}
public static String doPost(HttpServletRequest req, HttpServletResponse res) throws JsonException, IOException, NotesException {
System.out.println("1) "+req.getAttribute("f1"));
System.out.println("2) "+req.getParameter("f1"));
System.out.println("3) "+req.getContentLength());
return "AllOK";
}
In firebug and domino log I see that POST goes trough ok, gets the response. But I can't figure out how to get params f1 and f2 in domino.
In domino log:
1) is null,
2) is null,
3) is 23.
Idea for later is to POST JSON, but for now it would be great to have this code working.
How to get POST parameters in domino via java?
(I see stackoverflow has a lot of similar questions answered, but couldn't find anything specific to my problem)
Thank you!
Use reg.getReader() or req.getInputStream() to read the body of the request with elements f1 and f2.
Here is an example how you can read the JSON data:
https://stackoverflow.com/a/3831791/2065611
req.getParameter() works only if content type is "application/x-www-form-urlencoded", not json.
Related
Trying to send a response.sendRedirect to an HTML page on my server But, the function on Angular side always trying to parse my HTML page to JSON. even though my I'm configuring my Observable generic to 'any'.
Looked everywhere couldn't find an answer.
Thank you everyone who tries to help.
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.getSession().invalidate();
String loginUrl = new Gson().toJson("login.html");
PrintWriter out = response.getWriter();
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
out.print(loginUrl);
out.flush();
}
public logOut():Observable<any> {
return this.client.get<any>("../Login");
}
public disconnect():void {
this.service.logOut().subscribe( content => {
}, fail => {
console.log(fail);
});
Unexpected token < in JSON at position 0 at JSON.parse
Http failure during parsing for http://localhost:8080/...
Disclaimer: I am not a JAVA API developer so there may be a more efficient way of doing the JAVA backend.
Okay, in order to get this to work you should update your code to be the following:
Backend:
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.getSession().invalidate();
String loginUrl = "index.html";
PrintWriter out = response.getWriter();
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
out.print(loginUrl);
out.flush();
}
Angular:
public logOut():Observable<string> {
return this.client.get<string>("../Login");
}
public disconnect():void {
this.service.logOut().subscribe(redirectUrl => {
const baseUrl = window.location.href.split('/').slice(0,4).join('/');
window.location.href = `${baseUrl}/${redirectUrl}`;
}, fail => {
// Do fail stuff
});
}
Update: Changed the redirect location based off of the comments.
IMO this solution is starting to get a bit dirty. It will work in a pinch but, in the long-run, I would recommend changing to a Angular-routing related solution similar to the solution posted by 'Thomas Cayne'
Daniel Mizrahi: do not send login.html back from the server. Send back something like this: '{"redirectTo": "login"}'.
First you need to import the angular router in your service:
import {Route} from "#angular/router"
Then inject it in your component constructor:
constructor(private route: Route) { }
Finally in your disconnect() method:
public disconnect():void {
this.service.logOut().subscribe( content => {
this.route.navigate([`/${content.redirectTo}`])
}, fail => console.log('Display fail error:', fail)
)
);
Also, disconnect() method might not be necessary because you can do the work from:
logOut(): Observable<any> {
return this.client.get<any>('../Login')
.pipe(
map(success => this.route.navigate([`/${success}`]),
catchError(fail => console.log('Display fail error:', fail)
// and then redirect somewhere
)
)
}
I have a problem in one of my projects.
We have a backend in Java and a FrondEnd app in HTML and AngularJS (v1.4.6).
In the frondend we display a table contaning some records retrieved from Java in JSON format.
In Java we use GSON to convert an object to JSON format and then we will send to browser.
Here's my Java Code:
public class doSomething {
public void caricaFile(HttpServletRequest request, HttpServletResponse response, FiltriParameters filtri) throws IOException
{
RetObj r = caricaFile(request, response, filtri, ...);
response.getWriter().println(Utils.json(r));
}
}
public class Utils {
public final static String json(Object obj) {
return new GsonBuilder().serializeNulls().create().toJson(obj);
}
}
Here's our Angular Function
$scope.uploadFile = function(files) {
if (files.length == 0)
return;
openLoader();
var fd = new FormData();
//Take the first selected file
fd.append("file", files[0]);
$http.post(urlUploader, fd, {
withCredentials: true,
headers: {'Content-Type': undefined },
transformRequest: angular.identity
})
.success(function(response){
closeLoader();
response = angular.fromJson(response);
// do something
})
.error(
function(response){
closeLoader();
alert(response);
});
$( "#file-upload" ).val("");
}
In chrome everything works fine, the JSON get received then parsed and all the rows are showed in the html table.
In Internet Explorer we get the following error. "response is undefined" in error function
IE Console:
SyntaxError: Expected '}'
at uc (http://127.0.0.1:8085/HERMESCS2/js/generics/1-4-6angular.min.js?vid=120:15:463)
at Zb (http://127.0.0.1:8085/HERMESCS2/js/generics/1-4-6angular.min.js?vid=120:82:227)
at Anonymous function (http://127.0.0.1:8085/HERMESCS2/js/generics/1-4-6angular.min.js?vid=120:83:141)
at m (http://127.0.0.1:8085/HERMESCS2/js/generics/1-4-6angular.min.js?vid=120:7:320)
at cd (http://127.0.0.1:8085/HERMESCS2/js/generics/1-4-6angular.min.js?vid=120:83:125)
at d (http://127.0.0.1:8085/HERMESCS2/js/generics/1-4-6angular.min.js?vid=120:84:366)
at Anonymous function (http://127.0.0.1:8085/HERMESCS2/js/generics/1-4-6angular.min.js?vid=120:118:324)
at n.prototype.$eval (http://127.0.0.1:8085/HERMESCS2/js/generics/1-4-6angular.min.js?vid=120:132:441)
at n.prototype.$digest (http://127.0.0.1:8085/HERMESCS2/js/generics/1-4-6angular.min.js?vid=120:129:455)
at n.prototype.$apply (http://127.0.0.1:8085/HERMESCS2/js/generics/1-4-6angular.min.js?vid=120:133:234)
Here a pastebin with the JSON the backend returns to frontend/angular.
https://pastebin.com/zUiX3AtV
We already tested it and it's a valid JSON
Any Advice?
Problem Solved
I changed the content-type in the header response to: text/json somehow Internet Explorer is affected by this whereas Chrome/FireFox no!
public class doSomething {
public void caricaFile(HttpServletRequest request, HttpServletResponse response, FiltriParameters filtri) throws IOException
{
RetObj r = caricaFile(request, response, filtri, ...);
response.setContentType("text/json");
response.getWriter().println(Utils.json(r));
}
}
I am trying to send some query from jsp file to servlet via post method and then get some modified result from servlet to jsp file.
I am able to complete first part successfully, but I cannot receive the response in jsp file.
Servlet post method is:-
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
JSONObject js = <some method to get json>;
System.out.println(js); //works fine
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(js.toJSONString());
}
And my jsp code is:
<script>
function getData() {
$.post("MyServlet", {
query : "Wolf of wall street",
choice : "M"
}, function(response) {
alert("hello" + response);
});
}
</script>
The output is:
How can i get that json string ?
you are getting json as response need to stringify it.
<script>
function getData() {
$.post("MyServlet", {
query : "Wolf of wall street",
choice : "M"
}, function(response) {
alert("hello" + JSON.stringify(response));
});
}
</script>
i have a servlet my goal is to return a customer object from the process request, where i can then access this object in my jquery. Does anyone know how i can go about doing this?
e.g. myObject.getMethod()
Servlet Code:
Customer loginResult;
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
/* TODO output your page here. You may use following sample code. */
//request.setAttribute("customerFirstName", loginResult.getFirstName()); //String Value
//request.setAttribute("customerID", loginResult.getCustomerID()); //IntegerValue
out.println(loginResult);
} finally {
out.close();
}
}
JSP CODE:
<script type="text/javascript">
$().ready(function() {
$('#submit').click(function() {
var dataf = 'email=' + $('#email').val()
+ '&password=' + $('#password').val();
$.ajax({
url: "http://localhost:8080/RetailerGui/loginServlet",
type: "get",
data: dataf,
success: function(data) {
alert(data);
}
});
return false;
});
});
</script>
Can someone please assist me in resolving this issue, thank you for your help in advance.
Since you want to handle an ajax request using a Servlet, the best bet you have is writing the data of your custom object into the response. The easier way I found to accomplish this is using JSON. There are lot of libraries that handles JSON conversion from objects to Strings and vice versa, I recommend using Jackson. This is how your code should look like.
Servlet code:
import com.fasterxml.jackson.databind.ObjectMapper;
#WebServlet("/loginServlet") //assuming you're using Servlet 3.0
public class YourServlet extends HttpServlet {
//Jackson class that handles JSON marshalling
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
//login operation should be handled in POST
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Customer loginResult = ...; //process data and get the loginResult instance
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
//marshalling the data of your loginResult in JSON format
String json = OBJECT_MAPPER.writeValueAsString(loginResult);
response.getWriter().write(json);
}
}
Javascript code:
<script type="text/javascript">
$().ready(function() {
$('#submit').click(function() {
var dataf = 'email=' + $('#email').val()
+ '&password=' + $('#password').val();
$.ajax({
url: "http://localhost:8080/RetailerGui/loginServlet",
type: "post", //login action MUST be post, NEVER a get
data: dataf,
success: function(data) {
//shows the relevant data of your login result object in json format
alert(data);
//parsing your data into a JavaScript variable
var loginResult = JSON && JSON.parse(data) || $.parseJSON(data);
//now you can use the attributes of your loginResult easily in JavaScript
//for example, assuming you have a name attribute in your Customer class
alert(loginResult.name);
}
});
return false;
});
});
</script>
More info:
How to use Servlets and Ajax?
Parse JSON in JavaScript?
Here is my AJAX code which triggers the Servlet 'CalculateLace'
laceTd.dblclick(function() {
var jsonObj= { jsonObj: [ {"rowID": $(nRow).attr('id')} ]};
$.ajax({
data: JSON.stringify(jsonObj),
contentType: "application/json; charset=utf-8",
traditional: true,
url: "CalculateLace"
});
});
And here is my Java Servlet code:
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String id = req.getParameter("rowId");
//do something
}
But I keep getting String id as null. I also tried
String id = req.getParameter("id");
but to no avail. What am I doing wrong here?
Try this way -
var jsonObj= {"rowId": $(nRow).attr('id')};
and get rowID in your servlet this way - You can get library to parse your json here JSON.org
req.getParameter("rowId");