JAVA EE: Some frequenty/important methods to remember in HttpServletRequest


setting attribute value in HttpServetRequest is same as putting key/value pair in HashMap, except the key is always String and value can be any Object. 

1. request.setAttribute("Products", "Products");
2. request.setAttribute("Products",this.products);


if u want to forward the request to another jsp page or servlet in the same web application, you can use this method.  

1. request.getRequestDispatcher("/WEB-INF/jsp/view/viewCart.jsp").forward(request, response);


How can u get the session in java web application? you can get the session in the following way.

its returntype is HttpSession. 


getSession() always returns a HttpSession. If the session is already exists, it returns that session else it creates a new session and returns it. 

getSession(false) returns a HttpSession, if the session is already exists and returns null if not.   



remember, getParameter always returns String, you have to cast to appropriate datatype as per your business requirement. 

How to get request url?

you can get request url, by calling getRequestURL();


How to get Query string from a request?

getQueryString() method will give you query string. The query string is nothing but string that comes after '?' in url.


How to get the IP address of client?

getRemoteAddr() method returns the IP address of the client. Just be careful, the remote IP address may or may not the address of the client. If the client is using some proxy or DHCP, then the IP address can and will change during the session.  

How to get the IP address of the server the application is running on?

getLocalAddr() gives the IP address of the server.