Wednesday, 8 March 2017

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

setAttribute():

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");

getRequestDispatcher():

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

getSession():

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

its returntype is HttpSession. 

request.getSession();  

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(fals) returns a HttpSession, if the session is already exists and returns null if not.   


getParameter():

request.getParameter("productId"); 

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();

request.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.

request.getQueryString();  


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.
 

 


0 comments:

Post a Comment

Note: only a member of this blog may post a comment.