The servlet doesn't come back to the previous page - java

This is my web servlet. its first job is to retrieve from the db a list of countries and print out in a select form element. for this point everything works. When I click the submit button in the form, I call the servlet through the action="/submit". Let suppose that I don't insert any username then when I submit the form. the validateSignUpForm return `true. Instead to return to signup page, I am in submit page. I don't understand. When the validationErrorFlag is true I should come back to signup page instead to be in submit page again. Where is the error?
#WebServlet(name = "SignUpServlet", urlPatterns =
{
"/signup"
})
public class SignUpServlet extends HttpServlet
{
#EJB
private UtilBeanInterface utilBean;
/**
* Handles the HTTP <code>GET</code> method.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
request.setAttribute("CountriesList", utilBean.getContriesList());
request.getRequestDispatcher("/WEB-INF/view/signup.jsp").forward(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
String username = request.getParameter("username");
String password = request.getParameter("password");
String confirm_password = request.getParameter("confirm_password");
String email = request.getParameter("email");
String name = request.getParameter("name");
String surname = request.getParameter("surname");
String address = request.getParameter("address");
String city = request.getParameter("city");
String zipcode = request.getParameter("zip_code");
String country = request.getParameter("country");
String homenumber_code = request.getParameter("homenumber_code");
String homenumber = request.getParameter("homenumber");
String mobilenumber_code = request.getParameter("mobilenumber_code");
String mobilenumber = request.getParameter("mobilenumber");
boolean validationErrorFlag = false;
validationErrorFlag = utilBean.validateSignUpForm(username,
password,
confirm_password,
email,
name,
surname,
address,
city,
zipcode,
country,
homenumber_code,
homenumber,
mobilenumber_code,
mobilenumber,
request);
if(validationErrorFlag == true)
{
doGet(request, response);
}
}
/**
* Returns a short description of the servlet.
*
* #return a String containing servlet description
*/
#Override
public String getServletInfo()
{
return "Short description";
}
}
JSP PAGE
<article class="container_12">
<section id="signupform" class="grid_5">
<h4>Registrazione membri</h4>
<p>(*) Campi richiesti</p>
<h6>I tuoi dati d'accesso su VolaConNoi.it</h6>
<form action="submit" method="POST">
<div>
<label>Username* <span class="advice">(max 16 caratteri)</span></label>
<input type="text" name="username" autofocus>
<c:if test="${!empty usernameInvalid}">
<p class="errorSignUp">Errore: inserisci un username valido</p>
</c:if>
<c:if test="${!empty usernameAlreadyExist}">
<p class="errorSignUp">Errore: l'username è già in uso</p>
</c:if>
</div>
<div>
<label>Password*</label>
<input type="password" name="password">
</div>
<div>
<label>Conferma Password*</label>
<input type="password" name="confirm_password">
</div>
<div>
<label>E-mail*</label>
<input type="email" name="email">
</div>
<br/>
<h6>Dati Personali</h6>
<div>
<label>Nome*</label>
<input type="text" name="name">
</div>
<div>
<label>Cognome/i*</label>
<input type="text" name="surname">
</div>
<div>
<label>Indirizzo*</label>
<input type="text" name="address">
</div>
<div>
<label>Città*</label>
<input type="text" name="city">
</div>
<div>
<label>CAP*</label>
<input type="text" name="zip_code">
</div>
<div>
<label>Paese*</label>
<select name="country">
<c:forEach items="${CountriesList}" var="country">
<option value="${country.iso}">${country.nicename}</option>
</c:forEach>
</select>
</div>
<div>
<label>Fisso</label>
<select name="homenumber_code">
<c:forEach items="${CountriesList}" var="country">
<option value="${country.phonecode}">${country.nicename} (+${country.phonecode})</option>
</c:forEach>
<input type="text" name="homenumber">
</select>
</div>
<div>
<label>Mobile*</label>
<select name="mobilenumber_code">
<c:forEach items="${CountriesList}" var="country">
<option value="${country.phonecode}">${country.nicename} (+${country.phonecode})</option>
</c:forEach>
</select>
<input type="text" name="mobilenumber">
</div>
<div>
<input type="submit" value="Registrati"/>
</div>
</form>
<div id="signupfooter"></div>
</section>
</article>

Compare:
#WebServlet(name = "MainControllerServlet",
loadOnStartup = 1,
urlPatterns = {"/signup",
"/submit"})
with:
String url = "/WEB-INF/view" + userPath + ".jsp";
Even if userPath = "/signup"; you'll never get to the signup servlet, because you appeneded that ".jsp" in there.
Also, if you ever did get to /signup it looks like it would be an infinite loop forwarding to itself over and over.
BTW, it would probably be a lot simpler to actually make separate servlets for each different operation than to double up on them and do this kind of string manipulation.

Related

convert parameter from multiselect checkbox of jsp page

