Button calling different servlet code in html form - servlets

I am bit new to Java web programming
I have two buttons(Test connection and Execute) in an html form and the form action is a servlet. How can I differentiate the action in the servlet based on which button is clicked.
Thanks

In the HTML:
<input type='submit' name='submitButton' value='Test connection' />
<input type='submit' name='submitButton' value='execute' />
In the servlet:
String clickedButtonValue = request.getParameter("submitButton");
if("Test connection".equals(clickedButtonValue))
{
...
}
else if("execute".equals(clickedButtonValue))
{
...
}
else ...
The reason this works: With both submit buttons sharing the same name attribute, the browser will only send the value of the one that was clicked.

Related

How to prevent double submission in magnolia form

I tried to add a handler to Submit button
<input type="submit" value="Submit/ Soumettre" onclick='submitform(); this.disabled = true;'>
function submitform()
{
let myForm = document.getElementById('MyForm');
myForm.submit();
}
but that kills all input field validators (in my case email field validator).
Magnolia should have something for such a common use-case.
Clarification: Model class attached to "Page after submit" perform time-consuming request to service. So the user doesn't see a new page and can click submit button several times.
Instead of attaching handler on submit button I put handler on form.onsubmit
<div id='shadow' style="display: none; position: absolute; width:100%;height:100%;opacity:0.3;z-index:100;background:#000"></div>
<form id="MyForm" method="post" action="" enctype="multipart/form-data" onsubmit="blockScreen()"> ... </form>
function blockScreen(){
let elem = document.getElementById('shadow');
elem.style.display = 'block';
elem.addEventListener('click', function(){}, false);
}
That shadow blocks the screen and activated only when all validators are completed

form submit redirect to a new url with AMP-HTML

I have a simple problem yet it seems impossible to solve in AMP!!
I have a simple form with an input and a submit button like this:
<form id="myform">
<input type="text" id="srchInput"/>
<button type="submit">Submit</button>
</form>
All I want is to be able to concat a static url to the input value and redirect the page to the result, when the form is submitted.
For instance if the user inputs: "Hello" and submits the form, I would like to redirect him to a page like "MY/STATIC/URL/Hello".
Is there any way to achieve this in amp?
One way of doing this is by setting the AMP-Redirect-To header in the response (See AMP-form-redirection). Send the user input on form submission, and then generate your desired url from your API endpoint and set AMP-Redirect-To header in your response to the generated URL.
Another way of doing it would be by using navigateTo(url=STRING) action (See AMP Actions & Events) on for the form submit event. In this case you have to store the value in input to a state by using events like input-throttled, and then use url substitution in the navigateTo url string to append amp-state value.
The first method is guaranteed to work.
The second method should work in theory, but I was unable to figure out how to get AMP-STATE value by url substitution. The code for the same should be something like:
<form id="myform" on="submit:AMP.navigateTo(url="MY/STATIC/URL/AMP_STATE(endValue)>")">
<input type="text" id="srchInput" on="input-throttled:AMP.setState({ endValue : event.value })" />
<button type="submit"> Submit </button>
</form>
If you can figure out how to substitute amp-state value to the url this should work. Let me know if it helped.
The easiest way to do this is via a GET action:
<head>
...
<script async custom-element="amp-form" src="https://cdn.ampproject.org/v0/amp-form-0.1.js"></script>
</head>
<body>
<form method="GET" action="MY/STATIC/URL" target="_top">
<input type="text" id="srchInput" name="srcInput" value="test">
<button type="submit">Submit</button>
</form>
</body>
The form submit will navigate to /MY/STATIC/URL?srcInput=test.

Form Submission on Enter Press

I have a form in my ASP .NET project that takes the users input, and appends it to a URL to search a wiki. The form works perfectly when you enter in a search term, and click the 'search' button, however when you type into the input box and hit enter, the page refreshes and the box clears.
my html
<form>
<label id="sideBarLabel"> Services
<input type="text" placeholder="Search Wiki: e.g. E911" name="queryString" id="query-string" />
</label>
Search Wiki
</form>
my js
function searchWiki(){
var siteQuery = $('#query-string').val();
window.location.href = "/dosearchsite.action?queryString=" + siteQuery;
}
Can anyone help ?
Your searchWiki() js method is only called when the evenement onclick is raised on your button, but not when your form is submitted.
There is several ways to achieve what you want:
Add a js method to catch the onsubmit event of your form:
$("form").on("submit", searchWiki());
Or add a tag on your form:
<form onsubmit="searchWiki()">
Or specify the action attribute on your form:
<form action="/dosearchsite.action">
Note that in ASP.NET, the ModelBinder will link your form inputs to your controller action parameters, using the name attribute of the inputs. That means that you should not specify them in the url yourself.
You should also declare your form using Html.BeginForm or Ajax.BeginForm if you want your form to be submitted by ajax.
#Html.BeginForm("ActionName", "ControllerName")
{
<label id="sideBarLabel">Services
<input type="text" placeholder="Search Wiki: e.g. E911" name="queryString" id="query-string" />
</label>
<input type="submit" class="button" value="Search Wiki"/>
}
This will call searchWiki when you press enter.
$('#query-string').keypress(function(event) {
if (event.keyCode == 13) {
searchWiki();
event.preventDefault();}});

