How to create new object on each button click in Java ee? - java

I'm practising Java ee and I made a two input fields and button in jsp. When clicked on button "add" I want to add those two fields in a list and just show them on my jsp page. For now it's showing me only one result each time I click on button. What am I doing wrong?
This is my jsp:
<body>
<form action="addtocart" method="GET">
Title: <input type="text" name="title"> <br>
Price: <input type="text" name="price"> <br>
<button type="subtmit">Add</button>
</form>
<c:forEach var="bookList" items="${book}">
<ul>
<li>${bookList.name}</li>
<li>${bookList.price}</li>
</ul>
</c:forEach>
</body>
And this is my servlet:
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
HttpSession session = request.getSession(true);
String title = request.getParameter("title");
double price = Double.parseDouble(request.getParameter("price"));
ArrayList<Book> list = new ArrayList<>();
list.add(new Book(title,price));
session.setAttribute("book", list);
RequestDispatcher rd = request.getRequestDispatcher("home.jsp");
rd.forward(request, response);
}

Problem
You are creating a new ArrayList<Book> on every call of doGet and setting the same into the session. Thus, on every call of doGet the list is getting reset.
Solution
Get the existing list from the session and add a book to it. Create a new list only when it is not present in the session.
#WebServlet("/addtocart")
public class BooklistServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
HttpSession session = request.getSession(true);
String title = request.getParameter("title");
double price = Double.parseDouble(request.getParameter("price"));
ArrayList<Book> list = (ArrayList<Book>) session.getAttribute("book");
if (list == null) {
list = new ArrayList<Book>();
}
list.add(new Book(title, price));
session.setAttribute("book", list);
RequestDispatcher view = request.getRequestDispatcher("home.jsp");
view.forward(request, response);
}
}
Additionally, I recommend you display the list only when it is not empty as shown below:
<body>
<form action="addtocart" method="GET">
Title: <input type="text" name="title"> <br> Price: <input
type="text" name="price"> <br>
<button type="submit">Add</button>
</form>
<c:forEach var="bookList" items="${book}">
<c:if test="${not empty book}">
<ul>
<li>${bookList.title}</li>
<li>${bookList.price}</li>
</ul>
</c:if>
</c:forEach>
</body>
As you can see, I've added the check <c:if test="${not empty book}"> as a condition for the visibility of the list.

Every time the statement session.setAttribute("book", list); runs, it replaces the previous list in the session with the new one.
You should first try to fetch the existing list and then add your current book object to it.
ArrayList<Book> list =(ArrayList<Book>)session.getAttribute("book"); // get the current list from the session
list.add(new Book(...));
session.setAttribute("book", list); // store list in session
This should give you the output you are asking for.. Make sure you handle the NullPointerException that may be thrown when you add the element in the list.

Related

After login by creating a session data is not listed on the jsp page retrieved from the database

I have been trying to list out the data that is in a specific table in my database. The data is only retrieved when i just execute the particular servlet. It does not fetch that list when i have logged in and has created a session and is directed to that particulr jsp page. I only get an empty page.
I have tried getting the session attribute to that jsp page but it does not work
list-medicine.jsp
<body>
<%
if(session.getAttribute("email")==null)
{
response.sendRedirect("login.jsp");
}
%>
<div>
<div id="wrapper">
<div id="header">
Welcome ${email}
add medicine
</div>
</div>
<form action="UserLogoutControllerServlet">
<input type="submit" value="Logout">
</form>
<div id="container">
<div id="content">
<table>
<tr>
<th>Name</th>
<th>Amount</th>
<th>Price</th>
<th>Email of the user</th>
</tr>
<c:forEach var="tempStudent" items="${MEDICINE_LIST}">
<tr>
<td>${tempStudent.name}</td>
<td>${tempStudent.amount}</td>
<td>${tempStudent.price}</td>
<td>${tempStudent.email}</td>
</tr>
</c:forEach>
</table>
</div>
</div>
</div>
</body>
MedicineControllerServlet.java
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try
//list tje medicine...in MVC fashion
{
listMedicine(request,response);
}
catch(Exception e)
{
throw new ServletException(e);
}
}
private void listMedicine(HttpServletRequest request, HttpServletResponse response) throws Exception {
//get medicine from db util
List<Medicine> medicine=medicineDbUtil.getMedicine();
//add medicne from db util
request.setAttribute("MEDICINE_LIST", medicine);
//send to jsp view(view)
RequestDispatcher dispatcher=request.getRequestDispatcher("/list-medicine.jsp");
dispatcher.forward(request, response);
}
MedicineDbUtil.java
public List<Medicine> getMedicine() throws Exception
{
List<Medicine> medicine=new ArrayList<>();
Connection myConn=null;
Statement myStmt=null;
ResultSet myRs=null;
try
{
//get a connection
myConn = dataSource.getConnection();
//create sql statement
String sql="select name,amount,price,users_email from medicine ";
myStmt= myConn.createStatement();
//execute query
myRs=myStmt.executeQuery(sql);
//process result set
while(myRs.next())
{
//retrieve data from result set row
//int id=myRs.getInt("id");
String name=myRs.getString("name");
int amount=myRs.getInt("amount");
double price=myRs.getDouble("price");
String email=myRs.getString("users_email");
//create new medicine
Medicine theMedicine=new Medicine(name,amount,price,email);
//add it to list of medicine
medicine.add(theMedicine);
}
return medicine;
}finally
{
//close jdbc objects
close(myConn,myStmt,myRs);
}
}
I want the data list fetched from the database to be shown in the jsp page while i am logged in through a session