<input type="checkbox" name="premium" value="HBO">HBO <br>
<input type="checkbox" name="premium" value="FOXP">FOX Película <br>
<input type="checkbox" name="premium" value="FOX">FOX + <br><br>
<input type="submit" value="cotizar" name="Cotizar" />
<br><br>
I'm trying to bring from an index.jsp the premium parameter of a checkbox, in a servlet of a client of a web service. I have to save it as a list but what I have tried has not worked
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String plan = request.getParameter("plan");
String PREMIUM = request.getParameter("premium");
How do I convert request.getParameter ("premium") into a list?
Try this:
String[] premiums = request.getParameterValues("premium");
You need to put all the checkbox inside of form then only multiple values will be sent to server.
HTML:
<form method="post">
<input type="checkbox" name="premium" value="HBO">HBO <br>
<input type="checkbox" name="premium" value="FOXP">FOX Película <br>
<input type="checkbox" name="premium" value="FOX">FOX + <br><br>
<input type="submit" value="cotizar" name="Cotizar" />
</form>
Servlet:
To get multiple values we need to use getParameterValues(), if you any value for the given parameter name it will give string array of values. If we have one value it will given string array with length of 1.
String[] premiums = request.getParameterValues("premium");
If no value sent to server then above method will return null value.

Java Servlet not receiving values from JSP Form

This is my first time setting up a Java Servlet, I am trying to retrieve values into my Java Servlet from my input fields in my JSP Form when the user clicks a specific button. I also, am unsure if I used the proper practice for creating my Servlet. I simply right-clicked on my Apache Tomcat 8.0 server and then selected new Servlet.
Java Servlet:
#WebServlet("/loginServlet")
public class loginServlet extends HttpServlet {
private static final long serialVersionUID = 3719628899527775749L;
public loginServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.getWriter().append("Served at: ").append(request.getContextPath());
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String username = request.getParameter("username");
String password = request.getParameter("password");
// do some processing here...
// get response writer
PrintWriter writer = response.getWriter();
// build HTML code
String htmlRespone = "<html>";
htmlRespone += "<h2>Your username is: " + username + "<br/>";
htmlRespone += "Your password is: " + password + "</h2>";
htmlRespone += "</html>";
// return response
writer.println(htmlRespone);
}
}
JSP:
<form name="loginForm" action="loginServlet" method="post" id="loginForm">
<div class="imgcontainer">
<img src="images/img_avatar2.png" alt="Avatar" class="avatar">
</div>
<div class="container">
<label><b>Username</b></label>
<input type="text" placeholder="Enter Username" name="uname" required>
<label><b>Password</b></label>
<input type="password" placeholder="Enter Password" name="psw" required>
<button id="loginButton" name="loginButton" type="submit">Login</button>
<button id="registerButton" name="registerButton" type="button">Register</button>
<input type="checkbox" checked="checked"> Remember me
</div>
<div class="container" style="background-color:#f1f1f1">
<button type="button" class="cancelbtn">Cancel</button>
<span class="psw">Forgot password?</span>
</div>
</form>
Your request attribute's name are uname and psw which are added on Jsp page. So you must change your doPost method like this.
String username = request.getParameter("uname");
String password = request.getParameter("psw");
Or
You must change your form in jsp page like this:
<label><b>Username</b></label>
<input type="text" placeholder="Enter Username" name="username" required>
<label><b>Password</b></label>
<input type="password" placeholder="Enter Password" name="password" required>

Reading table html rows values to a servlet to another jsp page for editing

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.

JSTL foreach hidden input submits a null value

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"));

Reload jsp and lose request.getParameter("...") on servlet

I have 2 jsp-page. In first jsp-page I use combobox who choosing subject, several radio button for action. On servlet this page I get request.getParameter("subjectID").
Better If I show servlets and jsp
<form action="/TutorWebApp/controller" method="POST" name="editTestForm">
<p>
Choose subject
<select name='subject'>
<c:forEach items="${subjects}" var="subject" >
<option value="${subject.key}">
${subject.value.getName()}
</option>
</c:forEach>
</select>
</p>
<input type="radio" name="command" value="add_test">
Add test <br />
<input type="radio" name="command" value="add_subject">
Add subject <br />
<input type="submit" value="OK"/>
</form>
In this page I choose subject from combobox. And choose "Add test". After I go to servlet where
class AddTestCommand implements Command {
private static final String PARAM_TEST_NAME = "testName";
private static final String PARAM_SUBJECT = "subject";
#Override
public String execute(HttpServletRequest request) throws ServletException, IOException {
String page = " ";
String message = " ";
String testName = request.getParameter(PARAM_TEST_NAME);
if (testName != null && (!"".equals(testName))) {
HttpSession session = request.getSession(true);
Integer userID = (Integer) session.getAttribute("userID");
Integer subjectId =
Integer.valueOf(request.getParameter(PARAM_SUBJECT));
if(AddTestLogic.addTest(userID, subjectId, testName)){
message = "Success";
} else{
message = "This test already exist";
}
request.setAttribute("result", message);
}
page = ResourceBuilder.getPropertyManager(PropertyEnum.JSP_PAGE).
getProperty("path.page.addtest");
return page;
}
}
There I can get value of subject as request.getParameter("subject"); near with testName before if(){} And next step - go to next jsp
<form action="/TutorWebApp/controller" method="POST" name="addTestForm">
<input type="hidden" name="command" value="add_test" />
Name of new test:
<input type="text" name="testName" value=""/>
<input type="submit" value="Add test"/>
</form>
An after input data in jsp I go to the same servlet again. But I lose value request.getParameter("subject").
I try to use HttpSession but on first page I send Map. And get with request just choosen subjectID from Map.
I don't know how resolve this problem.
Thanks
You can retain request parameters for the next request with a hidden field. Request parameters are available by the ${param} map in EL. So, this should do:
<input type="hidden" name="subject" value="${fn:escapeXml(param.subject)}" />
Note that I'm using JSTL fn:escapeXml() to escape HTML entities; this will prevent possible XSS attacks.

Categories