Can't call doPost from doGet - java

When I'm calling doPost directly, it shows me profile page in correct way. But then after login I open new tab in Chrome copy url "http://localhost:8080/17_servlets_jsp/profile" there and it shows me blank page
#WebServlet("/profile")
public class Profile extends HttpServlet {
**private String login;**
private HttpSession httpSession;
private User user;
private Role role;
public static Logger LOGGER = LogManager.getLogger(Profile.class.getName());
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html");
httpSession = req.getSession();
try (PrintWriter out = resp.getWriter()) {
**if (httpSession.getAttribute("userLoggedIn") == null) {
out.println("<title>Login Page</title>");
out.println("<p>Please follow the link to login</p>");
} else {
login = (String) httpSession.getAttribute("uLogin");
doPost(req, resp);
}**
} catch (IOException | NullPointerException e) {
LOGGER.error(e);
}
}
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
**login = req.getParameter("login");
user = new ImplUserDAO().findByLogin(login);**
httpSession = req.getSession();
resp.setContentType("text/html");
try (PrintWriter out = resp.getWriter()) {
out.println("<title>Profile page</title>");
if (user != null && user.getPassword().equals(req.getParameter("pass"))) {
role = new ImplRoleDAO().findById(user.getRoleId());
httpSession.setAttribute("userLoggedIn", true);
httpSession.setAttribute("uLogin",req.getParameter("login"));
httpSession.setAttribute("uPass",req.getParameter("pass"));
out.println("user id = " + user.getUserId());
out.println("login = " + user.getLogin());
out.println("password = " + user.getPassword());
out.println("role = " + role.getRoleName());
out.println("<form action=\"logout\" method=\"get\"/>" +
"<input type=\"submit\" value=\"Logout\"/>" +
"</form>");
if (role.getRoleName().equals("admin")) {
httpSession.setAttribute("isAdmin", true);
out.println("Go to admin page");
}
} else {
out.println("Wrong login or password");
out.println("Please follow the link to login");
}
} catch (IOException | NullPointerException e) {
LOGGER.error(e);
}
}
}

