Am trying to retrieve the data submitted from the HTML from in a servlet.Am using netbeans and am trying to get the enumeration returned by getAttributes().
The html is
<html>
<body>
<center>
<form name="Form1" action="http://localhost:8080/DemoWeb/TwoParServlet">
<B>Color:</B>
<select name="color" size="1">
<option value="Red">Red</option>
<option value="Green">Green</option>
<option value="Blue">Blue</option>
</select>
<br>
<br>
<B>Country:</B>
<select name="country" size="1">
<option value="India">India</option>
<option value="Srilanka">Srilanka</option>
<option value="Chinae">China</option>
</select>
<br>
<br>
<input type=submit value="Submit">
</form>
</center>
</body>
</html>
The servlet is
public class TwoParServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String color = request.getParameter("color");
String country = request.getParameter("country");
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("<p>The selected color is: ");
pw.println(color);
pw.println("<p>The selected country is: ");
pw.println(country);
Enumeration names;
names = request.getAttributeNames();
pw.println("<p> First value received = " + names.nextElement());
//pw.println("<p> First value received = " + names.nextElement());
pw.close();
}
}
When I run the project am getting this error
Exception report message description The server encountered an internal error that prevented it from fulfilling this request.
exception
java.util.NoSuchElementException
java.util.HashMap$HashIterator.nextEntry(HashMap.java:929)
java.util.HashMap$KeyIterator.next(HashMap.java:960)
java.util.Collections$2.nextElement(Collections.java:3665)
p1.TwoParServlet.doGet(TwoParServlet.java:36)
javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:51)
What might have gone wrong?
You Just check the size of names, it will be zero.
so it means there is nothing returned from request.getAttributeNames().
use request.getParameterNames() instead of request.getAttributeNames().
You should use getParameterNames() instead of getAttributeNames.
Enumeration parameterNames = request.getParameterNames();
For more information to know difference between Attributes and Parameters see this question.
Related
listCurrencies thinks that it is a string in jsp code but request attribute has it as an ArrayList Type... the foreach therefore doesn't work. Help!
Servlet Method
protected void listCurrency(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
currencies = new Currencies();
ArrayList<String> c = (ArrayList<String>) currencies.getCurrencyList();
request.setAttribute("listCurrencies", c);
RequestDispatcher dispatcher = request.getRequestDispatcher("/BrokerIndex.jsp");
dispatcher.include(request, response);
}
JSP Code
<form action="brokerServlet" method = "Post">
<select name="currency">
<c:forEach items="${listCurrencies}" var="cur">
<option value="${cur}"
<c:if test="${cur eq selectedCurId}">Currency</c:if>
>
${cur} </option>
</c:forEach>
</select>
<input type="submit" value="Submit" />
I have a JSP that has a form that looks like this:
<form method="GET" action="ManagerLogicServlet?action=salesreport" >
<select name="monthList">
<option value="1">January</option>
<option value="2">February</option>
<option value="3">March</option>
<option value="4">April</option>
<option value="5">May</option>
<option value="6">June</option>
<option value="7">July</option>
<option value="8">August</option>
<option value="9">September</option>
<option value="10">October</option>
<option value="11">November</option>
<option value="12">December</option>
</select>
<input type="submit" value="Submit">
</form>
I am trying to send over a query string with attribute action = salesreport which will be a condition that will return a sales report for the selected month (don't mind the missing default value). I submit the form over to the ManagerLogicServlet which has this code snippet:
..String action = request.getParameter("action");
if (action.equalsIgnoreCase("salesreport")){
forward = SALES_REPORT;
int month = Integer.parseInt(request.getParameter("monthList"));
String monthString = new DateFormatSymbols().getMonths()[month-1];
request.setAttribute("monthString", monthString);
request.setAttribute("salesReport", salesDAO.getSalesReport(month));
} else if..
But the action attribute is set to null. Why is this?
Because your form is using the GET method, the parameters from the action attribute are being discarded. If you insist on using GET, then you can include an <input> tag containing the parameter you wish to pass on to the servlet. Try doing this:
<form method="GET" action="ManagerLogicServlet?action=salesreport" >
<input type="hidden" name="action" value="salesreport">
<select name="monthList">
<option value="1">January</option>
...
</select>
<input type="submit" value="Submit">
</form>
The alternative would be for you to leave your code as is, but change the form's method to POST.
Its working fine.
I tried this
HTML
<form action="AnyServlet?action=salesreport" method="post">
<input type="submit" value="Submit Data" />
</form>
AnyServlet.java
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String action = request.getParameter("action");
System.out.println("action=="+action);
}
Output
action==salesreport
UPDATE
When i changed from "post" to "get",I am getting issue too.You can use hidden input field if you want go with "get".
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.
I have 2 or more dropdown list in my JSP page...Now in my servlet I want to pass the two value of the selected items in two dropdown list and query this value to the database. I dont want to have this many method about the all possible combinations and have all of this combination a one class. Now how can I able to pass the two value of the selected items in the ddl?
here's my try
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
{
int SelectedOrg;
int SelectedSec;
String FilterByOrg = req.getParameter("OrgFilter");
String FilterBySec = req.getParameter("SectorFilter");
if (!"11".equals(FilterByOrg) && !"11".equals(FilterBySec))
{
SelectedOrg = Integer.parseInt(req.getParameter("OrgFilter"));
SelectedSec = Integer.parseInt(req.getParameter("SectorFilter"));
List<OrganizationItems> orgItems = new ViewAllOrganizations().findEMSOnly(SelectedOrg, SelectedSec);
req.setAttribute("orgItems", orgItems);
jsp.forward(req, resp);
}
else
{
List<OrganizationItems> orgItems = new ViewAllOrganizations().findAll();
req.setAttribute("orgItems", orgItems);
jsp.forward(req, resp);
}
}
Here's my JSP page
<form method="GET">
<div>
<span>Organization: </span> <select name="OrgFilter">
<option value="11">Organization Type</option>
<option value="22">All</option>
<option value="1">Emergency Medical Service</option>
<option value="3">Fire Suppression Group</option>
<option value="4">Medical Facilities</option>
</select>
</div>
<div>
<span>Sector: </span> <select name="SectorFilter" onchange="submit()">
<option value="11">Sector Type</option>
<option value="22">All</option>
<option value="1">NA</option>
<option value="2">Government</option>
<option value="3">Private</option>
<option value="4">Volunteer</option>
<option value="5">Corporate/Industrial</option>
</select>
</div>
</form>
After this I have my table below the form tag that displays the results
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.