Print checked values in JSP page

I am trying to print checked values of checkbox list from a JSP page but nothing appears even if some selections are there.
<form action="process" method="POST">
<c:forEach var="item" items="${list.items}">
<input type="checkbox" name="chkSkills" value="${$item.Id}">${item.name}
</c:forEach>
<input type="submit" name="Getvalue" value="Get value" />
</form>
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
String[] Answers = request.getParameterValues("chkSkills");
PrintWriter out = response.getWriter();
String ButClicked = request.getParameter("Getvalue");
if (ButClicked != null) {
for (String Answer : Answers) {
out.print(Answer + "<br>");
}
}
//processRequest(request, response);
}
Correct your value attribute to
value="${item.Id}"
Notice, there's no need to put a $ inside the {} again.

Passing value from JSP scriptlet to servlet

I want to display table contents and edit the the specific row obtained based on unique id fetched by clicking submit button for respective row.
Below code is for listing all the records from table with edit button on every row:
<TABLE align="Center" border="1px" width="80%">
<%Iterator itr;%>
<%List data=(List) request.getAttribute("UserData");
for(itr=data.iterator();itr.hasNext();)
{%>
<tr>
<% String s= (String) itr.next(); %> <!-- Stores the value (uniquie id) in the String s -->
<td><%=s %></td>
<td><%=itr.next() %></td>
<td><%=itr.next() %></td>
<td><%=itr.next() %></td>
When I click the edit button I want to get the value from first column and first row which contains unique id.
The code fetching the value from String "s" is given below:
<form id="edit" action="EditRecord" method="post" onsubmit=<%=s %>>
<td><input type="submit" value="Edit" name="edit"> </td>
</form>
Now I want to pass this value stored in String s to my servlet "EditRecord" but somehow the value is not getting passed.
The code for servlet is given below:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Connection conn;
Statement stmt;
ResultSet res = null;
String id ;
String query;
DatabaseConnection dbconn;
// protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try{
id=request.getParameter("id");
System.out.println(id);
dbconn=new DatabaseConnection();
conn=dbconn.setConnection();
System.out.println(conn);
stmt=conn.createStatement();
System.out.println(stmt);
query="select * from user_details where User_id="+id;
res=dbconn.getResultSet(query, conn);
System.out.println(res);
}catch (Exception e)
{
}finally{
request.setAttribute("EditData",res );
RequestDispatcher rd=request.getRequestDispatcher("/editdata.jsp");
rd.forward(request, response);
out.close();
}
}
}
Could anyone tell me where I am making the mistake..Please guide me
Thanks in advance
The onSubmit event is invoked when the submit button is clicked, but it doesn't send any data to the server.
In your case I suggest you to add a hidden input to the form, so it will be sent to the server when submit button is clicked. Check the code below:
<form id="edit" action="EditRecord" method="post" >
<td><input type="hidden" id="id" value="<%=s %>"/>
<input type="submit" value="Edit" name="edit"> </td>
</form>

calling 2 forms from a jsp to a controller one after another

