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".
Related
I have problems with sending data to one of my tables.
Below you can see my methods: one that shows the template with form, and the second that shoud add this action.
#GetMapping("/addaction/{id}")
public String addAction(Model model, #PathVariable("id") int id ) {
Optional<PlantEntity> plantEntity = plantService.getPlantById(id);
if (plantEntity.isPresent()) {
model.addAttribute("plant", plantEntity.get());
}
return "addaction";
}
#PostMapping("/addaction/{id}")
public String addAction(#ModelAttribute ActionForm actionForm,
#PathVariable("id") int plantId) {
if(!userService.isLogin()) {
return "redirect:/";
}
actionService.addAction(actionForm, plantId);
return "redirect:/plant/"+plantId;
}
Here is my method in Service:
public void addAction (ActionForm actionForm, int plantId) {
PlantEntity plantEntity = new PlantEntity();
plantEntity.setId(plantId);
ActionEntity act = new ActionEntity();
act.setName(actionForm.getName());
act.setDescription(actionForm.getDescription());
act.setPlant(plantEntity);
act.setUser(userService.getUserData());
act.setMonth(actionForm.getMonth());
actionRepository.save(act);
}
and my template: addaction.html
<form method="post" action="'/addaction/'+${plant.getId()}"
th:object="${actionForm}">
<div class="form-group">
<label for="exampleInputEmail1">Name of activity</label> <input
type="text" th:field="*{name}" class="form-control"
id="exampleFormControlInput1" aria-describedby="emailHelp"
placeholder="Name your work">
</div>
<div class="form-group">
<label for="exampleFormControlTextarea1">What you gonna
do?</label>
<textarea class="form-control" th:field="*{description}"
id="exampleFormControlTextarea1" rows="4"></textarea>
</div>
<div class="input-group mb-3">
<div class="input-group-prepend">
<label class="input-group-text" for="inputGroupSelect01">Month of activity</label>
</div>
<select class="custom-select" th:field="*{month}"
id="inputGroupSelect01">
<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>
</div>
<button type="submit" class="btn btn-dark">Action!</button>
</form>
The main problem is: when I try to addAction the result is:
http://localhost:8080/addaction/'/addaction/'+$%7Bplant.getId()%7D
There is some kind of loop. What am I doing wrong? Thank you for your time!
You don't have to pass '. spring expression language will take without ' also.
Try removing like below.
action="/addaction/${plant.getId()}"
Refer thymeleaf-construct-url-with-variable
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.
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.
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.