Print checked values in JSP page - java

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.

Related

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

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.

How to update value on click in servlets? [duplicate]

This question already has answers here:
How can I share a variable or object between two or more Servlets?
(6 answers)
Closed 2 years ago.
I just want with each button click to add price value. This is my jsp:
<body>
<h1>Welcome ${user.name}</h1>
<c:forEach var="artical" items="${articals}">
<ul>
<li>${artical.name} </li>
<li>${artical.price}</li>
<li>${priceSum}</li> // i want to show value here just to test it.
</ul>
<form action="addtocart" method="POST">
<input type="hidden" name="names" value="${artical.name}"/>
<input type="hidden" name="price" value="${artical.price}"/>
<button type="submit" name="button">Add to cart</button>
</form>
</c:forEach>
And this is my servlet:
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
HttpSession session = request.getSession(true);
String name = request.getParameter("names");
double price = Double.parseDouble(request.getParameter("price"));
double priceSum = 0;
priceSum += price;
session.setAttribute("names", name);
session.setAttribute("price", price);
session.setAttribute("priceSum", priceSum);
RequestDispatcher rd = request.getRequestDispatcher("home.jsp");
rd.forward(request, response);
}
Now when i put priceSum outside doPost method as an attribute, it works, but i heard it shouldn't be solved like that. So how can i solve this properly and why is bad to put variable outside methods in servlets? Thanks!
I solve problem like this:
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
HttpSession session = request.getSession(true);
String name = request.getParameter("names");
double price = Double.parseDouble(request.getParameter("price"));
Double priceSum = (Double) session.getAttribute("priceSum");
if (priceSum == null) {
priceSum = 0.0;
}
priceSum+=price;
session.setAttribute("names", name);
session.setAttribute("price", price);
session.setAttribute("priceSum", priceSum);
RequestDispatcher rd = request.getRequestDispatcher("home.jsp");
rd.forward(request, response);
}
Is this proper way to do it?

Form submit for two times with null values and given me 500 error [duplicate]

This question already has answers here:
How should I use servlets and Ajax?
(7 answers)
Closed 5 years ago.
I created a login form which as I wanted to practice ajax from JQUERY. Unfortunately this program is given me unexpected error.
ISSUE
Browser is given me 500 error : NullPointerException
So I printed username and password. Then I saw that for one button click username and password print for two times and for first time it is same values as I entered and second time username is Null password is similar to entered value.And other thing is although I commented out the Ajax part that second scenario is happening (null username and entered password printing)
JSP:
<form action="" style="border:1px solid #ccc" method="post">
<div class="container">
<h2>LogIn Form</h2>
<label><b>Email</b></label>
<input type="text" placeholder="Enter Email" name="email" id="uName" required>
<label><b>Password</b></label>
<input type="password" placeholder="Enter Password" name="psw" id="psw" required>
<div class="clearfix">
<button type="button" class="cancelbtn">Cancel</button>
<button type="submit" class="signupbtn" id="login">LogIn</button>
</div>
</div>
</form>
JQUERY
<script type="text/javascript">
$(document).ready(function() {
alert("qwqw");
$('#login').click(function(){
$.post('userRegistrationServlet',{
uName : $('#uName').val(),
psw : $('#psw').val()},
function(responseText) {
alert(uName);
alert("Login Successfully..!");
});
});
});
</script>
Servlet
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
//PrintWriter out = response.getWriter();
String userName = request.getParameter("uName");
System.out.println(userName+"uName");
String psw = request.getParameter("psw");
System.out.println(psw+"psw");
RequestDispatcher rd;
if(!userName.isEmpty()| userName != null){
rd = request.getRequestDispatcher("/Header.html");
rd.forward(request, response);
}else{
rd = request.getRequestDispatcher("/SignUp.jsp");
rd.forward(request, response);
}
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException{
request.getRequestDispatcher("UserRegistration.jsp").forward(request,response);
}
Please help me to solve this issue..Thank you..!
I'd rather put an event handler on the "submit" event of the form, then call preventDefault() and stopPropagation() on the event:
$("#myform").on("submit", function(e) {
e.preventDefault();
e.stopPropagation();
$.post('userRegistrationServlet',{
uName : $('#uName').val(),
psw : $('#psw').val()},
function(responseText) {
alert(uName);
alert("Login Successfully..!");
});
});
this button type is 'submit' so when you click it your form will be submit coherently but no url path
LogIn

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.

Categories