I have created two forms in my jsp. 1st one is an upload functionality and other is the submit page functionality. My requirement is to upload the file using upload functionality. and if upload is successful . The pass the file name back to jsp and on submit button pass the file name along with other details to other page.
My code:
MyJsp.jsp
</tr>
<tr>
<td colspan="2" rowspan="2" align="center"> <form action="UploadDownloadFileServlet" method="post"
enctype="multipart/form-data" class="CSSTableGenerator">
Select the Raw Data Sheet of Customer : <input type="file"
name="fileName" class="button"> <input type="submit" value="Upload"
class="button">
</form>
<form action="DataController" method="post" >
<input type="submit" name="listUser" value="Confirm Selection"
class="button" align="middle">
</form>
</td>
</tr>
</table>
My Controller (Servlet):
UploadDownloadFileServlet.java
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
if(!ServletFileUpload.isMultipartContent(request)){
throw new ServletException("Content type is not multipart/form-data");
}
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.write("<html><head></head><body>");
try {
List<FileItem> fileItemsList = uploader.parseRequest(request);
Iterator<FileItem> fileItemsIterator = fileItemsList.iterator();
while(fileItemsIterator.hasNext()){
FileItem fileItem = fileItemsIterator.next();
System.out.println("FieldName="+fileItem.getFieldName());
System.out.println("FileName="+fileItem.getName());
System.out.println("ContentType="+fileItem.getContentType());
System.out.println("Size in bytes="+fileItem.getSize());
String fileName = fileItem.getName().substring(fileItem.getName().lastIndexOf("\\") + 1);
System.out.println("FILE NAME>>>>"+fileName);
File file = new File(request.getServletContext().getAttribute("FILES_DIR")+File.separator+fileName);
System.out.println("Absolute Path at server="+file.getAbsolutePath());
fileItem.write(file);
HttpSession session = request.getSession();
session.setAttribute("Success", "Success");
getServletContext().getRequestDispatcher("/Welcome.jsp").forward(request, response);
/*out.write("File "+fileName+ " uploaded successfully.");
out.write("<br>");
out.write("Download "+fileName+"");*/
}
} catch (FileUploadException e) {
out.write("Exception in uploading file.");
HttpSession session = request.getSession();
session.setAttribute("Failed", "Failed");
getServletContext().getRequestDispatcher("/Welcome.jsp").forward(request, response);
} catch (Exception e) {
out.write("Exception in uploading file.");
HttpSession session = request.getSession();
session.setAttribute("Failed", "Failed");
getServletContext().getRequestDispatcher("/Welcome.jsp").forward(request, response);
}
out.write("</body></html>");/**/
}
}
My Next Contoller for submit button which needs value:
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String upload = (String)request.getAttribute("Success");
if(upload.equalsIgnoreCase("Success")){
System.out.println("SERVLET DOPOST");
String action = (String) request.getAttribute("DownLoadToExcel");
System.out.println(action);
String[] kpi = request.getParameterValues("kpi");
how is it possible in jsp to know that upload was successful and submit should go forward else give an error.
Awaiting reply.
Thanks,
MS
First, after UploadDownloadFileServlet successfully receives and process the upload, you should make it go back to the JSP. You need to "redirect it" to "MyJsp.jsp".
HttpServletResponse.sendRedirect("MyJsp.jsp?fileName2="+fileName);
//- you can also call sendRedirect from a PrintWriter -
Then, in the 2nd form in the JSP you could use something (javascript, scriptlets, a tag library, a custom tag, etc) to detect the parameter "fileName2" and set a hidden input with the name of the file.
Keep in mind you don't sendRedirect() and forward() for the same response.
You can pass as many parameters as you want together with the file name.

How to pass a session value as request parameter from JSP to servlet?

<c:forEach var="it" items="${sessionScope.projDetails}">
<tr>
<td>${it.pname}</td>
<td>${it.pID}</td>
<td>${it.fdate}</td>
<td>${it.tdate}</td>
<td> Related Documents</td>
<td>${it.pdesc}</td>
<form name="myForm" action="showProj">
<td><input id="button" type="submit" name="${it.pID}" value="View Team">
</td>
</form>
</c:forEach>
Referring to the above code, I am getting session object projDetails from some servlet, and displaying its contents in a JSP. Since arraylist projDetails have more than one records the field pID also assumes different value, and the display will be a table with many rows.
Now I want to call a servlet showProj when the user clicks on "View Team" (which will be in each row) based on the that row's "pID".
Could someone please let me know how to pass the particular pID which the user clicks on JSP to servlet?
Instead of an <input> for each different pID, you could use links to pass the pID as a query string to the servlet, something like:
View Team
In the showProj servlet code, you'll access the query string via the request object inside a doGet method, something like:
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
String pID = request.getParameter("pID");
//more code...
}
Here are some references for Java servlets:
HttpServletRequest object
Servlet tutorials
Pass the pID along in a hidden input field.
<td>
<form action="showProj">
<input type="hidden" name="pID" value="${it.pID}">
<input type="submit" value="View Team">
</form>
</td>
(please note that I rearranged the <form> with the <td> to make it valid HTML and I also removed the id from the button as it's invalid in HTML to have multiple elements with the same id)
This way you can get it in the servlet as follows:
String pID = request.getParameter("pID");
// ...
Define onclick function on the button and pass the parameter
<form name="myForm" action="showProj">
<input type='hidden' id='pId' name='pId'>
<td><input id="button" type="submit" name="${it.pID}" value="View Team" onclick="populatePid(this.name)">
</td>
.....
Define javascript function:
function populatePid(name) {
document.getElementById('pId') = name;
}
and in the servlet:
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
String pID = request.getParameter("pId");
.......
}

Categories