Passing parameters to httpPost method in a controller in MVC

I have a controller with this method
[HttpPost]
public ActionResult AssociateCaseDetails(string btnSubmit, string navigate)
{
................................
................................
}
In the view i had an input like
<input type="submit" class="backdetails" value="BACK" name="btnSubmit" />
When i clicked on that button the btnSubmit value was BACK, so i thought of creating a similar input which will call that method
<input type="submit" class="submit" value="SAVE" name="btnChangeStatus" />
When i click this the AssociateCaseDetails is getting called but the btnSubmit is having null as value
What have i done wrong here?
Your post method has a parameter named btnSubmit, so the first submit button works because it has the attribute name="btnSubmit". The second does not work because it has name="btnChangeStatus". Change the second button to have the same name attribute (name="btnSubmit") so that it will be bound to your parameter.

ASP.Net MVC 4 Form with 2 submit buttons/actions

I have a form in ASP.Net and razor.
I need to have two ways of submitting said form: one that goes through the Edit action, and another that goes through the Validate action.
How should I go about doing this?
I don't mind using JavaScript for this.
EDIT:
Using the custom attribute I get this error.
The current request for action 'Resultados' on controller type 'InspecoesController' is ambiguous between the following action methods:
System.Web.Mvc.ActionResult Validar(System.Collections.Generic.ICollection1[Waveform.IEP.Intus.Server.Web.ViewModels.ResultadoViewModel]) on type Waveform.IEP.Intus.Server.Web.Controllers.InspecoesController
System.Web.Mvc.ActionResult Resultados(System.Collections.Generic.ICollection1[Waveform.IEP.Intus.Server.Web.ViewModels.ResultadoViewModel]) on type Waveform.IEP.Intus.Server.Web.Controllers.InspecoesController
That's what we have in our applications:
Attribute
public class HttpParamActionAttribute : ActionNameSelectorAttribute
{
public override bool IsValidName(ControllerContext controllerContext, string actionName, MethodInfo methodInfo)
{
if (actionName.Equals(methodInfo.Name, StringComparison.InvariantCultureIgnoreCase))
return true;
var request = controllerContext.RequestContext.HttpContext.Request;
return request[methodInfo.Name] != null;
}
}
Actions decorated with it:
[HttpParamAction]
public ActionResult Save(MyModel model)
{
// ...
}
[HttpParamAction]
public ActionResult Publish(MyModel model)
{
// ...
}
HTML/Razor
#using (#Html.BeginForm())
{
<!-- form content here -->
<input type="submit" name="Save" value="Save" />
<input type="submit" name="Publish" value="Publish" />
}
name attribute of submit button should match action/method name
This way you do not have to hard-code urls in javascript
You can do it with jquery, just put two methods to submit for to diffrent urls, for example with this form:
<form id="myForm">
<%-- form data inputs here ---%>
<button id="edit">Edit</button>
<button id="validate">Validate</button>
</form>
you can use this script (make sure it is located in the View, in order to use the Url.Action attribute):
<script type="text/javascript">
$("#edit").click(function() {
var form = $("form#myForm");
form.attr("action", "#Url.Action("Edit","MyController")");
form.submit();
});
$("#validate").click(function() {
var form = $("form#myForm");
form.attr("action", "#Url.Action("Validate","MyController")");
form.submit();
});
</script>
If you are working in asp.net with razor, and you want to control multiple submit button event.then this answer will guide you. Lets for example we have two button, one button will redirect us to "PageA.cshtml" and other will redirect us to "PageB.cshtml".
#{
if (IsPost)
{
if(Request["btn"].Equals("button_A"))
{
Response.Redirect("PageA.cshtml");
}
if(Request["btn"].Equals("button_B"))
{
Response.Redirect("PageB.cshtml");
}
}
}
<form method="post">
<input type="submit" value="button_A" name="btn"/>;
<input type="submit" value="button_B" name="btn"/>;
</form>
Here is a good eplanation:
ASP.NET MVC – Multiple buttons in the same form
In 2 words:
you may analize value of submitted button in yout action
or
make separate actions with your version of ActionMethodSelectorAttribute (which I personaly prefer and suggest).
With HTML5 you can use button[formaction]:
<form action="Edit">
<button type="submit">Submit</button> <!-- Will post to default action "Edit" -->
<button type="submit" formaction="Validate">Validate</button> <!-- Will override default action and post to "Validate -->
</form>
<input type="submit" value="Create" name="button"/>
<input type="submit" value="Reset" name="button" />
write the following code in Controler.
[HttpPost]
public ActionResult Login(string button)
{
switch (button)
{
case "Create":
return RedirectToAction("Deshboard", "Home");
break;
case "Reset":
return RedirectToAction("Login", "Home");
break;
}
return View();
}
We can have this in 2 ways,
Either have 2 form submissions within the same View and having 2 Action methods at the controller but you will need to have the required fields to be submitted with the form to be placed within
ex is given here with code Multiple forms in view asp.net mvc with multiple submit buttons
Or
Have 2 or multiple submit buttons say btnSubmit1 and btnSubmit2 and check on the Action method which button was clicked using the code
if (Request.Form["btnSubmit1"] != null)
{
//
}
if (Request.Form["btnSubmit2"] != null)
{
//
}

Resources