i am working on java application where user's login and predict football matches , i create an admin jsp to get all teams name from stored table in database to set this week matches and set the final results later when the matches finish to compare them with users results and calculate points , top users etc ...
my admin.jsp where i choose matches team from jstl foreach loop and set the final result later to compare them with user prediction results.
<%#page import="pws.daoImp.UsersDaoImp"%>
<%#page import="java.lang.String"%>
<%#page import="java.util.List"%>
<%#page import="java.util.ArrayList"%>
<%#page import="pws.beans.Users"%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<% request.getAttribute("admminresult");
%>
<%
List<String> teams1 = new ArrayList();
UsersDaoImp udi = new UsersDaoImp();
List<String> admminresult = new ArrayList();
admminresult = udi.getadminresult();
request.setAttribute("admminresult", admminresult);
List<String> teams = new ArrayList();
teams = udi.getallteams();
request.setAttribute("teams", teams);
%>
<head>
<link rel="stylesheet" type="text/css" href="css/main.css" />
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Match Prediction</title>
</head>
<body>
<div>
<h1 class="title">Welcome to Match Prediction Site </h1>
<div id="logo" >
<img src="images/cl.png" alt="Smiley face" width="142" height="142">
</div>
</div>
<form action ="AdminUserHandling" method = "post" >
<div class="form-lables">
<h1><select name="clteam1" >
<c:forEach items="${teams}" var="teams" >
<option name="clm1g1" value="${teams}">
${teams}
</option>
</c:forEach>
</select> Vs <select name="clteam1" >
<c:forEach items="${teams}" var="teams" >
<option name="clm1g1" value="${teams}">
${teams}
</option>
</c:forEach>
</select> </h1>
<label for="user_lic">Goals : </label><input id="user_lic" name="clm1g1" type="number" min="" max="10" step="1" value ="1"/>
<label for="user_lic">Goals : </label><input id="user_lic" name="clm1g2" type="number" min="" max="10" step="1" value ="1"/>
</div>
<input type ="submit" value="Submit" />
</form>
</body>
</html>
and my servlet code
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
UsersDaoImp udi = new UsersDaoImp();
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String team1 = request.getParameter("clteam1");
String team2 = request.getParameter("clteam2");
String team1gl = request.getParameter("clteam1gl");
String team2gl = request.getParameter("clteam2gl");
Users user = (Users) request.getSession().getAttribute("user");
System.out.println(team1);
System.out.println(team2);
udi.adminhandling(team1, team2,team1gl,team2gl); //save teams name and goals in database
processRequest(request, response);
}
}
my question is that i set the teams name and final result in admin page jsp but have problem to pass them to users jsp dynamically , iam running out of ideas to do so any help would be much appreciated.
You can use RequestDispatcher.
Defines an object that receives requests from the client and sends
them to any resource (such as a servlet, HTML file, or JSP file) on
the server. The servlet container creates the RequestDispatcher
object, which is used as a wrapper around a server resource located at
a particular path or given by a particular name.
RequestDispatcher rd = request.getRequestDispatcher("/path/to/your/users.jsp"); // mention correct path to your user.jsp here
request.setAttribute("teams",teams);
rd.forward(request, response);
Or
You can set the object into Session.
HttpSession session = request.getSession(false);
session.setAttribute("teams",teams);
Related
I can`t understand one thing when i send request to get object by name from db,
it always return me null. I surf all sites try to fix it with session and etc. Nothing to work.
Any ideas?
enter image description here
This is my Servlet class:
#WebServlet(value = "/display", name = "IndexServlet")
public class IndexServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
if(!(request.getParameter("mysql")==null)) {
MySQLRepository sql = new MySQLRepository();
Headline object = sql.getByHeadline(request.getParameter("mysql"), DatabaseConnection.initDatabase());
request.setAttribute("id", object.getId());
request.setAttribute("headline", object.getHeadline());
RequestDispatcher requestDispatcher = getServletContext().getRequestDispatcher("out.jsp");
requestDispatcher.forward(request,response);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
This is index.jsp:
<%# page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html>
<head>
<title>MySQLSolrProject</title>
</head>
<!DOCTYPE html>
<body>
<form action="out.jsp" method="get">
<p>Headline:</p>
<label>
<input type="text" name="mysql">
</label>
<%--<br>
<p>Full text:</p>
<label>
<input type="text" name="solr">
</label>--%>
<br><br>
<input type="submit" value="Search" formmethod="get">
</form>
</body>
</html>
This is out.jsp:
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Out</title>
</head>
<body>
<h2>Text is:</h2>
<table>
<tr><th>Id</th><th>Headline</th><th></th></tr>
<tr><td><%=session.getAttribute("id")%></td>
<td><%=session.getAttribute("headline")%></td>
</tr>
</table>
<p>Return to search</p>
</body>
</html>
the error was that Tomcat version 10.* didn't want to work with version 4 servlets
I downgraded Tomcat to version 9.* and it worked.
I'm passing an array of beans from servlet to jsp. I also want to send status "onHand" for each bean. I'm using arrayList for the status.
In Servlet:
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import pckg.ProductBean;
public class GetProducts extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException {
PrintWriter out = response.getWriter();
Vector<String[]> v = DBHelper.runQuery("SELECT * FROM SKU;");
ProductBean [] beans = new ProductBean[v.size()];
ArrayList<String> onHand=new ArrayList<String>();
//onHand.add("a");
for(int i=0; i < v.size(); i++) {
String [] tmp = v.elementAt(i);
Vector<String[]> on = DBHelper.runQuery("SELECT on_hand_quantity FROM on_hand where sku='"+tmp[0]+"' ;");
if((on.size())>0){
String [] tmp1 = on.elementAt(0);
if(Integer.parseInt(tmp1[0])>0){
onHand.add("InStock");}
else if(Integer.parseInt(tmp1[0])==0){
onHand.add("MoreOnTheWay");
}
}
beans[i] = new ProductBean(tmp[0],tmp[1],tmp[2],tmp[3],tmp[4],
tmp[5],tmp[8],Double.parseDouble(tmp[6]),Double.parseDouble(tmp[7]));
}
request.setAttribute("p_beans",beans);
request.setAttribute("onHand",onHand);
String toDo = "/WEB-INF/jsp/cameraList.jsp";
RequestDispatcher dispatcher = request.getServletContext().getRequestDispatcher(toDo);
dispatcher.forward(request, response);
}
}
In JSP page:
<%# page import = "java.util.*"%>
<%# page import="java.io.*" %>
<%# page import="java.net.*" %>
<%#page import="java.util.ArrayList" %>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html;
charset=iso-8859-1" />
<link rel="stylesheet" href="../css/cameraList.css" type="text/css"></link>
<script src="../script/jquery.js"></script>
<script src="../script/cameraList.js"></script>
</head>
<body>
<div id="main">
<% ArrayList<String> onHand=(ArrayList<String>) request.getAttribute("onHand");%>
<c:forEach items="${p_beans}" var="item">
<table >
<tr><td rowspan=5><img id="image" src="upload_dir/${item.image}" style="height:350px; width:350px; background-color:yellow";></td>
<td><b> ${item.vendor} ${item.model} ${item.category}</b></td></tr>
<tr><td width=45%> Price:$${item.retail}</td><td>Status:</td></tr>
<c:url value="/servlet/GetProductDetails?" var="myURL">
<c:param name="sku" value="${item.sku}" />
</c:url>
<tr><td><a href="${myURL}" >Get Details</a></td>
<c:url value="/servlet/OrderPage" var="cartURL">
<c:param name="itemID" value="${item.sku}" />
</c:url>
<td>Add To Cart</td></tr>
</table>
</c:forEach>
</div>
</body>
</html>
I get the following error in server:
An exception occurred processing JSP page /WEB-INF/jsp/cameraList.jsp at line 44:
41: <body>
42:
43: <div id="main">
44: <% ArrayList<String> onHand=(ArrayList<String>) request.getAttribute("onHand");%>
45: <c:forEach items="${p_beans}" var="item">
46:
47: <table >
request.getParameter() always return a String and it is basically use to get data from a form submitted by the user or to get the data from query string.
Because you are calling getParameter() , it will return String and therefore you are getting that exception.
As per your question, because you are setting value for onHand field as attribute in request, you should call getAttribute() method in JSP. Return type for getAttribute() is Object.
Cannot cast from String to ArrayList
It seems like your onHand object is of String type which you are setting your servlet/controller class (using request.setAttribute("onHand",onHand)), so you need to typecast to String rather than ArrayList<String> as shown below in your JSP:
<% String onHand= (String)request.getAttribute("onHand"); %>
Also, the important point is that you need to use request.getAttribute(key) to retrieve the objects inside JSP.
<%
String param = request.getAttribute("onHand");
%>
<c:forEach items="${p_beans}" var="item">
<tr>
<td>iterated fields</td>
<td>
..
..
<td><%=param%></td>
</tr>
I have a JSP page :
employee5_searchByName.jsp
<%#page import="java.util.Iterator"%>
<%#page import="java.util.List"%>
<!-- EMPLOYEE wants to search items by their name -->
<!DOCTYPE html>
<html>
<head>
<title>Employee - Search for items by name</title>
<link rel="stylesheet"
href="./css/styles.css"
type="text/css"/>
<link rel="stylesheet" type="text/css" href="css/jquery.autocomplete.css" />
<script src="http://www.google.com/jsapi"></script>
<script>
google.load("jquery", "1");
</script>
<script src="js/jquery.autocomplete.js"></script>
<style>
input
{
font-size: 120%;
}
</style>
</head>
<body>
<h1>Employee - Search for items by name</h1>
<h1>
Search for items by name
</h1>
<fieldset>
<legend>Please enter the item's name :</legend>
<form action="Employee5_After">
Item's name : <input type="text" name="prod_name" id="myProduct"><br>
<script>
$("#myProduct").autocomplete("autocompleteFromDb.jsp");
</script>
<input type="submit" value="Register">
</form>
</fieldset>
</body></html>
It forwards to this servlet :
Employee5_After
package controller.employee;
/**
* Retrieve the record of a given product by its name
* using hibernate
* #author X
*
*/
#WebServlet("/Employee5_After")
public class Employee5_After extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
// grab the product's name that the user entered
String productName = request.getParameter("prod_name");
// create DB instance
DatabaseInventory inventory = new DatabaseInventory();
// get the details
String details = inventory.getProductDetailsByName(productName);
HttpSession session = request.getSession();
// forward answer to JSP
synchronized(session)
{
if (details != null) // then the product has been found
{
session.setAttribute("foundProd", details);
String addressPath = "/WEB-INF/results/employee/employeeResult5.jsp";
RequestDispatcher dispatcher = request.getRequestDispatcher(addressPath);
dispatcher.forward(request, response);
}
}
}
}
That servlet is doing his stuff , and then forwards to a 2nd JSP ,called :
employeeResult5.jsp
<!-- Employee - get a description of a product by its name -->
<!DOCTYPE html>
<html>
<head><title>The details for the product you requested are below</title>
<link rel="stylesheet"
href="./css/styles.css"
type="text/css"/>
</head>
<body>
<h1>Here are the details from the product you request :</h1>
<h2>${foundProd}</h2>
<h1>We wish you well - bye bye!</h1>
<fieldset>
<legend>Go back to Employee's web-page</legend>
<form action="blablabla">
Press here to continue
</form>
</fieldset>
</body></html>
I guess that I can use the <% and %> in the JSP to do the logic side of the servlet (contacting to DB and retrieve data) . How can I avoid using a servlet in between , and just pass the data from one JSP to another JSP ?
You can use the request.redirect(URL) method to do it.
Or you can use request. forward(req, resp).
See example
Separate the business logic from the font end, there is no need to redirect to an intermediate servlet. The best practice is to put the business logic in a separate class and instantiate that class in the destination page. Here is one example:
mainPage.jsp - create the page similar to your employee5_searchByName.jsp. Now this page posts the data you enter.
Create a backing class called - dbData.java (DatabaseInventory in your case)- put all your database query here and functions to retrieve what your want. A function like public String searchText(String param) (similar to getProductDetailsByName(productName)) which will essentially fetch your search results from database.
Now the most important part - Instantiate this class in your destination SearchResults.jsp page and show whatever data you get in a manner similar to this:
<%#page import="mysource.dbData"%>
<%
searchParam = request.getParameter("searchStr");
dbData data = new dbData();
String result = data.searchText(searchParam);
%>
<HTML>
<BODY>
The result is: <% out.print(result); %>
</BODY>
</HTML>
The industry standard is to follow an MVC Architecture. Following that will create applications which are clear to understand and easy to maintain.
Try this code to forward with parameteres
<jsp:forward page="URL">
<jsp:param nama="param1" value="hello"/>
<jsp:param nama="param2" value="hello2"/>
<jsp:param nama="param3" value="hello3"/>
<jsp:param nama="param4" value="hello4"/>
.
........... and so on
</jsp:forward
I'm trying to make a list of members of type Party, and linking their memberID to an update page which automatically gets the memberID of the one which was clicked.
I've already written code in the servlet to display a view of all of the members, with each of their IDs linked to a page called UpdateParty.jsp however what I want is for the ID clicked to be passed on with the request so that it can be used in the UpdateParty.jsp as a parameter so that the user does not have to enter it.
I'm using postgres for my SQL if anyone wants to know.
Servlet code which produces a list of all party members:
else if (request.getParameter("listallmembers") != null) {
try {
User sessionuser = (User) session.getAttribute("User");
String u = sessionuser.getUsername();
ArrayList<Party> p = new ArrayList<Party>();
ResultSet rs = this.findAllMembers(u);
while (rs.next()) {
Party party = new Party();
party.setMemberID(rs.getString("memberID"));
party.setPartyFirstname(rs.getString("partyFirstname"));
party.setPartySurname(rs.getString("partySurname"));
party.setUsername(rs.getString("username"));
p.add(party);
}
request.setAttribute("members", p);
request.getRequestDispatcher("ViewPartyMembers.jsp").forward(request, response);
} catch (Exception e) {
out.print(e);
e.printStackTrace(out);
}
Code for ViewPartyMembers.jsp:
<%#page import="HolidayExchange.Party"%>
<%#page import="HolidayExchange.User"%>
<%#page import="java.util.List"%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>All Party Members</title>
</head>
<body>
<h1>View Party Members</h1>
<%
List<Party> l = (List<Party>) request.getAttribute("members");
if(l!=null){
out.println("<table>");
out.println("<tr><th>Member ID</th><th>Firstname</th><th>Second Name</th><th>Associated User</th></tr>");
for(int i = 0; i < l.size();i++){
out.println("<tr><td>"+ l.get(i).getMemberID() +
"</td><td><a href='UpdateParty.jsp'>"+ l.get(i).getPartyFirstname() +
"</a></td><td>"+ l.get(i).getPartySurname() +
"</td><td>" + l.get(i).getUsername() + "</td>");
out.println("</tr>");
}
out.println("</table>");
}else{
%>
<form action="PartyServlet" method="get">
<input type="hidden" name="listallmembers" value="1" /><br />
<input type="submit" value="Show all Members" />
</form>
<%
}
%>
</body>
</html>
Here's something a little more sane for you. It uses the JSTL Expression Language and tag library.
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>All Party Members</title>
</head>
<body>
<h1>View Party Members</h1>
<c:if test="${!empty members}">
<table>
<tr><th>Member ID</th><th>Firstname</th><th>Second Name</th><th>Associated User</th></tr>
<c:forEach items="${members}" var="member">
<tr><td>${member.memberID}</td>
<c:url value="link" value="UpdateParty.jsp">
<c:param name="memberId" value="${member.memberID}"/>
</c:url>
<td>${member.partyFirstname}</td>
<td>${member.partySurname}</td>
<td>${member.username}</td>
</tr>
</c:forEach>
</table>
</c:if>
<c:if test="${empty members}">
<form action="PartyServlet" method="get">
<input type="hidden" name="listallmembers" value="1" /><br />
<input type="submit" value="Show all Members" />
</form>
</c:if>
</body>
</html>
If you want the ID to be available on the UpdateParty.jsp your link should look like:
<a href='UpdateParty.jsp?id=" + l.get(i).getMemberID() + "'>"+ l.get(i).getPartyFirstname()"</a>
So the id property will be available in the JSP as a request parameter.
Anyway, I recommend you not use scriptlet in your JSP and instead point directly to a JSP point to a Controler/Action
I would like to determine which link is being click, and set a request attribute accordingly; to be processed in the controller. The controller is generic. It will dispatch to another page according to the attribute set in the JSP. How can I achieve this?
EDIT:
I have followed the BalusC's advice where
Register
Login
RandomController :
#WebServlet(name = "RandomController", urlPatterns = {"/RandomController/*"})
public class RandomController extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
int theRandom = 0;
Random myRandom = new Random();
RequestDispatcher dispatcher = null;
String pathInfo = request.getPathInfo();
String contextPath = request.getContextPath();
String dispatchesPath = contextPath + pathInfo;
System.out.println(pathInfo);
System.out.println(contextPath);
System.out.println(dispatchesPath);
theRandom = myRandom.nextInt(MAX_RANDOM);
request.setAttribute("random", theRandom);
if(pathInfo.equals("/Login")) {
dispatcher = request.getRequestDispatcher("Login.jsp");
dispatcher.forward(request, response);
}
else {
dispatcher = request.getRequestDispatcher("Register.jsp");
dispatcher.forward(request, response);
}
}
}
I have tried this approach but the Exception about maximum depth for nested request dispatchers : 20 is throw.
The generic controller is RandomController which servers two produces random number and set as attribute in request object and sent it to login or register page.
Login.jsp :
<%--
Document : Register
Created on : May 28, 2011, 5:49:35 PM
Author : nicholas_tse
--%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!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=UTF-8">
<title>Online Store Register Page</title>
<link rel="stylesheet" href="style.css" type="text/css" media="screen" />
</head>
<body>
<jsp:useBean id="randomBean" class="Helper.RandomInt"
scope="request">
</jsp:useBean>
<h1>Online Store</h1>
<p></p>
<div align="right">
<h3>
<c:if test="${not empty sessionScope.username}">
! Welcome ${sessionScope["username"]} !
<form action="LogoutController" method="POST">
<input type="submit" name="submit" value="Logout"/>
</form>
</c:if>
</h3>
</div>
<ul id="nav_list">
<li>Home</li>
<li>Product</li>
<li>Add Stock</li>
<li>Shopping Cart</li>
<li>Order Status</li>
<li>Register</li>
<li>Login</li>
</ul>
<br></br>
<p></p>
<c:if test="${!not empty sessionScope.username}">
<div id="registerForm" align="center"
style="border:1px solid black; width:760px" >
<form name="RegisterForm" action="RegisterController"
method="POST">
<p>
Username : <input type="text" id="username" name="username">
<c:if test="${message.msg} != null" >
${message.msg}
</c:if>
</p>
<p>
Password : <input type="password" id="password" name="password"
</p>
<p>
Name : <input type="text" id="name" name="name">
<c:if test="${message.msg} != null" >
${message.msg}
</c:if>
</p>
<p>
Address : <input type="text" id="address" name="address">
<c:if test="${message.msg} != null" >
${message.msg}
</c:if>
</p>
<p>
State :
<select>
<option>Selangor</option>
<option>Kuala Lumpur</option>
<option>Cyberjaya</option>
<option>Putrajaya</option>
</select>
</p>
<p></p>
<input type="submit" name="submit" value="Register">
<input type="reset" name="clear" value="Clear">
<p></p>
</form>
</div>
</c:if>
</body>
</html>
Without further info the only suggestion I can think of is to add a querystring to your URLs. Like this:
Page 1
This way you can look at the actiuon parameter in the request to determine what to do in your controller.
You can add a request parameter. This can be done in 2 ways depending on whether your form has a method of POST or GET.
You have implemented the submit buttons in the forms with a name attribute of submit and different value attributes. This should mean that the requests will include a submit parameter in the query string or the POST form data. On the server side, you can use this to figure out which of the submit buttons was clicked.