By calling doPost() you also execute this line:
user = new ImplUserDAO().findByLogin(req.getParameter("login"));
Which will throw an Exception or return null or whatever because your GET request didn't include that parameter. If you want to reuse doPost() you'd need to fetch login from either session or request:
String login = req.getParameter("login");
if(null == login) {
login = (String)httpSession.getAttribute("uLogin");
}
Or similar.
On Attributes and Parameters
In your commented out code, you tried to solve this issue by calling setAttribute("login"... on your request. While this is legal, you can not retrieve that value by calling getParameter(). Instead you'd have to call 'getAttribute()` again - which doesn't make much difference to retrieving directly from the session:
//Retrieve Parameter (been send into the servlet from outside)
String login = req.getParameter("login");
if(null == login) {
//Retrieve Attribute you put into the request in doGet()
login = (String)req.getAttribute("login");
}
Another Edit
You have the same issue with req.getParameter("pass").
You should seriously consider splitting login-process (checking username/password from request) from other functionality (display profile page) or reverse your logic: Do login, set user into session in doPost() and if successful call goGet()?
Full Example Code
Consider these changes to somewhat fix your logic:
#WebServlet("/profile")
public class Profile extends HttpServlet {
// Don't use member variables on Servlets - they get reused for all users!
// private String login;
// private HttpSession httpSession;
// private User user;
// private Role role;
public static Logger LOGGER = LogManager.getLogger(Profile.class.getName());
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html");
HttpSession httpSession = req.getSession();
try (PrintWriter out = resp.getWriter()) {
if (httpSession.getAttribute("userLoggedIn") == null) {
out.println("<title>Login Page</title>");
out.println("<p>Please follow the link to login</p>");
}
else {
User user = httpSession.getAttribute("userLoggedIn");
Role role = httpSession.getAttribute("userRole");
out.println("<title>Profile page</title>");
out.println("user id = " + user.getUserId());
out.println("login = " + user.getLogin());
out.println("password = " + user.getPassword());
out.println("role = " + role.getRoleName());
out.println("<form action=\"logout\" method=\"get\"/>" +
"<input type=\"submit\" value=\"Logout\"/>" +
"</form>");
if("true".equals(httpSession.getAttribute("isAdmin")) {
httpSession.setAttribute("isAdmin", true);
out.println("Go to admin page");
}
}
} catch (IOException | NullPointerException e) {
LOGGER.error(e);
}
}
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String login = req.getParameter("login");
User user = new ImplUserDAO().findByLogin(login);
HttpSession httpSession = req.getSession();
try (PrintWriter out = resp.getWriter()) {
if (user != null && user.getPassword().equals(req.getParameter("pass"))) {
Role role = new ImplRoleDAO().findById(user.getRoleId());
httpSession.setAttribute("userLoggedIn", user);
httpSession.setAttribute("userRole", role);
if (role.getRoleName().equals("admin")) {
httpSession.setAttribute("isAdmin", true);
}
// Now refer to display part.
goGet(req, resp);
} else {
out.println("Wrong login or password");
out.println("Please follow the link to login");
}
} catch (IOException | NullPointerException e) {
LOGGER.error(e);
}
}
}

Related

How to show another html page with servlet?

this is my first time with Java's servlet (and JSP) programming and right now I have a doubt. Imagine that I'm building an online shop with a login page (let's suppose is the starting page) and maybe a shopping page (the "second" one). My servlet contains the code for autenticate the users and if the user is correct the servlet should shows the shopping catalog. My answer is, what's the best method for doing this? This is my servlet code (doGet) now:
nb: userName and password come from the login page...
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.getWriter().append("Served at: ").append(request.getContextPath());
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String userName = request.getParameter("userName");
String password = request.getParameter("password");
out.println("<html>");
out.println("<body bgcolor = 'green'>");
out.println("<br>" + "Hello " + " " + userName + "<br> LOGGED IN!" + "<br>");
out.println("Your password is : " + " " + password + "<br>");
if(userName.equals("some_correct_user")) {
out.println("<p>Login correct </p>");
response.sendRedirect("/FirstServletExercise/shoppingPage.html");
}
else {
out.println("<p>Access denied</p>");
}
I know it's very simple but is just the concept: it's correct to use "sendRedirect" to display another different page, or I have to upgrade the content of the first page? And how I can do this? Hope I have explained myself well.
Thanks!
I am using Jetty-11 Server standalone/embedded mode. And here is how the Login Servlet looks like.
import java.io.IOException;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
public class LoginServlet extends HttpServlet {
private Logger log = LoggerFactory.getLogger(LoginServlet.class);
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
log.debug("LoginServlet {} userPrincipal: {}", req.getServletPath(), req.getUserPrincipal());
Map<String, String[]> p = req.getParameterMap();
p.forEach((k, v) -> {
log.debug("{} {}", k, v);
});
String un = (p.get("j_username") != null) ? p.get("j_username")[0] : null;
String up = (p.get("j_password") != null) ? p.get("j_password")[0] : null;
try {
if (un != null && up != null) {
req.logout();
req.login(un, up);
}
} catch (Exception e) {
log.error("AuthenticationException: ", e);
}
log.debug("{} userPrincipal: {}", req.getServletPath(), req.getUserPrincipal());
boolean isAuth = (req.getUserPrincipal() == null) ? false : true;
log.debug("isAuth: {}", isAuth);
resp.setContentType("text/html");
if (isAuth) {
/** Session Management */
HttpSession session = req.getSession();
session.setAttribute("user", req.getUserPrincipal().getName());
// setting session to expiry in 30 mins
session.setMaxInactiveInterval(30 * 60);
log.debug("sessionId: {} ", req.getSession().getId());
/** Cookie Management */
Cookie loginCookie = new Cookie("user", req.getUserPrincipal().getName());
loginCookie.setMaxAge(30 * 60);
resp.addCookie(loginCookie);
/** Login Success - so display the Home Page */
resp.sendRedirect("./index.html");
} else {
Cookie loginCookie = new Cookie("user", "unknownUser");
loginCookie.setMaxAge(0);
loginCookie.setPath("/");
resp.addCookie(loginCookie);
req.getRequestDispatcher("./login.html").forward(req, resp);
}
}
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}

How to maintain session between Android and Servlet? [duplicate]

This question already has answers here:
How to use java.net.URLConnection to fire and handle HTTP requests
(12 answers)
Making http calls from swing application to a servlet, session not saved
(1 answer)
Closed 1 year ago.
Server-side I have an HttpSession object. Each time the client starts the connection to the Servlet, the session changes.
Here I have a simplified version of my Servlet code:
//import ...
#WebServlet(name = "ServletController", urlPatterns = {"/ServletController"})
public class ServletController extends HttpServlet {
public void init(ServletConfig conf) {
//...
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//...
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/plain");
HttpSession s = request.getSession();
PrintWriter out = response.getWriter();
try {
String action = request.getParameter("action");
switch (action) {
case "login":
s.setAttribute("account", "John");
out.println("Logged in successfully. Session: " + s);
out.flush();
break;
case "account":
String account = (String) s.getAttribute("account");
out.println(account + ". Session: " + s);
out.flush();
break;
default:
break;
}
} catch (Exception x) {
System.out.println(x);
}
}
}
And here the simplified Android one:
//import ...
public class Operation {
public static Executor e = Executors.newSingleThreadExecutor();
public static void main(String[] args) {
Button login_btn = findViewById(R.id.login);
Button account_btn = findViewById(R.id.account);
login_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
e.execute(() -> {
String login = Operation.operation("?action=login");
});
}
});
account_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
e.execute(() -> {
String account = Operation.operation("?action=account");
});
}
});
System.out.println(login);
System.out.println(account);
}
public static String operation(String urlParameters) {
HttpURLConnection conn = null;
try {
System.out.println(urlParameters);
URL url = new URL("http://10.0.2.2:8080/progettoTweb/ServletController" + urlParameters);
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(1000);
conn.setConnectTimeout(1500);
conn.setRequestMethod("GET");
conn.setDoInput(true);
conn.connect();
int response = conn.getResponseCode();
return readIt(conn.getInputStream());
} catch (Exception ex) {
System.out.println(ex);
return null;
} finally {
if (conn != null) {
conn.disconnect();
}
}
}
//building the output as a String
private static String readIt(InputStream stream) throws IOException, UnsupportedEncodingException {
BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
String line;
StringBuilder result = new StringBuilder();
while ((line = reader.readLine()) != null) {
result.append(line).append("\n");
}
return result.toString();
}
}
As the System.out.println in the Android app show, I obtain a different session for each Operation.operation call I make.
In the original code I use SharedPreferences in order to save my data, but it does not solve the problem since I do not know how to use the session, gained from the interaction with the server-side, to obtain the required values.
Indeed, in the Servlet code I use s.getAttribute() but, since it creates a new HttpSession object each time, It cannot give back the requested values.

Getting session from another Servlet

I'm trying to store a User object in session in Servlet1. In Servlet2 I'm trying to get the values from the same logged in session from Servlet1.
Servlet1:
private void login(HttpServletRequest request, HttpServletResponse response) throws IOException {
request.setCharacterEncoding("UTF-8");
String emailFromForm = request.getParameter("email").toLowerCase();
String passwordFromForm = request.getParameter("passWord");
try {
User userThatLogsIn = manager.getUser(emailFromForm);
String passwordFromDB = userThatLogsIn.getPassword();
if (passwordFromDB.equals(passwordFromForm)) {
request.getSession().setAttribute("TheLoggedInUser", userThatLogsIn);
response.sendRedirect("/Slit/welcome.jsp");
} else {
request.setAttribute("error", "Unknown login, try again");
response.sendRedirect("/Slit/LoginFailed.jsp");
}
} catch (NullPointerException nullPointer) {
System.err.println("NullPointerException: " + nullPointer.getMessage());
response.sendRedirect("/Slit/LoginFailed.jsp");
}
}
Servlet2: Im getting a nullpointer sessionaccept fnavn
at Mypage.MyPageServlet.sessionAccept(MyPageServlet.java:40)
private void sessionAccept(HttpServletRequest request, HttpServletResponse response) throws IOException {
HttpSession session = request.getSession();
session.setMaxInactiveInterval(30 * 60);
User loggedInUser = (User) request.getAttribute("TheLoggedInUser");
String fnavn = loggedInUser.getfName();
String enavn = loggedInUser.getlName();
String epost = loggedInUser.getEmail();
request.getSession().setAttribute("messageJSP", "Velkommen" + epost);
response.sendRedirect("Innstillinger.jsp");
}
This line
User loggedInUser = (User) request.getAttribute("TheLoggedInUser");
has to replaced with
User loggedInUser = (User)
request.getSession().getAttribute("TheLoggedInUser");

application deployed in server works in chrome but not in firefox and IE

We've recently deployed an application in our tomcat server. It's working properly when we used Chrome, but when we've tried it in Firefox, it's not. The same goes for IE.
We've checked and found that when in Chrome, the status is 200.
But in Firefox or IE, the status alternates from 302 to 200.
Also, there are times when it works in those two browsers.
Here's some code snippets which might help :
private SecurityContext processSession(final HttpSession session) {
LOG.info("SESSION ID: {}", session.getId());
final int maxAppSessionTimeout = 28800;
final String ssc = "SPRING_SECURITY_CONTEXT";
// set context
SecurityContext context = (SecurityContext) session.getAttribute(ssc);
// set session timeout in seconds
session.setMaxInactiveInterval(maxAppSessionTimeout);
return context;
}
We suspect that it is being caused by the method above since it sometimes returns null when in Firefox or IE. This method is being called by the code below :
public final void doFilter(final ServletRequest request,
final ServletResponse response, final FilterChain chain)
throws IOException, ServletException {
User user = getUser();
String userId = "";
String uname = "";
HttpServletRequest httpRequest = (HttpServletRequest) request;
HttpServletResponse httpResponse = (HttpServletResponse) response;
HttpSession session = httpRequest.getSession(false);
SecurityContext context = null;
String logURL = httpRequest.getRequestURI();
String logParams = httpRequest.getQueryString();
LOG.info("lOG URI: {}", logURL);
LOG.info("lOG URI PARAMS: {}", logParams);
if (session != null) {
// validate and add new parameters in session
context = processSession(session);
// sanitize cookies
processCookies(httpRequest, httpResponse);
// commit
}
// anti x-frame
// httpresponse.addHeader("X-FRAME-OPTIONS", "SAMEORIGIN");
httpResponse.addHeader("X-Content-Type-Options", "nosniff");
httpResponse.addHeader("X-XSS-Protection", "1; mode=block");
try {
if (user != null) {
userId = user.getUid();
uname = user.getUsername();
if (StringUtils.isNotBlank(userId)
&& StringUtils.isNotBlank(uname)) {
if (session.getAttribute("fullname") == null) {
// add user name in session
session.setAttribute("fullname", uname);
}
if (session.getAttribute("userId") == null) {
// add user nadme in session
session.setAttribute("userId", userId);
}
}
initiateLogger(session, userId, request.getRemoteAddr(),
"userLogged");
}
} catch (Exception e) {
LOG.error("Exception while getting employee information.", e);
}
System.out.println("context " + context);
if ("/MTBBR/".equalsIgnoreCase(logURL) || context != null) {
try {
chain.doFilter(request, response);
} catch (Exception e) {
throw new ServletException(e);
}
} else {
httpResponse.setStatus(HttpURLConnection.HTTP_MOVED_TEMP);
}
}
Could you guys help us figure this out?
Thanks a lot!

Unrecognized temporary token when attempting to complete authorization: FITBIT4J

I am trying to create a app for fitbit using fitbit4j . I found their sample code
at
https://github.com/apakulov/fitbit4j/blob/master/fitbit4j-example-client/src/main/java/com/fitbit/web/FitbitApiAuthExampleServlet.java
When i tried to implement it I am getting many errors.
below is their doGet function()
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
FitbitAPIClientService<FitbitApiClientAgent> apiClientService = new FitbitAPIClientService<FitbitApiClientAgent>(
new FitbitApiClientAgent(apiBaseUrl, fitbitSiteBaseUrl, credentialsCache),
clientConsumerKey,
clientSecret,
credentialsCache,
entityCache,
subscriptionStore
);
if (request.getParameter("completeAuthorization") != null) {
String tempTokenReceived = request.getParameter(OAUTH_TOKEN);
String tempTokenVerifier = request.getParameter(OAUTH_VERIFIER);
APIResourceCredentials resourceCredentials = apiClientService.getResourceCredentialsByTempToken(tempTokenReceived);
if (resourceCredentials == null) {
throw new ServletException("Unrecognized temporary token when attempting to complete authorization: " + tempTokenReceived);
}
// Get token credentials only if necessary:
if (!resourceCredentials.isAuthorized()) {
// The verifier is required in the request to get token credentials:
resourceCredentials.setTempTokenVerifier(tempTokenVerifier);
try {
// Get token credentials for user:
apiClientService.getTokenCredentials(new LocalUserDetail(resourceCredentials.getLocalUserId()));
} catch (FitbitAPIException e) {
throw new ServletException("Unable to finish authorization with Fitbit.", e);
}
}
try {
UserInfo userInfo = apiClientService.getClient().getUserInfo(new LocalUserDetail(resourceCredentials.getLocalUserId()));
request.setAttribute("userInfo", userInfo);
request.getRequestDispatcher("/fitbitApiAuthExample.jsp").forward(request, response);
} catch (FitbitAPIException e) {
throw new ServletException("Exception during getting user info", e);
}
} else {
try {
response.sendRedirect(apiClientService.getResourceOwnerAuthorizationURL(new LocalUserDetail("-"), exampleBaseUrl + "/fitbitApiAuthExample?completeAuthorization="));
} catch (FitbitAPIException e) {
throw new ServletException("Exception during performing authorization", e);
}
}
}
When i run the code it goes into the 'else' part first and i get the URL with
localhost:8080/fitbitApiAuthExample?completeAuthorization=&oauth_token=5bccadXXXXXXXXXXXXXXXXXXXXXXXXXX&oauth_verifier=h35kXXXXXXXXXXXXXXXXX, and i get the fitbit login screen and when i log in
and since the
'completeAuthorization==null',
it is executing the else part again.So i manually added a value so that it will enter the 'if' section .
So the new URL became
localhost:8080/fitbitApiAuthExample?completeAuthorization=Success&oauth_token=5bccadXXXXXXXXXXXXXXXXXXXXXXXXXX&oauth_verifier=h35kXXXXXXXXXXXXXXXXX and entered the 'if' section.
Now am getting the exception
'Unrecognized temporary token when attempting to complete authorization:'I tried many workarounds but still cant understand the error.
Please Help.
Solved the problem. the 'apiClientService' was going null when i reload the servlet. Made it member variable and everything started working.
public class NewServlet extends HttpServlet {
public String apiBaseUrl = "api.fitbit.com";
public String webBaseUrl = "https://www.fitbit.com";
public String consumerKey = "your key";
public String consumerSecret = "your secret";
public String callbackUrl = "*****/run?Controller=Verifier";
public FitbitAPIClientService<FitbitApiClientAgent> apiClientService = null;
public String oauth_token = null;
public String oauth_verifier = null;
public String token = null;
public String tokenSecret = null;
public String userId = null;
public APIResourceCredentials resourceCredentials=null;
public FitbitApiClientAgent agent =null;
public LocalUserDetail user=null;
public Gson gson =null;
public UserInfo userInfo=null;
private static Properties getParameters(String url) {
Properties params = new Properties();
String query_string = url.substring(url.indexOf('?') + 1);
String[] pairs = query_string.split("&");
for (String pair : pairs) {
String[] kv = pair.split("=");
params.setProperty(kv[0], kv[1]);
}
return params;
}
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException, ParserConfigurationException, SAXException, Exception {
PrintWriter out = response.getWriter();
response.addHeader("Access-Control-Allow-Origin", "*");
// out.println(" ----- process Request Called-----");
String controllerValue = request.getParameter("Controller");
// out.println(" Controller Request : "+param);
if (controllerValue == null) {
// out.println(" inside if part ");
FitbitAPIEntityCache entityCache = new FitbitApiEntityCacheMapImpl();
FitbitApiCredentialsCache credentialsCache = new FitbitApiCredentialsCacheMapImpl();
FitbitApiSubscriptionStorage subscriptionStore = new FitbitApiSubscriptionStorageInMemoryImpl();
FitbitApiClientAgent apiClientAgent = new FitbitApiClientAgent(apiBaseUrl, webBaseUrl, credentialsCache);
out.println("testing2");
apiClientService
= new FitbitAPIClientService<FitbitApiClientAgent>(
apiClientAgent,
consumerKey,
consumerSecret,
credentialsCache,
entityCache,
subscriptionStore
);
// out.println("<script>localStorage.setItem('api',apiClientService);</script>");
LocalUserDetail userDetail = new LocalUserDetail("-");
try {
// out.println("testing4");
String authorizationURL = apiClientService.getResourceOwnerAuthorizationURL(userDetail, callbackUrl);
out.println("access by web browser: " + authorizationURL);
out.println("Your web browser shows redirected URL.");
out.println("Input the redirected URL and push Enter key.");
response.sendRedirect(authorizationURL);
} catch (FitbitAPIException ex) {
out.println("exception : " + ex);
//Logger.getLogger(NewServlet.class.getName()).log(Level.SEVERE, null, ex);
}
} else if (controllerValue.equalsIgnoreCase("Verifier")) {
oauth_token = request.getParameter("oauth_token");
oauth_verifier = request.getParameter("oauth_verifier");
resourceCredentials = apiClientService.getResourceCredentialsByTempToken(oauth_token);
if (resourceCredentials == null) {
out.println(" resourceCredentials = null ");
throw new Exception("Unrecognized temporary token when attempting to complete authorization: " + oauth_token);
}
if (!resourceCredentials.isAuthorized()) {
resourceCredentials.setTempTokenVerifier(oauth_verifier);
apiClientService.getTokenCredentials(new LocalUserDetail(resourceCredentials.getLocalUserId()));
}
userId = resourceCredentials.getLocalUserId();
token = resourceCredentials.getAccessToken();
tokenSecret = resourceCredentials.getAccessTokenSecret();
user = new LocalUserDetail(userId);
userInfo = apiClientService.getClient().getUserInfo(new LocalUserDetail(resourceCredentials.getLocalUserId()));
user = new LocalUserDetail(userId);
agent = apiClientService.getClient();
response.sendRedirect("http://localhost:8084/FitbitClientCheck/");
}

Categories

Resources