Login Controller:
package test;
import java.io.IOException;
import java.util.ArrayList;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.webappmvc.mvc.controller.Controller;
public class Login implements Controller{
public void doProcess(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession();
System.out.println("UserName Parameter Value: " + request.getParameter("username"));
if(request.getParameter("login") != null && request.getParameter("userName") != null && request.getParameter("password") != null){
if(!request.getParameter("userName").equals("") && !request.getParameter("password").equals("") && request.getParameter("login").equals("Login")){
ArrayList<String> data = (ArrayList<String>) request.getAttribute("model");
for(int i=0; i<data.size(); i+=2){
System.out.println("Username from DB: " + data.get(i) + "\nPassword: " + data.get(i+1));
// if(request.getParameter("username").toString().equals(data.get(i))){
// if(request.getParameter("password").toString().equals(data.get(i+1).toString())){
// session.setAttribute("loggedUser", data.get(i).toString());
// response.sendRedirect("home");
// return;
// }
// request.setAttribute("errorMsg", "Invalid Login");
// }
}
}
}
System.out.println("Result view is: " + request.getAttribute("view"));
request.getRequestDispatcher(request.getAttribute("view").toString()).forward(request, response);
}
public String addMapping() {
return "/login";
}
}
Here, Every request going through WebappController class defined in com.webappmvc.mvc.controller.Controller, com.webappmvc.mvc.controller.Controller#doGet method select controller, model, view on runtime, then forward it to com.webappmvc.mvc.controller.ResponseController#doGet
Then, In response Controller, some code like this which forward request, response client project Controller#doProcess method.
Controller controller = (Controller) request.getAttribute("controller");
controller.doProcess(request, response);
With these, when i tried to acces /login, LoginController getting called, But
getParameter() returning null each and every time. I also tried to acces this URL
Requested URL:
http://localhost:8080/FreameworkTest/controller/login?userName=test&password=test&login=Login
I'm Getting Output in console like these.
Console Output:
All request passing through WebApp Controller //From WebAppController
----- From Response Controller //From WebAppResponseController
UserName Parameter Value: null //From LoginController
Username from DB: jitu
Password: 12345
Result view is: /WEB-INF/views/Login.jsp
You are using send :
userName=test
And get the attribute with
request.getParameter("username");
You made a typo. Use instead
request.getParameter("userName");
Error you didn't do in the second part.
NOTE:
I suggest you define constant value for those instead of use a String literal
private final statis String USER_NAME = "userName";
And use it each time you need
request.getParameter(USER_NAME);
Related
I want to make a login process using mvc structure where i send userid and password from index.jsp page.If they match with the database value then it will go to the stater001.jsp.In index.jsp i've 2 fields userid and password from.I've post userid and pwd into LoginServlet servlet.
LoginServlet process userid , pwd making the instance of loginAuthentication class.loginAuthentication class checks whether userid and password exists in database or not with select query.I have also used setter getter classuser to set userid and pwd into session.I tried to do the whole login process in an organised way.But i'm stucked with error i couldn't under stand what is the problem please help me to solve this.First i tried it without using mvc pattern then it worked fine.But now it is not working.
Below is my previous code all process in one servlet
package DataAccess;
import DataAccess.dbconnector;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
import java.util.logging.Level;
import java.util.logging.Logger;
#WebServlet(urlPatterns = {"/LoginServlet"})
public class LoginServlet extends HttpServlet {
String userid, pwd;
Connection connection = null;
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
Statement statement = null;
userid = request.getParameter("uname");
pwd = request.getParameter("pass");
try {
dbconnector dbc = new dbconnector();
connection = dbc.Open();
PreparedStatement ps = connection.prepareStatement("select * from member where uname='" + userid + "' and pass='" + pwd + "'");
ResultSet rs = ps.executeQuery();
if (rs.next()) {
HttpSession session = request.getSession();
session.setAttribute("userid", userid);
response.sendRedirect("view/starter001.jsp");
} else {
request.setAttribute("errorMessage", "Invalid user or password");
RequestDispatcher rd = getServletContext().getRequestDispatcher("/index.jsp");
rd.include(request, response);
}
} catch (Exception e) {
e.printStackTrace();
}
finally {
try {
connection.close();
} catch (SQLException ex) {
Logger.getLogger(LoginServlet.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
And in my new code here i've stucked with error in execution
And here i've attached my new edited codes where i tried to do this in an organised way .My errors have been gone but not showing the userid after login http://pastebin.com/RKyieMqn
Please consider my question
at first when all codes were in loginservlet then it was like but when i start using mvc structure it is not showing the username
Obviously, you pasted the wrong code:
In the below statement, where is the variable user defined?
session.setAttribute("user", user);
Perhaps, you have created a authenticateUser object somewhere. Please check you code to find it.
I have changed session.setAttribute("userid", user); to session.setAttribute("userid", user.getUserId()); and now it's working
I am trying to send a request to my jsp page i.e manufacturer details and get the attribute via session, but it throws a 500 error.
package com.osahub.disaster.controller;
import java.io.IOException;
import static com.osahub.disaster.controller.Ofymethodadmin.ofy;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.*;
import com.osahub.disaster.controller.SendMail;
#SuppressWarnings("serial")
public class admin extends HttpServlet {
public void doPost(HttpServletRequest req, HttpServletResponse resp)
throws IOException, ServletException {
resp.setContentType("text/plain");
resp.getWriter().println("Data Saved!");
PrintWriter out = resp.getWriter();
String name= req.getParameter("name");
String address = req.getParameter("address");
String email = req.getParameter("email");
String website = req.getParameter("website");
String topex = req.getParameter("topex");
String topdes = req.getParameter("topdes");
String topmob = req.getParameter("topmob");
String year = req.getParameter("year");
String brand = req.getParameter("brand");
String factory = req.getParameter("factory");
String sector = req.getParameter("sector");
String contactpername = req.getParameter("contactpername");
String contactperdes = req.getParameter("contactperdes");
String contactpermob = req.getParameter("contactpermob");
HttpSession currentSession=req.getSession();
currentSession.setAttribute("name", name);
req.getRequestDispatcher("ManufacturerDetails.jsp").forward(req, resp);
SendMail mail = new SendMail();
mail.send(email, "send Test mail from gae" , "this is the mail body");
ManufacturerDetails ad = new ManufacturerDetails(name,address,email,website,topex,topdes,topmob,year,brand,factory,sector,contactpername,contactperdes,contactpermob);
ofy().save().entity(ad);
ofy().clear();
List<ManufacturerDetails> li = ofy().load().type(ManufacturerDetails.class).list();
Iterator<ManufacturerDetails> iter = li.iterator();
while(iter.hasNext())
{
ManufacturerDetails ad1 = iter.next();
System.out.println(ad1.getName());
System.out.println(ad1.getAddress());
System.out.println(ad1.getEmail());
System.out.println(ad1.getWebsite());
System.out.println(ad1.getTopex());
System.out.println(ad1.getTopdes());
System.out.println(ad1.getTopmob());
System.out.println(ad1.getYear());
System.out.println(ad1.getBrand());
System.out.println(ad1.getFactory());
System.out.println(ad1.getSector());
System.out.println(ad1.getContactpername());
System.out.println(ad1.getContactpermob());
System.out.println(ad1.getContactperdes());
}
resp.sendRedirect("about.jsp");
}
}
A response with HTTP status code 500 can be caused by any exception.
However, it looks like in your case the exception is thrown because you call resp.sendRedirect("about.jsp"); after req.getRequestDispatcher("ManufacturerDetails.jsp").forward(req, resp);.
You cannot do that, because once the call to forward() completes, the response is committed. However, it does not mean that doPost() method returns control, it keeps executing. Thus, resp.sendRedirect("about.jsp"); causes java.lang.IllegalStateException exception to be thrown, since the response is already closed.
You have to review your method, and introduce a conditional statement:
if (condition) {
// do something
req.getRequestDispatcher("ManufacturerDetails.jsp").forward(req, resp);
} else {
// do something
resp.sendRedirect("about.jsp");
}
Another option is to introduce an explicit return after req.getRequestDispatcher("ManufacturerDetails.jsp").forward(req, resp);.
500 exception occurs due to the server problem . It is cause because you can write both code - getRequestDispatcher and sendRedirect for execute . And this is not possible . You can not do this because after once send the request paramater it terminate . So you can write both code in if-else condition .
I am new to servlet development, and I was reading an ebook, and found that I can redirect to a different web page using
setHeader("Location", "http://www.google.com")
But this is not working, as I have written this code as:
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class ModHelloWorld extends HttpServlet{
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException{
// response.addHeader("Location", "http://www.google.com");
response.setHeader("Location", "http://www.google.com");
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("<html><head><title>Modified Hello World</title></head><body>");
pw.println("<h1>");
//getInitParameter function reads the contents ot init-param elements.
pw.println(getInitParameter("message"));
pw.println("</h1>");
pw.println("</body></html>");
pw.close();
}
}
i have checked the headers using my program to get the headers of the webpage which is as under:
import java.net.*;
import java.io.*;
class getHeaders{
public static void main(String args[]){
URL url = null;
URLConnection urc = null;
try {
url = new URL(args[0]);
urc = url.openConnection();
for(int i=0 ; ; i++) {
String name = urc.getHeaderFieldKey(i);
String value = urc.getHeaderField(i);
if(name == null && value == null)//both null so end of header
break;
else if(name == null){//first line of header{
System.out.println("Server HTTP version, Response code: ");
System.out.println(value);
System.out.println("ENd of first header field");
} else {
System.out.println("name of header is: " + name + " and its value is : " + value);
}
}
} catch(MalformedURLException e){
System.out.println("Malformed URL " + e.getMessage());
} catch(IOException e){
e.printStackTrace();
}
}
}
And i am getting the output as:
Server HTTP version, Response code:
HTTP/1.1 200 OK
ENd of first header field
name of header is: Server and its value is : Apache-Coyote/1.1
name of header is: Location and its value is : http://www.google.com
name of header is: Content-Type and its value is : text/html
name of header is: Content-Length and its value is : 101
name of header is: Date and its value is : Sat, 05 Mar 2011 15:27:29 GMT
But I was not redirected to google's page from my browser.
Thanks in advance:)
Oh no no! That's not how you redirect. It's far more simpler:
public class ModHelloWorld extends HttpServlet{
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException{
response.sendRedirect("http://www.google.com");
}
}
Also, it's a bad practice to write HTML code within a servlet. You should consider putting all that markup into a JSP and invoking the JSP using:
response.sendRedirect("/path/to/mynewpage.jsp");
As you can see, the response is still HTTP/1.1 200 OK. To indicate a redirect, you need to send back a 302 status code:
response.setStatus(HttpServletResponse.SC_FOUND); // SC_FOUND = 302
Alternatively, you could try the following,
resp.setStatus(301);
resp.setHeader("Location", "index.jsp");
resp.setHeader("Connection", "close");
Another way of doing this if you want to redirect to any url source after the specified point of time
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
public class MyServlet extends HttpServlet
{
public void doGet(HttpServletRequest request,HttpServletResponse response) throws IOException
{
response.setContentType("text/html");
PrintWriter pw=response.getWriter();
pw.println("<b><centre>Redirecting to Google<br>");
response.setHeader("refresh,"5;https://www.google.com/"); // redirects to url after 5 seconds
pw.close();
}
}
Preface
This is my first attempt at a Filter, be gentle.
Project Description
I am trying to finalize a build for a SSO for several of our applications and I seem to be hitting a wall. The webapp I am attempting to connect to uses the "Authentication" header to determine user credentials within the application. I have built a Filter with hopes of setting the header before it is passed on to the webapp.
The Problem
The code passes eclipse validation, compiles, loads to Tomcat, and passes through to the webapp. The only thing that is missing is the Authentication header.
What am I missing/doing wrong?
AuthenticationFilter source
package xxx.xxx.xxx.xxx.filters;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import xxx.xxx.xxx.ConfigFile;
import xxx.xxx.xxx.Console;
import xxx.xxx.xxx.FalseException;
import xxx.xxx.activity.EncryptUtil;
public class AuthenticationFilter implements Filter {
public ConfigFile config;
public void init(FilterConfig arg0) throws ServletException {
config = new ConfigFile("C:/config.properties");
}
public void doFilter(ServletRequest sRequest, ServletResponse sResponse, FilterChain filterChain) throws IOException, ServletException {
Console.debug("AuthenticationFilter.doFilter() triggered.");
ServletRequestWrapper request = new ServletRequestWrapper((HttpServletRequest) sRequest);
HttpServletResponse response = (HttpServletResponse) sResponse;
HttpSession session = request.getSession();
Cookie cookie = null;
try {
if (request.getParameter("logout") != null) {
session.invalidate();
throw new FalseException("Logout recieved");
}
String auth = request.getHeader("Authorization");
if (auth == null) {
Console.debug("Authorization Header not found.");
// get cookie --COOKIE NAME--
Cookie[] cookies = request.getCookies();
if (cookies == null) {
throw new FalseException("Cookies not set.");
}
for (int i = 0; i < cookies.length; i++) {
if (cookies[i].getName().equals(config.getProperty("authentication.cookie.name"))) {
cookie = cookies[i];
}
}
if (cookie == null) {
throw new FalseException("Cannot find Cookie (" + config.getProperty("authentication.cookie.name") + ") on Client");
}
Console.debug("Cookie (" + config.getProperty("authentication.cookie.name") + ") found on Client. value="+cookie.getValue());
String decToken = decryptToken(cookie.getValue());
Console.debug("Decrypted Token: "+decToken);
Console.debug("Setting Authorization Header...");
request.setAttribute("Authorization", decToken);
request.addHeader("Authorization", decryptToken(cookie.getValue()));
Console.debug("Authorization Header set.");
Console.debug("Validating Authorization Header value: "+request.getHeader("Authorization"));
}
}catch (FalseException e) {
Console.msg(e.getMessage() + ", giving the boot.");
response.sendRedirect(config.getProperty("application.login.url"));
} catch (Exception e) {
Console.error(e);
}
Console.debug("AuthenticationFilter.doFilter() finished.");
filterChain.doFilter(request, response);
}
public void destroy() {
}
private String decryptToken(String encToken) {
String token = null;
token = EncryptUtil.decryptFromString(encToken);
return token;
}
}
web.xml source
<web-app>
<filter>
<filter-name>AuthenticationFilter</filter-name>
<display-name>AuthenticationFilter</display-name>
<description></description>
<filter-class>com.xxx.xxx.xxx.filters.AuthenticationFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>AuthenticationFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
...
</web-app>
ServletRequestWrapper Source
package com.xxx.xxx.xxx.filters;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
public class ServletRequestWrapper extends javax.servlet.http.HttpServletRequestWrapper {
public ServletRequestWrapper(HttpServletRequest request) {
super(request);
headerMap = new HashMap();
}
private Map headerMap;
public void addHeader(String name, String value) {
headerMap.put(name, new String(value));
}
public Enumeration getHeaderNames() {
HttpServletRequest request = (HttpServletRequest) getRequest();
List list = new ArrayList();
for (Enumeration e = request.getHeaderNames(); e.hasMoreElements();) {
list.add(e.nextElement().toString());
}
for (Iterator i = headerMap.keySet().iterator(); i.hasNext();) {
list.add(i.next());
}
return Collections.enumeration(list);
}
public String getHeader(String name) {
Object value;
if ((value = headerMap.get("" + name)) != null)
return value.toString();
else
return ((HttpServletRequest) getRequest()).getHeader(name);
}
}
Debug Log
LoginServlet.doGet() triggered.
[DEBUG] : Authenticate.isClientLoggedIn() triggered.
xxx url : https://xxx.xxx.xxx/xxx/home.action
[DEBUG] : Authenticate.isClientLoggedIn() status code: 401
Unauthorized User.
Client IS NOT logged in.
-- Fill out Login Form, submit --
LoginServlet.doPost() triggered.
[DEBUG] : Authenticate.isClientLoggedIn() triggered.
xxx url : https://xxx.xxx.xxx./xxx/home.action
[DEBUG] : Authenticate.isClientLoggedIn() status code: 401
Unauthorized User.
Client IS NOT logged in.
Client (--USERID--) attempting basic authentication with password(--PASSWORD--).
[DEBUG] : BasicAuthentication.touch(http://localhost:PORT/vu/loginCheck.html, --USERID--, --PASSWORD--) triggered.
[DEBUG] : BasicAuthentication.touch() response code: 200
Client (--USERID--) has been logged IN.
Client (--USERID--) basic authentication finished, Client is logged in.
Client (--USERID--) logged in successfully.
[DEBUG] : Cookie (xxx_token) Set: 1e426f19ebdfef05dec6544307addc75401ecdc908a3c7e6df5336c744--SECRET--
[DEBUG] : Redirecting client to https://xxx.xxx.xxx/xxx/home.action
-- Redirected to webapp, filter recieves --
[DEBUG] : AuthenticationFilter.doFilter() triggered.
[DEBUG] : Authorization Header not found. << Initical check to see if user is already logged in to site
[DEBUG] : Cookie (xxx_token) found on Client. value=1e426f19ebdfef05dec6544307addc75401ecdc908a3c7e6df5336c744--SECRET--
[DEBUG] : Decrypted Token: Basic --SECRET--
[DEBUG] : Setting Authorization Header...
[DEBUG] : Authorization Header set.
[DEBUG] : Validating Authorization Header value: Basic --SECRET-- << Value matches Decrypted Token
[DEBUG] : AuthenticationFilter.doFilter() finished.
-- Web Application errors out, unable to find Authorization header
Thanks for your help.
I'm adding a new answer, since it's completely different.
I did a test on my system. I copied your code, dumped the cookie test, and wrote a simple Servlet to dump things out for me.
And it worked fine, save for one caveat.
I don't know how your app is using this. But your ServletRequestWrapper implements getHeaderNames, and getHeader, but it does NOT implement getHeaders. I ran in to that problem as I used getHeaders to try and dump the request, and, of course, Authorization was missing.
So, you may want to look at your code closer to see if it is indeed not using getHeaders. If it is, it will "work fine", but completely skip the work you've done, and thus miss your Authorization header.
Here's my implementation, and it worked for me.
#Override
public Enumeration getHeaders(String name) {
Enumeration e = super.getHeaders(name);
if (e != null && e.hasMoreElements()) {
return e;
} else {
List l = new ArrayList();
if (headerMap.get(name) != null) {
l.add(headerMap.get(name));
}
return Collections.enumeration(l);
}
}
First, the most basic question (kind of an "is this plugged in" question), I assume that your cookies are all rooted in the same domain, and that you're not trying to get cross domain behavior here. Because cookies won't do that.
Beyond the cookie test, this looks fine. But it all hinges on the cookie test.
If you want to test the Authorization header, then you can simply short circuit the cookie test (i.e. it always passes) and populate the Authorization header with some valid value. This will, in the short term, test your whole Authorization scheme.
Once that's done/fixed, then you can focus on the cookie setting and delivery.
I also assume that you're not using Java EE Container based authentication, with Tomcat doing this check for you. In that case, a filter is simply "too late". The container will have already made it's decisions before your filter even gets called.
If you are using container based authentication, and your apps are on the same container, I would imagine Tomcat (or someone) has an SSO option at the container level. I know that Glassfish will do this for you out of the box. It should be straightforward to modify Tomcat artifacts (i.e. not portable Java EE/Servlet mechanisms) to implement this if that is the case.
I've created two servlets:
UserReceiverServlet receives a username from a form. It then sets the username to an attribute and forwards the request to UserDisplayServlet.
UserDisplayServlet will add the username to a cookie and then display the current continents of both the attribute which was set and the cookie which was stored.
However, while I've managed to determine that the cookie is definitely being created and the value is being stored, when this Servlet goes to look for it, it doesn't find it
Here is UserDisplayServlet. It is correctly receiving a value through request.getAttribute("username"), so attributeUsername isn't the problem...
/**
*
*/
package hu.flux.user;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.http.*;
/**
* #author Brian Kessler
*
*/
public class UserDisplayServlet extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 1L;
public void service (HttpServletRequest request, HttpServletResponse response)
{
response.setContentType("text/html");
String attributeUsername = (String) request.getAttribute("username");
String cookieUsername = null;
for (Cookie cookie: request.getCookies())
{ if (cookie.getName() == "username")
{
String value = cookie.getValue();
if (value.isEmpty()) { value = "--- EMPTY ---"; }
cookieUsername = cookie.getValue();
break;
}
}
if (cookieUsername == null) {cookieUsername = "--- NOT FOUND ---"; }
String newCookieValue;
if (!(cookieUsername.isEmpty())) { newCookieValue = cookieUsername;}
else if (!(attributeUsername.isEmpty())) { newCookieValue = cookieUsername;}
else { newCookieValue = "UNKOWN";}
Cookie usernameCookie = new Cookie ("username", attributeUsername);
usernameCookie.setMaxAge(24*60*60);
response.addCookie(usernameCookie);
PrintWriter out = null;
try { out = response.getWriter(); }
catch (IOException e)
{
System.err.print ("Cannot getWriter():" + e);
e.printStackTrace();
}
out.println("<html>");
out.println("<head>");
out.println("<title>User Display Servlet</title>");
out.println("</head>");
out.println("<body");
if ((attributeUsername != null) && (!(attributeUsername.isEmpty())))
{
out.println ("<p>I have an attribute which says your username is "
+ request.getAttribute("username") + "</p>");
}
else { out.println ("<p>The attribute hasn't been set.</p>"); }
if ((cookieUsername != null) && (!(cookieUsername.isEmpty())))
{
out.println ("<p>You have a cookie which says your username is " + cookieUsername + "</p>");
out.println ("</body></html>");
}
else { out.println ("<p>The cookie hasn't been set.</p>"); }
}
}
If it is helpful, here is the servlet that is receiving the input and forwarding it to the above servlet:
/**
*
*/
package hu.flux.user;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.*;
/**
* This simple servlet receives a username from a form,
* stores the name in a context attribute,
* and forwards the context attribute to another servlet
* which displays the name.
*
* #author Brian Kessler
*
*/
public class UserReceiverServlet extends HttpServlet
{
/**
*
*/
private static final long serialVersionUID = 1L;
public void service (HttpServletRequest request, HttpServletResponse response)
{
String username = request.getParameter("username");
request.setAttribute("username", username);
try {
getServletConfig()
.getServletContext()
.getRequestDispatcher("/userdisplay")
.forward(request, response);
} catch (ServletException e) {
System.err.println ("Can't forward: " + e);
e.printStackTrace();
} catch (IOException e) {
System.err.println ("Can't forward: " + e);
e.printStackTrace();
}
}
}
What am I missing to retrieve the value to stored in the cookie?
Found the problem:
if (cookie.getName() == "username")
should have been:
if (name.equals("username"))
That always trips me up!
How do you know that a cookie has not been set? The HTML body certainly won't tell you because the content is evaluated on the server side not the client side. If you really want the page to tell you if a cookie has been set successfully, you'll need to embed some javascript in the HTML to access the browser's cookie store.
If I was trying to solve this problem, I'd start by looking at the HTTP responses on the server and client side. On the server-side turn on response dumping / logging supported by your webapp container; e.g. for Tomcat, turn on the RequestDumperValve. On the client-side, use the browser's preferences dialogs (or whatever) to look at the contents of the cookie store for the server you are interacting with. Then use the browser's Javascript debugger (or whatever) to see whether the response headers contain headers to set the cookies. (If you are using firefox, install the firebug plugin.)