Usually i can find solution provided by StackOverflow community in older questions. This time my brain stopped working, i guess...
All I'm trying to do is show a list of customers which I'm taking out of MySQL database. Everything is going fine, but when i'm passing the List from controller to view I can't use it in jsp file, as it appears to be out of scope(?).
If you could suggest any solutions / links / tutorials i would be really thankful
CustomerDAO:
public List<Customer> getAllCustomers()
{
EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("library-manager");
EntityManager entityManager = entityManagerFactory.createEntityManager();
TypedQuery<Customer> query = entityManager.createQuery("select e from Customer e", Customer.class);
List<Customer> customers = query.getResultList();
entityManager.close();
entityManagerFactory.close();
return customers;
}
CustomersController:
#RequestMapping(value = "/getAllCustomers")
public ModelAndView getAllCustomers(){
List<Customer> customers = customerDAO.getAllCustomers();
return new ModelAndView("getAllCustomers", "customersList", customers);
}
At this point I have no clue how to access this List in my jsp file (getAllCustomers.jsp).
When I try to access it in Java block <% %>, then I get simple errors like:
"customers cannot be resolved to a variable"
getAllCustomers.jsp:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# page import="db_objects.Customer" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h2>List of all customers:</h2>
<%
for(Customer customer : customers){
out.println(customer.getCustomerFirstName);
out.println(customer.getCustomerLastName);
out.println(customer.getCustomerContactNumber);
}
%>
</body>
</html>
I hope you will find some patience to help me a little bit here :)
edit
I got some information that my question may be the same as this one
I'm not sure if it's automatic system or not, but my question is not how to use for loop but how to pass a collection to jsp via ModelAndView.
edit2
I just figured it out what #RamPrakash meant. I will try his solution tomorrow.
But until then, maybe someone from different timezone could answer if using scriptlet instead of JSTL may cause that problem?
Thanks in advance!
In your jsp you are referring to the customers list by customers. This however is only a valid identifier in the context of the getAllCustomers method of your controller.
Try customersList instead and consult the JavaDoc of the ModelAndView
Related
I am trying to build a site that displays report results based on a date range inputted by the user. First I built the front-end "aesthetics" part of it in HTML/CSS/JS using dummy json data to retrieve the results. Now I am trying to eliminate the json and actually integrate it with the backend, which I have no experience with so am struggling a bit.
Right now I have a Java servlet written, and it works alright. I'm writing the ResultSet from the database query by doing response.getWriter().write(""); Now from what I've seen the next step is to display the results by appending to the URL, but the code that formats and displays it properly is just a div currently. What is the proper way to do this/modify the code?
Sorry if this is a badly written question, I'm not totally sure of all the terminology or best practices, although I'm trying to learn.
EDIT: Currently on the html page I have
$('#gen-report').click(function(){
$("#auction-report").fadeIn({ duration: 400 });
}
In the auction-report div is all of my formatting & elements (charts, displays, etc.) Is there a way to make use of this code instead of having to start my jsp page from scratch?
Put parameters in servlet to request, then invoke forward from request.getRequestDispatcher.
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setAttribute("now", LocalDate.now());
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/view/test.jsp");
dispatcher.forward(request, response);
}
Now you have access to params which you put in request. Here jsp:
<%# page language="java" contentType="text/html; charset=windows-1255"
pageEncoding="windows-1255"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1255">
<title>Test</title>
</head>
<body>
<h2>Date</h2>
<%= request.getParameter("now") %>
</body>
</html>
I am trying to just set up a very basic jsp file that takes in a query from a url and displays it. I have the following test.jsp file that I run on the server:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Test jsp</title>
</head>
<body>
<% String firstName = (String) request.getAttribute("firstName");
out.println("Hello :" + firstName);%>
</body>
</html>
However, when I type in the following URL, I still get a "null" result (even after refreshing): see Picture.
Note: my ultimate goal is to do have an event at some point that sends a POST request from a java file and display its result in the jsp page. If I understood well from my research, I would have to do it via a Servlet with a DispacherRequest forwarding method. But I first want to understand why the simple aforementioned code isnt working).
Thank you for your help !
You mention that you're trying to display a query parameter from the URL. A query or request parameter is not the same as a request attribute.
To get a query parameter, you would have to use the getParameter() method:
String firstName = request.getParameter("firstName")
This question already has an answer here:
How do I pass current item to Java method by clicking a hyperlink or button in JSP page?
(1 answer)
Closed 7 years ago.
I have a facultylist.jsp page which displays List<Faculty> as a request attribute parameter in forEach loop and I want every item in this loop to be a link to specified faculty facultyview.jsp. How can I achieve that ?
facultylist.jsp:
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Faculties</title>
</head>
<body>
<h1>Faculties list</h1>
<ul>
<c:forEach var="faculty" items="${faculties}">
<li>${faculty.name}</li>
</c:forEach>
</ul>
</body>
</html>
facultyview.jsp:
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Faculty</title>
</head>
<body>
<h1>${faculty.name}</h1>
<ul>
<li>Faculty name: <c:out value="${requestScope.name}"></c:out></li>
<li>Total seats: <c:out value="${requestScope.total_seats}"></c:out></li>
<li>Budget seats: <c:out value="${requestScope.budget_seats}"></c:out></li>
</ul>
apply for this faculty
</body>
</html>
I don't know if its may help, but I'm using following technologies: tomcat, jsp, servlets and log4j.In my project I have one FrontController, which is a servlet that interacts with Command pattern - each Command returns a path to resource and action type: forward or redirect.
You can solve your issue by adding a query params to the link, edit with respect to the comment. Note that you cannot access directly the JSP pages that reside under WEB-INF folder. Also, to encode properly the paramters, better construct url like
<c:url value="facultyview.jsp" var="url">
<c:param name="name" value="${faculty.name}"/>
<c:param name="total_seats" value="${faculty.total_seats}"/>
<c:param name="budget_seats" value="${faculty.budget_seats}"/>
</c:url>
<li>${faculty.name}</li>
and than than in your facultyview.jsp read from the query params
<li>Faculty name: ${param.name}</li>
<li>Total seats: ${param.total_seats}</li>
<li>Budget seats:${param.budget_seats}</li>
This direct JSP communication should solve your immediate issue, but a truly proper way would be to pass an id of a faculty to servlet, fetch the faculty instance, place in the model and pass to the view.
in other way is just take the selected value from the drop down with a name and forward it to front controller servlet ,there use if else conditions and depends on the value you could forward the request to corresponding jsp or servlet
<select name="value"> in jsp
String value=req.getParameter("value"); in servlet
if()
else if()
If you have a field in Faculty entity simply:
${faculty.name}
#Mark: faculty represents an entity from database, i'm not sure if I want to change it adding another field, or you mean some other way ?
Add a field does not means you must change database, you can have a Helper entity that inherits from Faculty and have more fields you can need,
public class FacultyFormHelper extends Faculty implements Serializable {
private String URL;
and in your view:
${facultyHelper.name}
But, If you don't want to modify your database, either create a helper class, you may add onclick event to the <a>
<a onclick="goToURL(${faculty.id})">
Then retrieve the data... i'm not sure how you get the urls... from a variable in the view, ajax call or wherever you have this URL...
Short version-display home page only if session is already created
Details
I have a login.html. It links to validation.jsp. It checks for password and then redirects to the following page.
But I want that this following page to be displayed only when the
validation is true. Otherwise if someone enters the link to the page
and finds that the page has not been logged into, it will prompt to
do it so.
It worked fine in the servlet. I created a new session in validation page
and set request.getSession(false) in the home page.
but this doesnt seem to work in jsp. If I set session=false in the page
directive, then I can not access session object at all. and if I
explicitly do what I have done in the page, it still doesn't work!!
<%# page language="java" import="java.io.*"
contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"
import="java.util.*;"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%
session=request.getSession(false);
if(session==null)
{
out.println("please login");
}
else
{
out.println("how did it run!!! ??");
out.println(application.getAttribute("one"));
out.println(session.isNew());
out.println(session.getId());
out.println("<form action='logout.jsp' method='post'>");
out.println("<input type='submit'>");
out.println("</form>");
}
%>
</body>
</html>
You don't use if(session==null) to determine if someone is logged in. Sessions are generally created automatically, and besides, you might want to use a session for something even before login. You check for a specific session attribute.
String userid = (String)session.getAttribute("userid");
if(userid!=null)
{
out.print("logged in as:" + userid);
}
Of course in the login code you have to set it:
session.setAttribute("userid", userid);
There is also no need to call request.getSession in JSP. In a servlet you would need to, but in JSP the session object is already populated with request.getSession for you.
Edit:
When you do the session=false directive then the session object isn't declared so you'll need not just to set it but actually declare it: HttpSession session = request.getSession(false); Then you will get session=null, but its dangerous to rely on this for security, as going to a page where you didn't set session=false will create the session, and your code will then think someone was validly logged in, when they were not. Even if you are certain that you put session=false everywhere, you might miss a spot, or more likely, the next developer after you will not understand you did it this way, and a security disaster is just waiting to happen.
Using session=false is intended for performance boost not security. E.g. you have a faq page that doesn't care about sessions, set session=false so people going to that link doesn't create sessions and waste memory.
A JSP creates a session by default. If you don't need session then use following
<%# page session="false" %>
I'm learning java and try to pass some variable from servlet to jsp page. Here is code from servlet page
#WebServlet("/Welcome")
public class WelcomeServlet extends HttpServlet
{
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
HttpSession session = request.getSession();
session.setAttribute("MyAttribute", "test value");
// response.sendRedirect("index.jsp");
RequestDispatcher dispatcher = request.getRequestDispatcher("index.jsp");
dispatcher.forward(request, response);
}
}
And simple jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>My Index page</title>
</head>
<body>
Index page
<br />
<%
Object sss = request.getAttribute("MyAttribute");
String a = "22";
%>
<%= request.getAttribute("MyAttribute"); %>
</body>
</html>
Whatever I do attribete at jsp is null.
What is wrong at this simple code?
you are getting if from request not session.
It should be
session.getAttribute("MyAttribute")
I suggest you to use JavaServer Pages Standard Tag Library or Expression Language instead of Scriplet that is more easy to use and less error prone.
${sessionScope.MyAttribute}
or
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<c:out value="${sessionScope.MyAttribute}" />
you can try ${MyAttribute}, ${sessionScope['MyAttribute']} as well.
Read more
Oracle Tutorial - Using JSTL
Oracle Tutorial - Expression Language
You set an attribute in a session. You have to retrieve it from a session:
Object sss = session.getAttribute("MyAttribute");
And since you are dispatching the request, you actually don't need a session. You can set the attribute in a request object in your servlet:
request.setAttribute("MyAttribute", "test value");
Then read it as you are already doing in you JSP.
You should avoid scriptlets because they are java code in HTML, they break MVC pattern, they are ugly, odd and deprecated.
Simply replace :
<%
Object sss = request.getAttribute("MyAttribute");
String a = "22";
%>
with simply using EL ${MyAttribute}
But if you want to stick with scriptlets, you should get the attribute from the proper scope which is session in your case.