I'm developing a simple login form (security is not a problem) where the user visits the page login inserts username and password and press send that POST these information to the page check.
Page check checks credential and, if everything is OK, creates cookie and redirect to page home, otherwise redirects to page login.
I use the following redirect:
return Response.temporaryRedirect(new URI("/home")).cookie(cookie, cookie2).build();
This redirects from check (@POST method) to home (@POST method), I just wanna to redirect to home (@GET method).
Important note: I'm a newbie of JAX and what I would like to create is a RESTful service. Are redirects a correct way to implement a REST service?
Now I'll show you small slices of code hoping:
check Page
@POST
@Produces(MediaType.TEXT_HTML)
public Response checkLogin(@FormParam(Login.fieldUsername) String user, @FormParam(Login.fieldPsw) String psw) throws URISyntaxException {
boolean val = db.checkLogin(user, psw);
NewCookie cookie;
NewCookie cookie2;
if(val){
//Valid access + cookie creation
cookie = new NewCookie("username", user);
cookie2 = new NewCookie("hashedPassword", psw);
return Response.temporaryRedirect(new URI("/home")).cookie(cookie, cookie2).build();
} else {
//Wrong login + cookie deletion
cookie = new NewCookie("username", "");
cookie2 = new NewCookie("hashedPassword", "");
return Response.temporaryRedirect(new URI("/login")).cookie(cookie, cookie2).build();
}
}
login page
@GET
@Produces(MediaType.TEXT_HTML)
public Response showLoginForm() throws URISyntaxException{
boolean validCookie = db.checkLogin(username, hashedPassword);
String data = "<form name='Username' action='"+ redirect +"' method='post'><ul>"
+ "<li><label for='"+fieldUsername+"'>Username</label>"
+ " <input type='text' name='"+fieldUsername+"' placeholder='Insert username' required></li>"
+ "<li><label for='"+fieldPsw+"'>Password</label>"
+ " <input type='password' name='"+fieldPsw+"' placeholder='Insert password' required></li>"
+ "<li><input type='submit' value='Login'>"
+ "</li></ul></form>";
if(validCookie){
return Response.temporaryRedirect(new URI(homepage)).build();
}
else {
return Response.ok( showTheForm(data) ).build();
}
}
You can use:
Response.seeOther(redirecttUri).build();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With