How would I pass hidden parameters? I want to call a page (test.jsp) but also pass 2 hidden parameters like a post.
response.sendRedirect("/content/test.jsp");
TheNewIdiot's answer successfully explains the problem and the reason why you can't send attributes in request through a redirect. Possible solutions:
Using forwarding. This will enable that request attributes could be passed to the view and you can use them in form of ServletRequest#getAttribute or by using Expression Language and JSTL. Short example (reusing TheNewIdiot's answer] code).
Controller (your servlet)
request.setAttribute("message", "Hello world");
RequestDispatcher dispatcher = servletContext().getRequestDispatcher(url);
dispatcher.forward(request, response);
View (your JSP)
Using scriptlets:
<%
out.println(request.getAttribute("message"));
%>
This is just for information purposes. Scriptlets usage must be avoided: How to avoid Java code in JSP files?. Below there is the example using EL and JSTL.
<c:out value="${message}" />
If you can't use forwarding (because you don't like it or you don't feel it that way or because you must use a redirect) then an option would be saving a message as a session attribute, then redirect to your view, recover the session attribute in your view and remove it from session. Remember to always have your user session with only relevant data. Code example
Controller
//if request is not from HttpServletRequest, you should do a typecast before
HttpSession session = request.getSession(false);
//save message in session
session.setAttribute("helloWorld", "Hello world");
response.sendRedirect("/content/test.jsp");
View
Again, showing this using scriptlets and then EL + JSTL:
<%
out.println(session.getAttribute("message"));
session.removeAttribute("message");
%>
<c:out value="${sessionScope.message}" />
<c:remove var="message" scope="session" />
Generally, you cannot send a POST request using sendRedirect() method. You can use RequestDispatcher to forward() requests with parameters within the same web application, same context.
RequestDispatcher dispatcher = servletContext().getRequestDispatcher("test.jsp");
dispatcher.forward(request, response);
The HTTP spec states that all redirects must be in the form of a GET (or HEAD).
You can consider encrypting your query string parameters if security is an issue.
Another way is you can POST to the target by having a hidden form with method POST and submitting it with javascript when the page is loaded.
Using session, I successfully passed a parameter (name) from servlet #1 to servlet #2, using response.sendRedirect in servlet #1. Servlet #1 code:
protected void doPost(HttpServletRequest request, HttpServletResponse response) {
String name = request.getParameter("name");
String password = request.getParameter("password");
...
request.getSession().setAttribute("name", name);
response.sendRedirect("/todo.do");
In Servlet #2, you don't need to get name back. It's already connected to the session. You could do String name = (String) request.getSession().getAttribute("name"); ---but you don't need this.
If Servlet #2 calls a JSP, you can show name this way on the JSP webpage:
<h1>Welcome ${name}</h1>
To send a variable value through URL in response.sendRedirect(). I have used it for one variable, you can also use it for two variable by proper concatenation.
String value="xyz";
response.sendRedirect("/content/test.jsp?var="+value);
Use this:
out.println("<script>window.location.href = \"hoadon?OrderId=" + getIdOrder + "\"\n</script>>");
Related
For context I have a jsp called "withdraw.jsp" that calls a servlet that processes a withdrawal. In this servlet I would like to pass a string message if the transaction is successful or not and I would like to send this message to the same jsp that called the servlet (which is still "withdraw.jsp". Here is what I did so far
//In the servlet
RequestDispatcher view = request.getRequestDispatcher("registeredUser/withdraw.jsp");
String error = (String)ex.getMessage();
request.setAttribute("errorMessage", error);
view.include(request,response); // i also tried forward here
//In the jsp
<% if(request.getParameter("errorMessage") != null){ %>
<p> <%=(String)request.getParameter("errorMessage")%> </p>
<% } %>
If I run this code, the jsp wouldn't retrieve the errorMessage since it is null despite being set as an attribute by the servlet. Any help?
You are confusing attributes with parameters.
The message is always null in your JSP because you have set an attribute in you servlet, but in your JSP you are looking for a parameter. They are different things.
Things to do:
.forward(...) to your JSP using the RequestDispatcher;
make sure you retrieve an attribute in your JSP;
do not use scriptlets. Depending on your JSP version you can use EL expressions or JSTL.
I've developed an HTML page that sends information to a Servlet. In the Servlet, I am using the methods doGet() and doPost():
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
String id = req.getParameter("realname");
String password = req.getParameter("mypassword");
}
public void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
String id = req.getParameter("realname");
String password = req.getParameter("mypassword");
}
In the html page code that calls the Servlet is:
<form action="identification" method="post" enctype="multipart/form-data">
User Name: <input type="text" name="realname">
Password: <input type="password" name="mypassword">
<input type="submit" value="Identification">
</form>
When I use method = "get" in the Servlet, I get the value of id and password, however when using method = "post", id and password are set to null. Why don't I get the values in this case?
Another thing I'd like to know is how to use the data generated or validated by the Servlet. For example, if the Servlet shown above authenticates the user, I'd like to print the user id in my HTML page. I should be able to send the string 'id' as a response and use this info in my HTML page. Is it possible?
Introduction
You should use doGet() when you want to intercept on HTTP GET requests. You should use doPost() when you want to intercept on HTTP POST requests. That's all. Do not port the one to the other or vice versa (such as in Netbeans' unfortunate auto-generated processRequest() method). This makes no utter sense.
GET
Usually, HTTP GET requests are idempotent. I.e. you get exactly the same result everytime you execute the request (leaving authorization/authentication and the time-sensitive nature of the page —search results, last news, etc— outside consideration). We can talk about a bookmarkable request. Clicking a link, clicking a bookmark, entering raw URL in browser address bar, etcetera will all fire a HTTP GET request. If a Servlet is listening on the URL in question, then its doGet() method will be called. It's usually used to preprocess a request. I.e. doing some business stuff before presenting the HTML output from a JSP, such as gathering data for display in a table.
#WebServlet("/products")
public class ProductsServlet extends HttpServlet {
#EJB
private ProductService productService;
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
List<Product> products = productService.list();
request.setAttribute("products", products); // Will be available as ${products} in JSP
request.getRequestDispatcher("/WEB-INF/products.jsp").forward(request, response);
}
}
Note that the JSP file is explicitly placed in /WEB-INF folder in order to prevent endusers being able to access it directly without invoking the preprocessing servlet (and thus end up getting confused by seeing an empty table).
<table>
<c:forEach items="${products}" var="product">
<tr>
<td>${product.name}</td>
<td>detail</td>
</tr>
</c:forEach>
</table>
Also view/edit detail links as shown in last column above are usually idempotent.
#WebServlet("/product")
public class ProductServlet extends HttpServlet {
#EJB
private ProductService productService;
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Product product = productService.find(request.getParameter("id"));
request.setAttribute("product", product); // Will be available as ${product} in JSP
request.getRequestDispatcher("/WEB-INF/product.jsp").forward(request, response);
}
}
<dl>
<dt>ID</dt>
<dd>${product.id}</dd>
<dt>Name</dt>
<dd>${product.name}</dd>
<dt>Description</dt>
<dd>${product.description}</dd>
<dt>Price</dt>
<dd>${product.price}</dd>
<dt>Image</dt>
<dd><img src="productImage?id=${product.id}" /></dd>
</dl>
POST
HTTP POST requests are not idempotent. If the enduser has submitted a POST form on an URL beforehand, which hasn't performed a redirect, then the URL is not necessarily bookmarkable. The submitted form data is not reflected in the URL. Copypasting the URL into a new browser window/tab may not necessarily yield exactly the same result as after the form submit. Such an URL is then not bookmarkable. If a Servlet is listening on the URL in question, then its doPost() will be called. It's usually used to postprocess a request. I.e. gathering data from a submitted HTML form and doing some business stuff with it (conversion, validation, saving in DB, etcetera). Finally usually the result is presented as HTML from the forwarded JSP page.
<form action="login" method="post">
<input type="text" name="username">
<input type="password" name="password">
<input type="submit" value="login">
<span class="error">${error}</span>
</form>
...which can be used in combination with this piece of Servlet:
#WebServlet("/login")
public class LoginServlet extends HttpServlet {
#EJB
private UserService userService;
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String username = request.getParameter("username");
String password = request.getParameter("password");
User user = userService.find(username, password);
if (user != null) {
request.getSession().setAttribute("user", user);
response.sendRedirect("home");
}
else {
request.setAttribute("error", "Unknown user, please try again");
request.getRequestDispatcher("/login.jsp").forward(request, response);
}
}
}
You see, if the User is found in DB (i.e. username and password are valid), then the User will be put in session scope (i.e. "logged in") and the servlet will redirect to some main page (this example goes to http://example.com/contextname/home), else it will set an error message and forward the request back to the same JSP page so that the message get displayed by ${error}.
You can if necessary also "hide" the login.jsp in /WEB-INF/login.jsp so that the users can only access it by the servlet. This keeps the URL clean http://example.com/contextname/login. All you need to do is to add a doGet() to the servlet like this:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.getRequestDispatcher("/WEB-INF/login.jsp").forward(request, response);
}
(and update the same line in doPost() accordingly)
That said, I am not sure if it is just playing around and shooting in the dark, but the code which you posted doesn't look good (such as using compareTo() instead of equals() and digging in the parameternames instead of just using getParameter() and the id and password seems to be declared as servlet instance variables — which is NOT threadsafe). So I would strongly recommend to learn a bit more about basic Java SE API using the Oracle tutorials (check the chapter "Trails Covering the Basics") and how to use JSP/Servlets the right way using those tutorials.
See also:
Our servlets wiki page
Java EE web development, where do I start and what skills do I need?
Servlet returns "HTTP Status 404 The requested resource (/servlet) is not available"
Show JDBC ResultSet in HTML in JSP page using MVC and DAO pattern
Update: as per the update of your question (which is pretty major, you should not remove parts of your original question, this would make the answers worthless .. rather add the information in a new block) , it turns out that you're unnecessarily setting form's encoding type to multipart/form-data. This will send the request parameters in a different composition than the (default) application/x-www-form-urlencoded which sends the request parameters as a query string (e.g. name1=value1&name2=value2&name3=value3). You only need multipart/form-data whenever you have a <input type="file"> element in the form to upload files which may be non-character data (binary data). This is not the case in your case, so just remove it and it will work as expected. If you ever need to upload files, then you'll have to set the encoding type so and parse the request body yourself. Usually you use the Apache Commons FileUpload there for, but if you're already on fresh new Servlet 3.0 API, then you can just use builtin facilities starting with HttpServletRequest#getPart(). See also this answer for a concrete example: How to upload files to server using JSP/Servlet?
Both GET and POST are used by the browser to request a single resource from the server. Each resource requires a separate GET or POST request.
The GET method is most commonly (and is the default method) used by browsers to retrieve information from servers. When using the GET method the 3rd section of the request packet, which is the request body, remains empty.
The GET method is used in one of two ways:
When no method is specified, that is when you or the browser is requesting a simple resource such as an HTML page, an image, etc.
When a form is submitted, and you choose method=GET on the HTML tag. If the GET method is used with an HTML form, then the data collected through the form is sent to the server by appending a "?" to the end of the URL, and then adding all name=value pairs (name of the html form field and value entered in that field) separated by an "&"
Example:
GET /sultans/shop//form1.jsp?name=Sam%20Sultan&iceCream=vanilla HTTP/1.0 optional headeroptional header<< empty line >>>
The name=value form data will be stored in an environment variable called QUERY_STRING.
This variable will be sent to a processing program (such as JSP, Java servlet, PHP etc.)
The POST method is used when you create an HTML form, and request method=POST as part of the tag. The POST method allows the client to send form data to the server in the request body section of the request (as discussed earlier). The data is encoded and is formatted similar to the GET method, except that the data is sent to the program through the standard input.
Example:
POST /sultans/shop//form1.jsp HTTP/1.0 optional headeroptional header<< empty line >>> name=Sam%20Sultan&iceCream=vanilla
When using the post method, the QUERY_STRING environment variable will be empty.
Advantages/Disadvantages of GET vs. POST
Advantages of the GET method:
Slightly faster
Parameters can be entered via a form or by appending them after the URL
Page can be bookmarked with its parameters
Disadvantages of the GET method:
Can only send 4K worth of data. (You should not use it when using a textarea field)
Parameters are visible at the end of the URL
Advantages of the POST method:
Parameters are not visible at the end of the URL. (Use for sensitive data)
Can send more that 4K worth of data to server
Disadvantages of the POST method:
Can cannot be bookmarked with its data
The servlet container's implementation of HttpServlet.service() method will automatically forward to doGet() or doPost() as necessary, so you shouldn't need to override the service method.
Could it be that you are passing the data through get, not post?
<form method="get" ..>
..
</form>
If you do <form action="identification" > for your html form, data will be passed using 'Get' by default and hence you can catch this using doGet function in your java servlet code. This way data will be passed under the HTML header and hence will be visible in the URL when submitted.
On the other hand if you want to pass data in HTML body, then USE Post: <form action="identification" method="post"> and catch this data in doPost function. This was, data will be passed under the html body and not the html header, and you will not see the data in the URL after submitting the form.
Examples from my html:
<body>
<form action="StartProcessUrl" method="post">
.....
.....
Examples from my java servlet code:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
PrintWriter out = response.getWriter();
String surname = request.getParameter("txtSurname");
String firstname = request.getParameter("txtForename");
String rqNo = request.getParameter("txtRQ6");
String nhsNo = request.getParameter("txtNHSNo");
String attachment1 = request.getParameter("base64textarea1");
String attachment2 = request.getParameter("base64textarea2");
.........
.........
I have this little java project in which I have to use jsp files.
I have an html with a login button that triggers the following function:
var loginCall = "user/login";
var logoutCall = "user/logout";
var signupCall = "user/signup";
function login() {
var login = baseUrl + loginCall + "?";
var loginFormElements = document.forms.loginForm.elements;
login = addParam(login, USER_NAME, loginFormElements.userName.value, false);
login = addParam(login, PASSWORD, loginFormElements.password.value, true);
simpleHttpRequest(login, function(responseText){
var status = evalJSON(responseText);
if (status.errorCode == 200) {
var res = status.results;
var sessionId = res[0].sessionId;
setCookie(SESSION_ID,sessionId);
window.location="http://localhost:8080/"+baseUrl+"/main.html";
} else {
showError(status.errorCode, "Username or password was incorrect.")
}
}, function(status, statusText){console.log('z');
showError(status, statusText);
});
}
As far as I can see a httpRequest is made and sent with data to baseUrl + loginCall, meaning localhost/something/user/login?name=somename&pass=somepass
This is where I'm stuck, do I have to make a java file somewhere somehow, that takes the request information, works it up with the database and returns an answer?
If so, where, how? Do I have to name it login/user.java?
Can anyone point me to the right direction, if not give me some code example or explanation of what I have to do next?
You need to have another look at the JSP MVC
The jsp page should hold the html and javascript and java code. If you want to call a separate .java class, you need to write that class as a servlet then call it.
So in your .jsp you have you html and javascript just like you have it there, then any java you include in these brackets <% %>
Have a look at the tutorials here http://www.jsptut.com/
And i see your doing a login page. I used this brilliant tutorial for creating a log in system which helped me understand how jsp and servlets worked.
http://met.guc.edu.eg/OnlineTutorials/JSP%20-%20Servlets/Full%20Login%20Example.aspx
Also check out this image which should help you understand the concept. Remember servlets are pure java classes, used for mostly java but can also output html, jsp's are used for mostly html (& javascript) but can include jsp. So the servlets do the work, then the jsp gets the computed values so that they can be utilized by JavaScript. that's how i think of it anyway, may be wrong
http://met.guc.edu.eg/OnlineTutorials/static/article_media/jsp%20-%20servlets/LoginExample%20[4].jpg
All the best
If you are not using any MVC framework then best approach would be to extending HttpServlet classes for handling requests and doing all heavy lifting tasks such as business logic processing,accessing/updating databases etc. and then dispatching the request to .jsp files for presentation.In .jsp.You can also add custom objects to request scope that you wish to access on '.jsp' pages + using expression language you can access most request related implicit objects
I taken a typical example of flow in brief.You may can an idea and explore in deep yourself.
Here is java servlet class that will handle a posted form.
public class doLogin extends HttpServlet{
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException {
String username= request.getParameter("username"); // get username/pasword from form
String password = request.getParameter("password");
// This is your imaginary method for checking user authentication from database
if(checkUserAuthentication(username,password)){
/*
user is authenticated.Now fetch data for user to be shown on homepage
User is another class that holds user info. Initialize it with data received from database
*/
user userData = new User;
user.setName(...);
user.setAge(...);
user.setInfo(...);
// etc
}
RequestDispatcher view = req.getRequestDispatcher("login.jsp");
req.setAttribute("userdata", userData); // set user object in current request scope
view.forward(req, resp);//forward to login.jsp
}
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException {
}
but you need a form with some action to invoke above ServletClass
<form action="/checkLogin" method="POST">
<input type="text" name="username" value="">
<input type="password" name="password" value="">
<input type="submit" name="login" value="Login">
</form>
To tell your Servlet container to invoke doLogin class on form login button click
you have to configure it in deployment descriptor file web.xml which is part of standard dynamic web application in java
In web.xml' following xml snippet make apllication server aware ofdoLogin` class
<servlet>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>com.yourdomain.doLogin</servlet-class>
</servlet>
But its not mapped to any url yet,It is configured as below in <servlet-mapping> section in web.xml
<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/checkLogin</url-pattern>
</servlet-mapping>
Now any post request to url /checkLogin will invole doPost method on doLogin class
After successful login request will be trasfered to 'login.jsp' page.
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
You can use java code in sciptlet <% %> syntax to access userData object
<%
User data = (User)request.getAttribute('userData');
%>
Better and tidy approach is to use expression language
${ pageContext.request.userData.name }
Above expression calls getName() method on object of User class using java beans naming conventions
Here, you can learn more about expression language
May be some time later I can improve this and provide you more insight.Hope that helps :)
I'm trying to retrieve attribute values set by a servlet in a JSP page, but I've only luck with parameters by ${param}. I'm not sure about what can I do different. Maybe its simple, but I couldn't manage it yet.
public void execute(HttpServletRequest request, HttpServletResponse response) {
//there's no "setParameter" method for the "request" object
request.setAttribute("attrib", "attribValue");
RequestDispatcher rd = request.getRequestDispatcher("/Test.jsp");
rd.forward(request,response);
}
In the JSP I have been trying to retrieve the "attribValue", but without success:
<body>
<!-- Is there another tag instead of "param"??? -->
<p>Test attribute value: ${param.attrib}
</body>
If I pass a parameter through all the process (invoking page, servlets and destination page), it works quite good.
It's available in the default EL scope already, so just
${attrib}
should do.
If you like to explicitly specify the scope (EL will namely search the page, request, session and application scopes in sequence for the first non-null attribute value matching the attribute name), then you need to refer it by the scope map instead, which is ${requestScope} for the request scope
${requestScope.attrib}
This is only useful if you have possibly an attribute with exactly the same name in the page scope which would otherwise get precedence (but such case usually indicate poor design after all).
See also:
Our EL wiki page
Java EE 6 tutorial - Expression Language
Maybe a comparison between EL syntax and scriptlet syntax will help you understand the concept.
param is like request.getParameter()
requestScope is like request.getAttribute()
You need to tell request attribute from request parameter.
have you tried using an expression tag?
<%= request.getAttribute("attrib") %>
If the scope is of request type, we set the attribute using request.setAttribute(key,value) in request and retrieve using ${requestScope.key} in jsp .
What is the difference between getAttribute() and getParameter() methods within HttpServletRequest class?
getParameter() returns http request parameters. Those passed from the client to the server. For example http://example.com/servlet?parameter=1. Can only return String
getAttribute() is for server-side usage only - you fill the request with attributes that you can use within the same request. For example - you set an attribute in a servlet, and read it from a JSP. Can be used for any object, not just string.
Generally, a parameter is a string value that is most commonly known for being sent from the client to the server (e.g. a form post) and retrieved from the servlet request. The frustrating exception to this is ServletContext initial parameters which are string parameters that are configured in web.xml and exist on the server.
An attribute is a server variable that exists within a specified scope i.e.:
application, available for the life of the entire application
session, available for the life of the session
request, only available for the life of the request
page (JSP only), available for the current JSP page only
request.getParameter()
We use request.getParameter() to extract request parameters (i.e. data sent by posting a html form ). The request.getParameter() always returns String value and the data come from client.
request.getAttribute()
We use request.getAttribute() to get an object added to the request scope on the server side i.e. using request.setAttribute(). You can add any type of object you like here, Strings, Custom objects, in fact any object. You add the attribute to the request and forward the request to another resource, the client does not know about this. So all the code handling this would typically be in JSP/servlets. You can use request.setAttribute() to add extra-information and forward/redirect the current request to another resource.
For example,consider about first.jsp,
//First Page : first.jsp
<%# page import="java.util.*" import="java.io.*"%>
<% request.setAttribute("PAGE", "first.jsp");%>
<jsp:forward page="/second.jsp"/>
and second.jsp:
<%# page import="java.util.*" import="java.io.*"%>
From Which Page : <%=request.getAttribute("PAGE")%><br>
Data From Client : <%=request.getParameter("CLIENT")%>
From your browser, run first.jsp?CLIENT=you and the output on your browser is
From Which Page : *first.jsp*
Data From Client : you
The basic difference between getAttribute() and getParameter() is that the first method extracts a (serialized) Java object and the other provides a String value. For both cases a name is given so that its value (be it string or a java bean) can be looked up and extracted.
It is crucial to know that attributes are not parameters.
The return type for attributes is an Object, whereas the return type for a parameter is a String. When calling the getAttribute(String name) method, bear in mind that the attributes must be cast.
Additionally, there is no servlet specific attributes, and there are no session parameters.
This post is written with the purpose to connect on #Bozho's response, as additional information that can be useful for other people.
The difference between getAttribute and getParameter is that getParameter will return the value of a parameter that was submitted by an HTML form or that was included in a query string. getAttribute returns an object that you have set in the request, the only way you can use this is in conjunction with a RequestDispatcher. You use a RequestDispatcher to forward a request to another resource (JSP / Servlet). So before you forward the request you can set an attribute which will be available to the next resource.
-getParameter() :
<html>
<body>
<form name="testForm" method="post" action="testJSP.jsp">
<input type="text" name="testParam" value="ClientParam">
<input type="submit">
</form>
</body>
</html>
<html>
<body>
<%
String sValue = request.getParameter("testParam");
%>
<%= sValue %>
</body>
</html>
request.getParameter("testParam") will get the value from the posted form of the input box named "testParam" which is "Client param". It will then print it out, so you should see "Client Param" on the screen. So request.getParameter() will retrieve a value that the client has submitted. You will get the value on the server side.
-getAttribute() :
request.getAttribute(), this is all done server side. YOU add the attribute to the request and YOU submit the request to another resource, the client does not know about this. So all the code handling this would typically be in servlets.getAttribute always return object.
getParameter - Is used for getting the information you need from the Client's HTML page
getAttribute - This is used for getting the parameters set previously in another or the same JSP or Servlet page.
Basically, if you are forwarding or just going from one jsp/servlet to another one, there is no way to have the information you want unless you choose to put them in an Object and use the set-attribute to store in a Session variable.
Using getAttribute, you can retrieve the Session variable.
from http://www.coderanch.com/t/361868/Servlets/java/request-getParameter-request-getAttribute
A "parameter" is a name/value pair sent from the client to the server
- typically, from an HTML form. Parameters can only have String values. Sometimes (e.g. using a GET request) you will see these
encoded directly into the URL (after the ?, each in the form
name=value, and each pair separated by an &). Other times, they are
included in the body of the request, when using methods such as POST.
An "attribute" is a server-local storage mechanism - nothing stored in
scoped attribues is ever transmitted outside the server unless you
explicitly make that happen. Attributes have String names, but store
Object values. Note that attributes are specific to Java (they store
Java Objects), while parameters are platform-independent (they are
only formatted strings composed of generic bytes).
There are four scopes of attributes in total: "page" (for JSPs and tag
files only), "request" (limited to the current client's request,
destroyed after request is completed), "session" (stored in the
client's session, invalidated after the session is terminated),
"application" (exist for all components to access during the entire
deployed lifetime of your application).
The bottom line is: use parameters when obtaining data from the
client, use scoped attributes when storing objects on the server for
use internally by your application only.
Another case when you should use .getParameter() is when forwarding with parameters in jsp:
<jsp:forward page="destination.jsp">
<jsp:param name="userName" value="hamid"/>
</jsp:forward>
In destination.jsp, you can access userName like this:
request.getParameter("userName")
Basic difference between getAttribute() and getParameter() is the return type.
java.lang.Object getAttribute(java.lang.String name)
java.lang.String getParameter(java.lang.String name)