I have an input form (index.jsp):
<form action="process-mobile-number.jsp" method="post">
<table>
<tr>
<td>Enter a mobile number:</td>
<td>
<input type="number" name="telco" maxlength="4" style="width: 20%" required title="Please enter your 4-digit prefix."/>
-
<input type="text" name="mobile" maxlength="7" style="width: 70%" required title="Please enter your 7-digit number."/>
</td>
</tr>
<tr><td><input type="submit" value="Submit" style="width: 50%"/></td></tr>
</table>
</form>
This is the servlet that keeps count on how many times the system has been used:
#WebServlet("/process-mobile-number.jsp")
...
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
...
// initialize counters
int smartCtr = 0;
int globeCtr = 0;
int sunCtr = 0;
...
switch(telcoProvider) {
case "SMART":
smartCtr++;
break;
case "GLOBE":
globeCtr++;
break;
case "SUN":
sunCtr++;
break;
}
...
// assemble counter bean
Counter counter = CounterAssembler.getInstance(smartCtr, globeCtr, sunCtr);
// create session
HttpSession session = request.getSession();
// bind objects to session
session.setAttribute("smartCtr", counter.getSmartCtr());
session.setAttribute("globeCtr", counter.getGlobeCtr());
session.setAttribute("sunCtr", counter.getSunCtr());
// redirect to results jsp
response.sendRedirect("mobile-number-result.jsp");
}
This is the output JSP:
<form action="index.jsp" method="post">
<table>
...
<tr><td style="font-weight: bold">Your number of successful attempts are:</td></tr>
<tr><td>SMART: <%=session.getAttribute("smartCtr") %></td></tr>
<tr><td>GLOBE: <%=session.getAttribute("globeCtr") %></td> </tr>
<tr><td>SUN: <%=session.getAttribute("sunCtr") %></td></tr>
<tr>
<td>
<input type="hidden" name="smartctr" value="<%=session.getAttribute("smartCtr") %>"/>
<input type="hidden" name="globectr" value="<%=session.getAttribute("globeCtr") %>"/>
<input type="hidden" name="sunctr" value="<%=session.getAttribute("sunCtr") %>"/>
<input type="submit" value="Go Back" style="width: 18%"/>
</td>
</tr>
</table>
</form>
QUESTION:
However, when I press "Go Back" to return to index.jsp and begin another transaction, the counters are always reset to 0.
How do I make them persist with the hidden form fields?
Thank you.
Because each time your dopost method is called, you're initializing variable with value 0. Instead simply you can check if the session attribute exist, else set the attribute.
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
HttpSession session = req.getSession(true);
// get counter variables
Integer smartCtr = session.getAttribute("smart") == null? 0: session.getAttribute("smart");
Integer globeCtr = session.getAttribute("globe") == null? 0: session.getAttribute("globe");
Integer sunCtr = session.getAttribute("sun") == null? 0: session.getAttribute("globe");
//your logic
....
//set incremented values back
session.setAttribute("smart", smartCtr);
.....
}
If you want to count number times the of system usage, I suggest you should use static variable.
private static int smartCtr = 0;
private static int globeCtr = 0;
private static int sunCtr = 0;
Related
I want to get parameters from my jsp to my servelet.
so i used input form and it works for the name and the last name but it doesn't work for my ID.
Here is the code of my JSP:
<tr>
<td><form method="post" action="ServBddInsa">
<input type="hidden" name="id" id="id" value="testId"/>
<c:out value="${ utilisateur.id }" />
</form>
</td>
<td><c:out value="${ utilisateur.prenom }" /></td>
<td><c:out value="${ utilisateur.nom }" /></td>
<td><form method="post" action="ServBddInsa">
<p>
<label for="prenom"> Prenom :</label> <input type="text"
id="prenom" name="prenom" />
<label for="nom"> Nom :</label> <input type="text" id="nom"
name="nom" />
</p>
<input type="submit" name="editer" value="editer" />
</form></td>
</tr>
</c:forEach>
and this of my servlet:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
BddInsa listU = new BddInsa();
request.setAttribute("utilisateur", listU.recupererList());
this.getServletContext().getRequestDispatcher("/WEB-INF/bddinsa.jsp").forward(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Utilisateur utilisateurs = new Utilisateur();
utilisateurs.setNom(request.getParameter("nom"));
utilisateurs.setPrenom(request.getParameter("prenom"));
utilisateurs.setId(request.getParameter("id"));
System.out.println(utilisateurs.getPrenom());
System.out.println(utilisateurs.getNom());
System.out.println(utilisateurs.getId());
BddInsa listU = new BddInsa();
listU.Editer(utilisateurs);
request.setAttribute("utilisateurs", listU.recupererList());
this.getServletContext().getRequestDispatcher("/WEB-INF/bddinsa.jsp").forward(request, response);
}
}
I get NULL when I try to see the value of id
Thank you for your help !
Please can you try to use only one open and one close form tag? I think you problem is because you have two <form method="post" action="ServBddInsa"> . So the submit button is on the second form. In this case the hidden field of the first form is not considered and it is not sent.
I am trying to delete the data by checking multiple checkboxes, but when I choose the checkboxes from the screen and hit the delete button then the only top row gets deleted. Means no matter which row I select it deletes the only first entry of the table. Please help me.
Delete.servlet
delPage = request.getParameter("delPage");
patientId = request.getParameter("pid");
if(delPage.equals("true")) {
int p = Integer.parseInt(patientId);
patientDao = new PatientDAO();
boolean b = patientDao.isPatientDeleted(p);
if (b) {
System.out.println("Patient Deleted Successfully .... !");
RequestDispatcher rd = request.getRequestDispatcher("/Pages/MasterPage.jsp");
rd.forward(request, response);
}else
System.out.println("Patient deleting failed ... ! ");
}
RequestDispatcher rd = request.getRequestDispatcher("/Pages/MasterPage.jsp");
rd.forward(request, response);
}
Masterpage.jsp
<script type="text/javascript">
function addNewPatient(){
debugger;
var addNewPat = "true";
document.form.method = "POST";
document.form.action = "addPatient?newPage="+addNewPat;
document.form.submit();
}
function deletePatient(){
debugger;
var pid = document.getElementById("del").value;
var delpatient = "true";
document.form.method = "POST";
document.form.action = "deletePatient?delPage="+ delpatient+"&pid="+pid;
document.form.submit();
}
</script>
<c:forEach var="user" items="${patients}">
<tr>
<td>
<input type="checkbox" id="del" value="<c:out value="${user.patientId}">
</c:out>" >
</td>
<td>
<input type="hidden" id="delpatient"><c:out value="${user.patientId}">
</c:out>
<td><c:out value="${user.patientName}" /></td>
<td><c:out value="${user.patientAddress}" /></td>
<td><c:out value="${user.patientPhone}" /></td>
</tr>
</c:forEach>
<div class="ui small button" onClick="deletePatient(<c:out value="${user.patientId}"></c:out>)">
<i class="trash ulternate icon"></i>
Delete
</div>
DeletePatientServlet.java
public class DeletePatientServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private PatientBean patient = null;
private PatientDAO patientDao = null;
String delPage = null ;
String patientId = null;
protected void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
int patientId = Integer.parseInt(request.getParameter("pid"));
PatientDAO patientDao = new PatientDAO();
patientDao.isPatientDeleted(patientId);
System.out.println("Patient Deleted Successfully .... !");
RequestDispatcher rd = request.getRequestDispatcher("/Pages/MasterPage.jsp");
rd.forward(request, response);
}
}
Okay so there are a bunch of mistakes in your code. I'll start with the jsp...
You are trying to pass parameters via the servlet url with a POST request
document.form.method = "POST";
document.form.action = "deletePatient?delPage="+ delpatient+"&pid="+pid;
You cannot pass data in the url with post requests. You need to change your servlet to a GET if you want to do this.
Also, in this line:
<div class="ui small button" onClick="deletePatient(<c:out value="${user.patientId}"></c:out>)">
you are passing a value to your deletePatient method. But your deletePatient method does not have an option to pass a value:
function deletePatient(){ // no value being passed here?
debugger;
var pid = document.getElementById("del").value;
var delpatient = "true";
document.form.method = "POST";
document.form.action = "deletePatient?delPage="+ delpatient+"&pid="+pid;
document.form.submit();
}
You can also just do:
${user.patientId}
instead of:
<c:out value="${user.patientId}"></c:out>
Another problem with your code is this, you cannot have multiple elements in your HTML with the same id. This is illegal HTML, and it's the reason why you are getting the same id each time:
<c:forEach var="user" items="${patients}">
<tr>
<td>
<input type="checkbox" id="del" value="<c:out value="${user.patientId}"> //no this is bad.
</c:out>" >
</td>
<td>
<input type="hidden" id="delpatient"><c:out value="${user.patientId}">
</c:out>
<td><c:out value="${user.patientName}" /></td>
<td><c:out value="${user.patientAddress}" /></td>
<td><c:out value="${user.patientPhone}" /></td>
</tr>
</c:forEach>
Your delete button is not even inside your loop, so it will not work:
<div class="ui small button" onClick="deletePatient(<c:out value="${user.patientId}"></c:out>)"> //this will pass the same id each time
<i class="trash ulternate icon"></i>
Delete
</div>
Try something like this instead (for delete only):
<script type="text/javascript">
function deletePatient(e){
var patientid = e.getAttribute("data-patientid");
deletePatientForm(patientid);
}
function deletePatientForm(pid) {
var form = document.createElement("form");
var input = document.createElement("input");
form.method = "POST";
form.action = "deletePatient";
input.value=pid;
input.name="pid";
form.appendChild(input);
document.body.appendChild(form);
form.submit();
}
</script>
<c:forEach var="user" items="${patients}">
<tr>
<th>id</th>
<th>name</th>
<th>address</th>
<th>phone</th>
<th></th>
<tr>
<tr>
<td>${user.patientId}</td>
<td>${user.patientName}</td>
<td>${user.patientAddress}</td>
<td>${user.patientPhone}</td>
<td>
<div class="ui small button" onClick="deletePatient(this)" data-patientid="${user.patientId}"><i class="trash ulternate icon"></i> Delete</div>
</td>
<tr>
</c:forEach>
Then in the post of your servlet:
int patientId = Integer.parseInt(request.getParameter("pid"));
PatientDAO patientDao = new PatientDAO();
patientDao.isPatientDeleted(patientId);
RequestDispatcher rd = request.getRequestDispatcher("/Pages/MasterPage.jsp");
rd.forward(request, response);
If you have any problems or questions let me know.
I want to get the values for the rows which is then sent to a Java servlet then read by another page and inserts those values into the text boxes for the user to edit and write it back into the text file.
So it gets read by ProductIO which reads the textfile.
Its then entered into a jsp table
<c:forEach var="product" items="${products}">
<tr>
<td ><c:out value='${product.code}'/></td>
<td ><c:out value='${product.description}'/></td>
<td >${product.priceCurrencyFormat}</td>
<td><form action="editproduct" method="post">
<input type="submit" value = "Edit">
</form>
</td>
<td><form action="deleteproduct" method="post">
<input type="submit" value = "Delete">
</form>
</td>
</tr>
</c:forEach>
The User Clicks either the delete or edit button which will then send action to either the deleteproduct servlet or the editproduct servlet(only asking about the edit for now)
The edit product servlet
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
HttpSession session = request.getSession();
String url = "/editproduct.jsp";
getServletContext()
.getRequestDispatcher(url)
.forward(request, response);
String action = request.getParameter("action");
if (action == null) {
action = "editproduct"; // default action
} else if (action.equals("editproduct")) {
String productCode = request.getParameter("productCode");
String descString = request.getParameter("description");
//HttpSession session = request.getSession();
Product product = (Product) session.getAttribute("cart");
if (product == null) {
product = new Product();
}
getServletContext()
.getRequestDispatcher(url)
.forward(request, response);
}
}
Which the three Values are put into three text boxes on the editProduct.jsp page(where im having a problem getting the values to insert into the text boxes for it to be written back to the text file with the new information)
<form action="Product" method="post" >
<input type="hidden" name="action" value="add">
<label>Code:</label>
<input type="text" name="code" value='<%=request.getAttribute("code")%>'
required><br>
<label >Description:</label>
<input type="text" name="desc" value='<%=request.getAttribute("description")%>'
required ><br>
<label >Price:</label>
<input type="text" name="price" value='<%=request.getAttribute("price")%>'
required ><br>
<label> </label>
<!--<input type="submit" value="Update Product" class="margin_left">-->
<!--<input type="submit" value="View Product" class="margin_left">-->
<button type="submit">Update</button><br>
I can share more code if needed.
You aren't calling request.setAttribute() with any of the attributes in your Servlet. I assume you meant to add something like
request.setAttribute("code", productCode);
request.setAttribute("description", descString);
request.setAttribute("price", product.getPrice());
Before forwarding the request.
I've got a jsp file with two text fields (signUp and post). Now, I want the post text and the signUp text to be called to a servlet. Normally its going with request.getParameter(), but now I want the post text going to the servlet with an AJAX function and the signup text with the normal way (that means the name of the input within the jsp file and then request.getParameter).
Is it possible to mix both parts within one servlet because i have this:
<form name="form1" method="POST" action="PostWallServlet" id="form1">
form1 is the ajax code. I don't know how this should work. Normally there stands
`<form action="PostWallServlet" method="POST" >
and everything is callable through the Servlet. But, for now I don't know how I can mix up both components.
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PostWall pw=new PostWall();
SimpleDateFormat df = new SimpleDateFormat("YYYY/MM/DD hh:mm:ss");
Calendar cal = Calendar.getInstance();
System.out.println("Current Date Time : " + df.format(cal.getTime()));
String message = "";
String sender = request.getParameter("sender");
String post = request.getParameter("message");
String a= df.format(cal.getTime()).toString();
pw.setSender(sender);
pw.setPost(post);
pw.setDate(a);
if (pwi.addPost(pw)) {
message = "Student Successfuly Added";
} else {
message = "Student Adding Failed";
}
//RequestDispatcher rd = request.getRequestDispatcher("post.jsp");
//rd.forward(request, response);
}
$(document).ready(function(){
$('#Add').click(function(){
sendData();
});
});
function sendData(){
var mge = $('#newText').val();
alert(mge);
$.ajax({
type: "POST",
url: "PostWallServlet",
data: { message : mge }
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
}
</script>
<form name="form1" method="GET" action="PostWallServlet" id="form1"></form>
<table border="0" width="100%">
<tr>
<td colspan="3"> ${message}</td>
</tr>
<tr>
<td>Sender</td>
<td>:</td>
<td><input type="text" name="sender" value="" size=20/></td>
</tr>
<tr>
<td>Post</td>
<td>:</td>
<td><input type="text" name="post" value="" size=500 id="newText"/ ></td>
</tr>
<tr>
<td></td>
<td></td>
<td><input type="submit" value="Add" name="Add" /></td>
</tr>
</table>
Any solutions?
Put your ending tag for form AFTER all your inputs:
<form name="form1" method="GET" action="PostWallServlet" id="form1">
...
<td><input type="text" name="sender" value="" size=20 /></td>
...
<td><input type="text" name="post" value="" size=500 id="newText" /></td>
...
<td><input type="submit" value="Add" name="Add" /></td>
...
</form>
Your inputs must be INSIDE the form, not after the form.
Also make sure to end your input tags with /> not / >. You have a space between / and > on one of them.
For the Ajax part you need to give your inputs ids as well as names:
<td><input type="text" name="sender" id="sender" value="" size=20 /></td>
And then in your Ajax function for data:
data: { sender: $('#sender').val(), post: $('#post').val() }
I'm doing a small JEE5 application similar to an online shop and I need to show the shop products, it can be seen more clearly in the code:
<c:forEach var="product" items="${productsBean.products}">
<div class ="product">
<table>
<td>
<c:out value="${product.id}"/>
</td>
<td>
<c:out value="${product.name}"/>
</td>
<td>
<c:out value="${product.price}"/>
</td>
<td>
<c:out value="${product.description}"/>
</td>
<td>
<form method="post" action="/servlets-war/AddToCart">
<input type="hidden" name="id" value="${product.id}"></input>
<input type="submit" value="add to cart"/>
</form>
</td>
</table>
</div>
</c:forEach>
The problem is that the hidden input value in the form returns null instead of the ${product.id} when the form is submitted.
The associated servlet code is the next:
protected void processRequest(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
ShoppingCart shoppingCart = (ShoppingCart)request.getSession()
.getAttribute("shoppingCart");
if(shoppingCart == null){
shoppingCart = new ShoppingCart();
}
ProductsBean store =(ProductsBean) request
.getSession().getAttribute("productsBean");
int id = Integer.parseInt((String)request.getAttribute("id"));
Product temp = store.getProduct(id);
shoppingCart.getProducts().add(temp);
request.getSession().setAttribute("shoppingCart", shoppingCart);
this.getServletContext().getRequestDispatcher("/shop.jsp")
.forward(request, response);
}
You are retrieving the id as a request attribute.
int id = Integer.parseInt((String)request.getAttribute("id"));
Form input is sent to the servlet as a request parameter. Change your code appropriately:
int id = Integer.parseInt((String)request.getParameter("id"));