I have a servlet:
public class TestServlet extends HttpServlet {
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.getSession().setAttribute("user", "Test cookie");
req.getRequestDispatcher("test.jsp").forward(req, resp);
}
}
And I have a JSP:
<% String name = request.getParameter("user"); %>
<%= name%>
But if I run the code, the output is null, why?
Can you tell me why? What is easy way to get the "user" cookie.
You should use getAttribute(...) not getParameter(...) like this :
<% String name = session.getAttribute("user"); %>
Not.
<% String name = request.getParameter("user"); %>
getParameter() returns the value of a request parameter as a String, or null if the parameter does not exist.
getAttribute() returns the value of the named attribute as an Object, or null if no attribute of the given name exists.
Attribute, available for the life of the session.
Parameter, only available for the life of the request
"But if I run the code, the output is null, why"?
If you have set the attribute on the session, that attribute does not exist on the request, hence the null returned from
request.getParameter("user");
You need to get it from the session like so:
session.getAttribute("user");
Use implicit session object
session.getAttribute( "user" );
Beginners book -jsp implicit-object-session
Related
This question already has answers here:
Show JDBC ResultSet in HTML in JSP page using MVC and DAO pattern
(6 answers)
Closed 7 years ago.
I've been a PHP developer but recently need to work on some project using Google App Engine (Java). In PHP I can do something like this (in term of MVC model):
// controllers/accounts.php
$accounts = getAccounts();
include "../views/accounts.php";
// views/accounts.php
print_r($accounts);
I take a look at some demos of Google App Engine Java using Servlet and JSP. What they're doing is this:
// In AccountsServlet.java
public class AccountsServlet extends HttpServlet {
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String action = req.getParameter("accountid");
// do something
// REDIRECT to an JSP page, manually passing QUERYSTRING along.
resp.sendRedirect("/namedcounter.jsp?name=" + req.getParameter("name"));
}
}
Basically in the Java case it's 2 different HTTP requests (the second one being automatically forced), right? So in JSP file I can't make use of the data calculated in the Servlet.
Is there some way I can do it similar to the PHP way?
You will need to set the data retrieved in the servlet in request scope so that the data is available in JSP
You will have following line in your servlets.
List<Account> accounts = getAccounts();
request.setAttribute("accountList",accounts);
Then in JSP you can access this data using the expression language like below
${accountList}
I would use request dispatches instead of the sendRedirect as follows
RequestDispatcher rd = sc.getRequestDispatcher(url);
rd.forward(req, res);
If you can use RequestDispatcher then you can store these values in request or session object and get in other JSP.
Is there any specific purpose of using request.sendRedirect?. If not use RequestDispatcher.
See this link for more details.
public class AccountServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
List<Account> accounts = getAccountListFromSomewhere();
String url="..."; //relative url for display jsp page
ServletContext sc = getServletContext();
RequestDispatcher rd = sc.getRequestDispatcher(url);
request.setAttribute("accountList", accounts );
rd.forward(request, response);
}
}
What you want to do is first define an object to represent the information from getAccounts() - something like AccountBean.
Then in your servlets doPost or doGet function, use the request info to populate your AccountBean object.
You can then store the AccountBean object either in the request, session, or servlet context by using the setAttribute method, and forward the request to the JSP page.
The AccountBean data in your jsp page is extracted using the and tags.
Here might be an example of your servlet:
protected void doPost(HttpServletRequest req, HttpServletResponse resp) {
// get data from request querystring
String accountId = req.getParameter("accountid");
// populate your object with it (you might want to check it's not null)
AccountBean accountBean = new AccountBean(accountId);
// store data in session
HttpSession session = req.getSession();
session.setAttribute("accountBean", accountBean);
// forward the request (not redirect)
RequestDispatcher dispatcher = req.getRequestDispatcher("account.jsp");
dispatcher.forward(req, resp);
}
Then your JSP page would have the following to display the account information:
<jsp:useBean id="accountBean" type="myBeans.AccountBean" />
Your account is <jsp:getProperty name="accountBean" property="status" />
Besides what's mentioned above about using expression lang, you can also pass attributes via request itself. In Servlet's doGet(), we write something like:
Account[] accounts = AccountManager.getAccountList();
request.setAttribute("accountList", accounts );
RequestDispatcher rd = req.getRequestDispatcher(nextJSPurl);
rd.forward(req, resp);
In JSP, we can retrieve the attribute from request:
<%
Account[] accounts= (Account[])request.getAttribute("accountList");
if (accounts.length>0) {
for (Account account: accounts) {
%>
<blockquote>account name: <%= account.getName() %></blockquote>
<%
}
}
%>
import javax.servlet.http.*;
public class AccountsServlet extends HttpServlet {
public void doGet (HttpServletRequest request, HttpServletResponse response) {
try {
// Set the attribute and Forward to hello.jsp
request.setAttribute ("somename", "someValue"); // to save your temporary calculations.
getServletConfig().getServletContext().getRequestDispatcher("/namedcounter.jsp?name=" + req.getParameter("name")).forward(request, response);
} catch (Exception ex) {
ex.printStackTrace ();
}
}
}
In the above code servlet will not create 2 different requests. It will forward, also will retain all data from original request.
request.setAttribute ("somename", "someValue"); // to save your temporary calculations.
This is my understanding of your question - you want to redirect or dispatch to a new JSP page along with the data calculated in Servlet, right? To do so you need to set request attributes before dispatching the request.
You can set attributes using HttpServletRequest object (req.setAttribute("attribute name", "attribute value")). Attribute value can be any Java object.
You can retrieve the value by req.getAttribute("attribute name"). You'll also need to type cast the object while user getAttribute() function.
You can set the data inside java beans and easily access that data onto jsp page when control goes to jsp. set the date in java beans using setters get access those data onto jsp page by including that bean into jsp.
<%#page contentType="text/html"%>
<jsp:useBean id="man" class="beans.Person"/>
<jsp:setProperty name="man" property="*"/>
First Name: <jsp:getProperty name="man" property="firstName"/>
like this you can access as many properties your bean class can have.
I made a LoginServlet with Java, that gets username and password from a database. Now I want to display the username on my website after logging in.
Servlet Code:
public class LoginServlet extends HttpServlet {
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String username = req.getParameter("username");
String password = req.getParameter("password");
Sql2o sql2o = DatabaseConnetcionProvider.getSql2oConnection();
User user = UserDAO.findBenutzerByUsername(username, sql2o);
if(user != null && user.getPassword().equals(password)){
UserListe.getInstance().add(user);
HttpSession session = req.getSession();
session.setAttribute("user", user);
resp.sendRedirect("/public/Home.html");
} else {
resp.sendRedirect("/public/Error.html");
}
}
}
Now I want to display the username on my Website.
I hope you can help me :)
In case of JSP you can use session implicit object
<%= ((User) session.getAttribute("user")).getUsername %>
You can retrieve value in your Home.html as below
<script type="text/javascript">
$(document).ready(function() {
userName = "{{user}}";
$("#yourFieldName").val(userName);
});
</script>
if the page is static html page,the static page can not handle the servlet page scope data,use jsp or other dynamic page to handle it,freemarker,velocity is suitable.
in jsp,you can use EL Express to show the data.the format is ${sessionScope.user}.
you should review the pageScope,requestScope,sessionScope,applicationScope concept.
sendRedirect method can cause data missing in pageScope,you should choose the right scope and the redirect or forward method,test it,please.
if the page is static page,please use AJAX to send request and handle the data,jQuery library is classic.
I am new to servlets and JSPs.
Recently.. I have been trying to send data from my Servlet to JSP using requestDispatcher.
This is my Servlet code responsible:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
sampleClass sampleObject = new sampleClass(1, "myname");
ObjectMapper mapper = new ObjectMapper();
String jsonstring = mapper.writeValueAsString(sampleObject);
request.setAttribute("values", jsonstring);
request.setAttribute("valuees", "testing");
request.getRequestDispatcher("/somejsp").forward(request, response);
}
My JSP part responsible for retrieving data:
${values}
${valuees}
<%
//out.println(Message);
Enumeration enume = request.getParameterNames();
for (Entry<String, String[]> entry : request.getParameterMap().entrySet()) {
String name = entry.getKey();
String value = entry.getValue()[0];
// ...
}
String value = request.getParameter("values");
out.println(value);
String valuee = request.getParameter("valuees");
out.println(valuee);
%>
But the output I get is:
{"n":1,"name":"myname"} testing null null
as you can see both the EL gives correct output, the implementation with the Enumeration returns nothing and the other two return null.
I donot understand this. I couldn't find any solution online.
You're confusing attributes (any object that you choose to store in the request, under a name you choose), with parameters (strings sent by the browser as part of the request, as in foo=bar&baz=2.
I want Create Session in CheckForLogin Servlet and Use it in all JSP pages(For checking).
What should Write in my JSP pages and instead of ......... in Sevlet.How to define Session in Servlet?
public void service(ServletRequest request,
ServletResponse response) throws ServletException, IOException {
String email = request.getParameter("email");
String password = request.getParameter("password");
if (email.equals("") || password.equals("") || email == null || password == null) {
request.getRequestDispatcher("Error.jsp?err=enterdata").forward(request,response);
} else {
UserBl userBl = new UserBl();
if (userBl.checkUser(email, password)) {
..........................
request.getRequestDispatcher("Home.jsp").forward(request, response);
} else {
request.getRequestDispatcher("Error.jsp?err=nulluser").forward(request, response);
}
}
}
I Should Write HttpServletRequest instead of ServletRequest and HttpServletResponse instead of ServletResponse in method parameters and then Create Session and access to session
session is jsp implicit variable using which you get session in JSP page.
example:
<%
String temp=session.getAttribute( "tvName");
%>
or using EL
<c:out value="${session.getAttribute("name")}"/>
Note: Using scriptlets in JSP pages is not good practice.
Actually you can use <%= request.getSession() %> for example.
Use ${sessionScope.sessionAttributeName} in Expression Language in JSP code.
I suggest you use include instead of forward
you should use this line
Session httpsession = request.getSession();
This line will create a new session object for you if one doesn't exist or it will return the existing session associated with the same client .
to get existing session use
HttpSession session=request.getSession(false);
I'm using jsp of out-of-box portlet like feed.jspf in Liferay 6:
String articleId =null;
HttpServletRequest httpReq = PortalUtil.getOriginalServletRequest(PortalUtil.getHttpServletRequest(renderRequest));
articleId = httpReq.getParameter("articleId");
It is giving a null value whether in custom portlet or in .jsp files, but it should have a value.
Sure, you can always use the standard HttpServletRequest to retrieve your parameters from. You can get this request by using the PortalUtil class, like in the following example:
HttpServletRequest request = PortalUtil.getHttpServletRequest(portletRequest);
String articleId = request.getParameter("articleId");
In my Liferay- JSP I use this:
<!-- ... some imports... -->
<!-- ... some more imports... -->
<%# page import="com.liferay.portal.util.PortalUtil" %>
<portlet:defineObjects /> <!-- Liferay-specific, defines renderRequest etc.-->
<%
HttpServletRequest r = PortalUtil.getHttpServletRequest(renderRequest);
String wellHole = PortalUtil.getOriginalServletRequest(r).getParameter("well_hole");
%>
(this combines fragments of wisdom from other answers, notably Miguel Gil MartÃnez's answer from 2012 Jul 23 at 17:35
When working with portlets, each HttpServletRequest paramenter has a prefix which informs the "type" of the parameter and a suffix expressing which instance of the portlet should process it. So, the name of the parameters is not just "articleId". I do not know what portlet are you working but if it was a portlet called, let's say, "example" deployed through a war the parameter would be called example_WAR_exampleportletwar_articleId_w2Xd.
However, you do not have to deal with such complexity. If you are working within a JSP of some already created portlet, there should be an object called renderRequest which contains all parameters and abstracts all this name mangling. So, instead of retrieving the original servlet requestion you an use it:
String articleId = renderRequest.getParamenter("articleId");
If this object is not defined, you just need to insert the <portlet:defineObjects/> tag somewhere and after this the object will be available.
HTH. Let us know if it worked!
It worked for me:
public void doView(RenderRequest request, RenderResponse response) throws
PortletException, IOException {
HttpServletRequest requestInsideThePortlet = PortalUtil.getHttpServletRequest(request);
String myURLParam =
PortalUtil.getOriginalServletRequest(requestInsideThePortlet).getParameter("myURLParam");
....
....
....
}
For JSF I use this:
#ManagedBean
#RequestScoped
public class OriginalRequest {
private HttpServletRequest getOriginalRequest() {
return PortalUtil.getOriginalServletRequest(
PortalUtil.getHttpServletRequest(
(PortletRequest) FacesContext.getCurrentInstance()
.getExternalContext().getRequest() ) );
}
public String getParam( String name ) {
return getOriginalRequest().getParameter( name );
}
public List<String> getParamNames() {
return Collections.list( getOriginalRequest().getParameterNames() );
}
}
Then in your facelet:
#{originalRequest.getParam('my_param')}
I tried ur solutions but render request it gives me an exception,
so this is another solution:
public String obtainFromUrl(String keyFromWeb) {
Object outcome = null;
Map<String, Object> map = FacesContext.getCurrentInstance().getExternalContext().getRequestMap();
if (map != null) {
for (String key : map.keySet()) {
if (map.get(key) instanceof HttpServletRequestWrapper) {
HttpServletRequest request = (HttpServletRequest) ((HttpServletRequestWrapper) map.get(key))
.getRequest();
outcome = request.getParameter(keyFromWeb);
break;
}
}
}
return (String) outcome;
}