JSP pass parameter to servlet according to button clicked - forms

I have the following JSP which contains a form. The user should be able to update and delete, so I have two buttons for these options:
<form method="GET" action ="${pageContext.request.contextPath}/CurrencyController">
Currency code: <input type="text" name="currencyCode" id="currencyCode" value="${currency.currencyCode}" />
<br/>
<input type="submit" value="Update" >
<input type="submit" value="Delete"/>
</form>
In my servlet CurrencyController I retrieve the action:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String action = request.getParameter("action");
if (action.equalsIgnoreCase("update")){
...
if (action.equalsIgnoreCase("delete")){
...
So how can I pass the value for action in my form? It should be update if the first button is clicked and delete if the second button is clicked

Add action parameter using new input:
<input type="hidden" name="action" id="action" value="" />
Add onClick attribure to each submit button that will change its value. for example:
onClick="document.getElementId('action').value=this.value;return true;"

Related

Form not submitting with query parameters set with "asp-route" despite being in action

UPDATE: per this response this is behavior of HTML5? I tried setting the parameters in hidden inputs and that works. Doesn't make much sense to me, but what do I know.
I have my form for a "next page" button set up like this:
<form id="next" method="get"
asp-controller="Search"
asp-action="Cities"
asp-route-sortOrder="#ViewData["CurrentSort"]"
asp-route-currentFilter="#ViewData["CurrentFilter"]"
asp-route-pageNumber="#(Model.PageIndex + 1)">
<input form="next" type="submit" class="page-btn" disabled="#nextDisabled" value="Next" />
</form>
When I inspect the page, the form has the correct action url (example):
/Search/Cities?currentFilter=Test&pageNumber=2
But the request actually being made is to
/Search/Cities?
But when it hits the controller, all of the parameters are null. Here is the top of my controller:
[Route("Search/Cities")]
public ActionResult Cities(string SearchString, string sortOrder, string currentFilter, int? pageNumber)
I'm not sure what I'm missing here.
you have 3 choices. This code was tested
first the most popular, you have to use post
<form id="next" method="post"
asp-controller="home"
asp-action="test"
asp-route-sortOrder="CurrentSort"
asp-route-currentFilter="CurrentFilter"
asp-route-pageNumber="1">
<label for="searchString">Search</label>
<input type="text" id="searchString" name="searchString"><br><br>
<input form="next" type="submit" class="page-btn" value="Next" />
</form>
in this case searchingString will be sent in a request body, all another params in a query string
second
<a href="/Home/Test?sortOrder=CurrentSort&currentFilter=CurrentFilter&pageNumber=2">
<button class="page-btn">Next</button>
</a>
the second option will generate get request if it is so important for you, but you will not be able post search string except using ajax.
third, you can use get, but route params should be in the inputs, probably hidden, search string will have a visible input
<form id="next" method="get"
asp-controller="home"
asp-action="test">
<input type="hidden" id="sortOrder" name="sortOrder" value="CurrentSort" />
<input type="hidden" id="currentFilter" name="currentFilter" value="CurrentFilter" />
<input type="hidden" id="pageNumber" name="pageNumber" value="23" />
<label for="searchString">Search</label>
<input type="text" id="searchString" name="searchString"><br><br>
<input form="next" type="submit" class="page-btn" value="Next" />
</form>
in this case nothing will be inside of the body, everything in a query string including searchString.

One servlet One JSP 2 forms [duplicate]

This question already has answers here:
How to transfer data from JSP to servlet when submitting HTML form
(4 answers)
Closed 4 years ago.
One JSP, which contains two forms
<div class="modal" id="modalDialog">
<input method="post" action="newsPage">
<input type="hidden" name="modalForm" value="modalFormPush"/>
<input type= "text" name="title">
<textarea cols="45" maxlength="100" onkeyup="countf()" id="text" name="content"></textarea>
<input type="submit" value="Save" name="modalForm">
</form>
</div>
<div class="modal" id="newsModalDialog">
<form method="post" action="newsPage">
<input type="hidden" name="modalForm" value="modalFormNews"/>
<input type= "text" name="title">
<textarea cols="45" maxlength="100" onkeyup="countf2()" id="news_text" name="content"></textarea>
<input type="submit" value="Save" name="modalForm">
</form>
The goal is to send data from this forms to one servlet, which inserts its to database.
From one form data values must be inserted to one table-database, from second form - to second table-database, accordingly.
protected void doPost(final HttpServletRequest request, final HttpServletResponse response)
throws ServletException, IOException {
String modalForm = request.getParameter("modalForm");
if ("modalFormPush".equals(modalForm)) {
Pushdata pushdata = new Pushdata();
pushdata.setTitle(request.getParameter("title"));
pushdata.setContent(request.getParameter("content"));
pushModifier.savePushdata(pushdata);
}
else
if ("modalFormNews".equals(modalForm)) {
Newsdata newsdata = new Newsdata();
newsdata.setTitle_news(request.getParameter("title_news"));
newsdata.setContent_news(request.getParameter("content_news"));
newsModifier.saveNewsdata(newsdata);
}
}
But when I try to send data from one of this forms (for example "newsModalDialog"), joint table is created. This table contains fields from two tables. And this new table is empty.
Thus, values are not inserted to database, through servlet.
Thanks in advance!
I have found a mistake.
Not
<input method="post" action="newsPage">
But
<form method="post" action="newsPage">

JSP form pass parameter

In my jsp I am calling a servlet:
<form method="GET" action ="${pageContext.request.contextPath}/CurrencyController?action=listCurrency">
Currency code: <input type="text" name="currencyCode" id="currencyCode" />
<br />
<input type="submit" value="Search" />
</form>
But in my Servlet request.getParameter("action") is null. So how can I pass the action parameter?
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String action = request.getParameter("action");
if (action.equalsIgnoreCase("delete")){
String currencyCode = request.getParameter("currencyCode");
...
} else if (action.equalsIgnoreCase("edit")){
String currencyCode = request.getParameter("currencyCode");
...
} else if (action.equalsIgnoreCase("listCurrency")){
request.setAttribute("currencies", dao.getCurrencyByCode(request.getParameter("currencyCode")));
} else {
forward = INSERT_OR_EDIT;
}
RequestDispatcher view = request.getRequestDispatcher(forward);
view.forward(request, response);
}
You can define another hidden parameter like this
<input name="action" type="hidden"
value="${pageContext.request.contextPath}/CurrencyController?
action=listCurrency" />
and then in servlet use the same code request.getParameter("action") to get its value.

How to pass data from a form in a view to another controller with C# MVC?

If I have a form that needs to use a textbox input like as below:
#{
if(IsPost){
username = Request.Form["username"]
}
}
<form action="Home/Index" method="post">
<input type="text" name="username" />
<input type="submit" value="submit" />
</form>
The controller is something like below,
public class HomeController : Controller
{
public ActionResult Index (string username) {
if (string username != string.Empty)
{
Console.WriteLine("Your username is " + username);
}
return View();
}
}
Seems like the data is not being passed from the post method. When I hit submit the URL that it requests is Home/Home/Index, which is not were the controller(HomeController) action is located, it should be Home/Index, and use the HomeController right?
What if I need to pass this data to a different controller that has an Index for the action, like UserController?
In this instance, you're missing a slash!
<form action="/Home/Index" method="post">
<input type="text" name="username" />
<input type="submit" value="submit" />
</form>
But when using asp.net mvc, you should use Url.Content with the home directory character to ensure that if your site is deployed in a sub-directory of the site, the correct root will be found. So use:
<form action="#Url.Content("~/Home/Index")" method="post">
<input type="text" name="username" />
<input type="submit" value="submit" />
</form>

