Use Java variable in HTML File - java

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.

Related

retrive session attribute and sort it into String [duplicate]

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.

Java servlet create cookie and then read from JSP is null

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

Not able to access request parameters in java servlets

I am using same dpPost method for two different form data. I am not able to access request parameters for second form.
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
if("schema".equals(session.getAttribute("which"))) {
second_html();
//call second page here
}
String btnClicked= request.getParameter("p2"); // This is getting null after submitting second_html()
if("edit".equals(session.getAttribute("which"))){
/* process second page here after Submit on the second page
I am trying to access request.getParameter() but value is null here for the fields in the second page */
second_html();
}
}
first_html() {
// have form and submit button
session.setAttribute("which","schema");
}
second_html() {
// have form and submit button
<input type='text' name='p2' id='p2' size='3' >
session.setAttribute("which","edit");
}
EDIT : My session getters are working fine. But the request.getParameter is not working.
You are accessing session variables, not your request parameters.
You can access them using
request.getParameter("which")
If I understand your question, you should be using ServletRequest.getParameter(String),
String v = request.getParameter("which");
if (v.equals("schema")) {
} else if (v.equals("edit")) {
}

display a message coming from servlet on jsp page in javascript alert box

Can anyone tell me a way to display a message in javascript alert box,that message is comming from a servlet.Please help.
You need AJAX.
Javascript will send a request to the servlet, retrieve the message from the servlet response, and then display it in the alert box.
Various tutorials on the web, including this one
You can store servlet variables in javascript variables, i.e. (JSP) :
<script language="javascript">
function displayObject(){
var javascriptVar="${servletObject}";
alert(javascriptVar);
}
</script>
</script>
</head>
<body onload="displayObject()">
</body>
</html>
To be able to use servletObject, you first need to put it in the server as an attribute in your doGet or doPost function :
public class YourClassName extends HttpServlet {
public static final String VUE = "/WEB-INF/yourPageName.jsp";
public void doGet( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException {
request.setAttribute( "ExampleValue", servletObject );
this.getServletContext().getRequestDispatcher( VUE ).forward( request, response );
}
}

Create Session in Servlet and Use in JSP pages?

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

Categories

Resources