Send a redirect from server to Angular - java

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
)
)
}

Related

Does a HttpServlet have to respond to a request?

I have several servlets that do things server side. On a few I just encode some unnecessary data and send it back, which seems pointless. Do you have to respond ? What happens when you just say return ? I've done that before and nothing seems to go wrong but I am relatively new to servlets. Are there consequences for simply returning that go above my head ? And what exactly happens when you return;
if(request.getParameter("name").equals("saveusedcards")) {
String sessId = request.getSession().getId();
//encode request with confirmation that cards were successfully updated
if(usersUpdatedCards.get(sessId).isEmpty()){
//no cards were seen
}
boolean success = DataDAO.updateCards(usersUpdatedCards.get(sessId));
if(success){
System.out.println("Data base update successfull!");
String responseMessage = new Gson().toJson("card successfully udpated");
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
System.out.println("updated cards response message: "+responseMessage);
response.getWriter().write(responseMessage);
return;
} else {
System.out.println("Data base update failed...");
String responseMessage = new Gson().toJson("card was not successfully updated");
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
System.out.println("updated cards response message: "+responseMessage);
response.getWriter().write(responseMessage);
return;
}
}
The servlet must produce an HTTP response for the client, however it is perfectly acceptable to return no content in the response body. When doing so your servlet should make this clear to the client by sending a response code of 204 (no content). Reference: https://httpstatuses.com/204
Here is an example of how you would set the response code from the doGet method. You could do the same from doPost or service methods.
#Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
// Do whatever work you need to do here...
res.setStatus(HttpServletResponse. SC_NO_CONTENT); // This returns a 204
}

How to retrieve parameters from POST in XPages (java)

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.

How to send and catch parameter from JavaScript (AJAX request) to Servlet

I created InformationServlet that whenever I need some details I can send it what I want (with AJAX) and it will return me the information.
I searched how to do it on Ajax and according to:
How to send parameter to a servlet using Ajax Call
I used: url: "InformationServlet?param=numberOfPlayers"
But on the servlet the request's attributes doesn't contain the parameter I sent so I suppose I am not doing it correctly:
you can see that the attributes size is zero
Servlet:
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
Gson gson = new Gson();
Engine engine = (Engine)getServletContext().getAttribute("engine");
String responseJson = "";
if(request.getAttribute("numberOfPlayers") != null)
{
String numberOfPlayers = "";
numberOfPlayers = gson.toJson(String.valueOf(engine.GetNumOfPlayers()));
responseJson = numberOfPlayers;
}
out.print(responseJson);
} finally {
out.close();
}
}
JavaScript (AJAX request):
function getNumberOfPlayersAndPrintSoldiers()
{
$.ajax({
url: "InformationServlet?param=numberOfPlayers",
timeout: 2000,
error: function() {
console.log("Failed to send ajax");
},
success: function(numberOfPlayers) {
var r = numberOfPlayers;
}
});
}
Edit:
you probably want to use getParameter and not getAttribute
Moreover, please pay attention to the order of parameter name and his value:
request.getParameter("param");
instad of:
request.getParameter("numberOfPlayers");
because the url form contains parameter name first and then the parameter value. for example:
myurl.html?param=17
and if more parameters needed then use the separator & sign
myurl.html?firstName=bob&age=5

Passing custom objects from servlet to Jquery

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?

Why the response.sendRedirect() in servlet doesn't work after receiving the post request of JQuery?

In the blog-edit.html, JQuery was used to send the post request to the sever side(java servlet).
$("#btn").click(function() {
$.post("/blog/handler",{"content":$('#textarea').val()},
function(data){
alert("Data Loaded: " + data);
if(data.toString().length>1){
alert("Saved!")
}else{
alert("Failed!")
}
})
In the server side:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String content = request.getParameter("content");
System.out.println(content);
response.sendRedirect("/blog/list");
return;
}
What I saw is the server side is printing the content from the html, and the alert window pops up to say "Saved!". But the redirect function doesn't work
After searching I have no choice but to use jquery to redirect:
if(data.toString().length>1){
alert("Saved!")
window.location.replace("/blog/list")
}
it works, but it's not what i want
please help
While using ajax. you can not execute server side redirect.
However, there are better way how to redirect on client in such a scenario.
See Here

Categories

Resources