Url parameter to servlet doGet()

I'm working on my first web application. I am sending email with an url in it:
http://localhost:8080/HotelP/requeteSuccesO.jsp?hotelId=hampton&city=Montreal
When clicking on the link, requeteSuccesO.jsp displays the hotelId and city parameters:
out.println("<b>Hotel:</b> "+request.getParameter("hotelId")+"</br>");
out.println("<b>City:</b> "+request.getParameter("city")+"</br>");
Then the user can accept by clicking on a button:
<form method="get" action="acceptOffer">
<input type="submit" value="Accept" class="sanslabel">
acceptOffer is mapped to a servlet DecisionPage.java, and by clicking on that button it's calling the doGet() method.
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
System.out.println("in do get DecisionPage, hotelId is "+request.getParameter("hotelId"));
this.getServletContext().getRequestDispatcher( VUE_PAIEMENT ).forward( request, response );
}
The parameter hotelId received by the doGet function is null, but I am expecting it to be the value found in the url (in our case, "hampton")
Can anyone tell me why I get null and not "hampton" ?
When you make a form and submit that form to some action, it will only create request parameters for the fields you have defined in your form.
So, while you run the application with mentioned URL, it would contain those parameters and will be avilable to your jsp but if you don't include them in your form it won't be available to servlet when you submit the form.
So, you need to include those parameters to some hidden fields if you don't won't to show them to user.
Example:
<form method="get" action="acceptOffer">
<input type="hidden" name="hotelId" value="<%= request.getParameter(\"hotelId\")" %> /> <---- this field will create a new parameter with name as hotelId
<input type="hidden" name="city" value="<%= request.getParameter(\"city\") %>" />
<input type="submit" value="Accept" class="sanslabel">
</form>
So, now as we made a new fields hotelId and city they will be sent to your servlet acceptOffer and then you'll be able to access them with request parameter as below:
request.getParameter("hotelId")
You have to include those paramters in the form itself because the scope of the paramters is request scope. Something like this
<form method="get" action="acceptOffer">
<input type="text" name="hotelId" value=assign the value from request here/>
<input type="submit" value="Accept" class="sanslabel">
</form>