message after form validation - java

I have a JSP page which has several input fields and a servlet validates the fields when I click on the submit button and redirects to another page.
I would like to add a popup window: "all the fields are ok" after a correct server-side validation.
So I started with:
<form ="alert('success');">
<input type="submit" value="submit">
</form>
The problem is that "success" is printed even if the fields are incorrect.
I thought about setting a parameter in the
protected void doPost(HttpServletRequest request,HttpServletResponse response, which calls an execute() function to say if things are OK or not but I do not know how to get this parameter just after the submit so I could make a conditional:
if (checkSubmitParameter == OK )
callsPopup()

Try something like this (see jsfiddle):
<script>
function checkit(){
var val = document.getElementById('txt').value;
if(val == "good"){
alert("success");
}else{
alert("failure!");
}
}
</script>
<form onsubmit='checkit()'>
<input type='text' id="txt" />
<input type='submit' value='Submit' />
</form>

Related

How to map submit button of a JSP to a servlet to?

I am old to JAVA but very new to the topics of JSPs & Servlets. I am trying to do some jdbc operations by taking the values from JSP into servlet. To do that, I have written a JSP with a drop down list and a submit button.
Jsp:
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<body>
<div align='left' >
<div align='left' >
<label class="text-white mb-3 lead">Which report do you want to generate?</label>
<select id="reportSelection" data-style="bg-white rounded-pill px-5 py-3 shadow-sm " class="selectpicker w-100" name="reportselection">
<option>Outage</option>
<option>DataQuality</option>
<option>Latency</option>
</select>
</head>
<body>
<p id = "demo"> </p>
<script>
var d = new Date();
document.getElementById("demo").innerHTML = d;
</script>
</body>
</div>
</div>
</body>
<hr class="colorgraph">
<div class="row">
<div class="col-xs-12 col-md-6"><input type="submit" value="Submit" class="btn btn-primary btn-block btn-lg register" tabindex="7"></div>
</div>
</body>
</html>
And this is how my servlet class looks like.
#WebServlet("/getdata.do")
public class DataServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
GetTableColumn gt = new GetTableColumn();
String issue = request.getParameter("reportSelection");
String message;
try {
if ("Latency".equals(issue)) {
message = gt.process("latency");
} else if ("DataQuality".equals(issue)) {
message = gt.process("DataQuality");
System.out.println("Data quality");
} else if ("Outage".equals(issue)) {
message = gt.process("Outage");
}
} catch (SQLException s) {
s.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
I am reading the JSP drop down values in my servlet class and passing a String to method process based on the value received. I looked online to configure the web.xml file as below.
http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<servlet>
<servlet-name>DataServlet</servlet-name>
<display-name>DataServlet</display-name>
<description>Begin servlet</description>
<servlet-class>com.servlets.DataServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>DataServlet</servlet-name>
<url-pattern>/parse</url-pattern>
</servlet-mapping>
I am trying to run the code on IntelliJ and here is how I have configured my tomcar server on IntelliJ.
When I run the code, I see the page is generating the jsp as expected.
What I don't understand is how to configure the submit with onclick so that I click on submit and the java program in the backed triggers. I have written the java code just to read values from a database by taking the input from the method process. This was running fine and I was asked to take the input from JSP and display the result back on a JSP.
When I click on submit button, I don't see any progress in the console output. I guess I didn't map it correctly.
Most of the links online contain JSP & JAVA together which is even more confusing.
Could anyone let me know how can I trigger the program by clicking the submit button
Since you are using #WebServlet, you do not need mapping in web.xml. Just add the following line inside body of your JSP:
<form action="getdata.do" method="post">
Look at your JSP file, pay attention at your head and body tag. I think it's a wrong that you have body inside other body and closing head tag inside body.
Other case that can be more important that to send a form by clicking to submit button you should put it inside tag form, something like this.
<form action = "getdata.do" method = "POST">
First Name: <input type = "text" name = "first_name">
<br />
Last Name: <input type = "text" name = "last_name" />
<input type = "submit" value = "Submit" />
</form>

`null` result from request in servlets

I am new in servlets-
I am filling text in form but value in request is null-
In login page-
<body>
<form action="">
<input type="text" name="uname">
<input type="text" name="pwd">
link
</form>
</body>
In DisplayPage-
<body>
Display:
<%
String uname=(String)request.getParameter("uname");
String upass=(String)request.getParameter("pwd");
out.println(uname+" - "+upass);
Enumeration<String> enumeration = request.getParameterNames();
boolean b=enumeration.hasMoreElements();
out.println(b);
while (enumeration.hasMoreElements()) {
String name = (String) enumeration.nextElement();
String data=(String)request.getParameter(name);
out.println(name+" - "+data);
}
%>
</body>
Now in my result value of uname and upass is null and hence boolean b is false.Weird!
My Question Is- If request object is created when we use anchor tag since there is no NPE on calling getParameter() on request object,so what kind of data attached with this request object.why this is provided to us?
Because you are not submitting your form to server or not passing any value in url, instead you are clicking on link, which will redirect it to your link.
<body>
<form action="display.jsp"> // added action
<input type="text" name="uname">
<input type="text" name="pwd">
<button type="submit">Link</button> // added submit button
</form>
</body>
For Updated Question
On server side every request is handled as HttpServletRequest object. So when we submit the form, every input field is submitted and then it is retrieved from the request object on server side.

javascript function call inside php function

I have a form which has 2 buttons: 'Submit' and 'Save'. Upon the submission of the form two kind of separate function run, depending on the button pressed. What I want to do is to call a function to check for empty fields when submit button is pressed.
Part of my code:
function valuecheck(){
var msg="";
if($F('entrepreneur_name')==""){
msg+="You need to fill the product name field!\n";
document.getElementById("entrepreneur_name").focus();
}
if($F('address')==""){
msg+="You need to fill in address!\n";
}
if (msg)
{alert(msg);
return false;
}
}
<?php
$chkbutton=$_POST['submit'];
switch ($chkbutton)
{
case "Submit":
// how to call the JavaScript function here..
...//rest of the code
?>
the form:
<input type="submit" style="width:10%" name="submit" value="Save" >
<input type="submit" style="width:10%" name="submit" value="Submit" >
how to call the javascript function inside the case "Submit":
Thanks in advance.
<input type="submit" style="width:10%" name="submit" value="Submit" onclick="Validate()" >
and
<script>
function Validate()
{
// your validation
}
</script>
You can do this on the form level prior submission:
<form name='myform' method='post' onSubmit="myFunction()">
And in your js function:
function myFunction()
{
if( !...)
return false; //don't submit the form
}
There are many ways to call JavaScript function from php function..
echo '<script type="text/javascript">'
, 'yourJSFunction();'
, '</script>';
Or you can do this way...
<?php
// some php stuff
?>
<script type="text/javascript">
yourJSFunction();
</script>
Hope it helps...
An alternative to sskoko's answer:
var submitButton = document.getElementById('submit-button');
submitButton.addEventListener('click', function(event) {
valuecheck();
}, false);
Though I have a sneaking suspicion that you will need to use event.preventDefault() to keep the form from submitting, when your values are invalid.
The method may have to be called either in the anonymous function passed to addEventListener(), or event may need to be passed into valuecheck() and then preventDefault() could be called down there. Play around with it and see.

Apache Wicket : Onclick of a form button, I need to call a small javascript function

Onclick of a form button, I need to call a small javascript function. This javascript function should validate some fields in the same form and then call the onSubmit() of the form which is in java.
Main Idea is that let validate happen in client side and not in java.
Complete idea :
I have help.html file as shown below :
<form wicket:id="form">
<input type="text" wicket:id="one"/>
<input type="text" wicket:id="two"/>
<input type="submit" wicket:id="save"/>
</form>
In help.java, I created a WebMarkupContainer and added this form with this submit button :
container.add(new Button("save") {
#Override
public void onSubmit() {
//saved
}
});
On click of the button in html, it calls onSubmit() and here we can do a validation on the text box values.
But I need to do all the validations in the HTML page itself.
OnClick of the Button Save, it should call a javascript funciton as shown below :
<form wicket:id="form">
<input type="text" wicket:id="one"/>
<input type="text" wicket:id="two"/>
<input type="submit" wicket:id="save" onclick="validateRange()"/>
</form>
JavaScript :
function validateRange(){
//logic
//Submit the form
}
Can this be done?
You need an AjaxSubmitLink or something like this. The you need to create a new IAjaxCallListener
public class MyAjaxCallListener implements IAjaxCallListener{
#Override
public CharSequence getBeforeHandler(Component component) {
return YOUR_JAVA_SCRIPT;
}
#Override
public CharSequence getBeforeSendHandler(Component component) {
return YOUR_JAVA_SCRIPT;
}
// ... not needed overrides can return null
}
Then in your AjaxSubmitLink you can add this AjaxCallListener
#Override
protected void updateAjaxAttributes(AjaxRequestAttributes attributes) {
super.updateAjaxAttributes(attributes);
attributes.getAjaxCallListeners().add(new MyAjaxCallListener());
}
Here you have an example Try if yourself
HTML:
<form id="form" action="#">
<input id="text" type="text"/>
<input type="button" onclick="validate()" value="TEST"/>
</form>
JS:
function validate() {
var value = document.getElementById("text").value;
if (value == "") {
alert("you have to write something");
return false;
}
else
document.getElementById("form").submit();
}

Multipart File submit never hit the server method

I have an ajax call:
what happens is that I click on an Image that clicks on "input file" that I don't want it to be shown. when the input val() is changed method uploadListener() is invoked which is basically an ajax method that get the file to the server "upload it to server"
code goes like this:
html:
<img id="${assayAssessRequest.id}" src="[#spring.url '/images/buttons/upload.jpg'/]" onclick="uploadFile(this);" title="Upload File" />
<form id="uploadForm" action="[#spring.url '/assay/designability/uploadFile.htm'/]" method="POST" enctype="multipart/form-data">
<div style="display: none;">
[#spring.formInput path="multiPartBean.file" fieldType="file" attributes="title='path' class='upload' accept='.txt,.csv,.zip'" /]
[#spring.formHiddenInput path="multiPartBean.fileName" attributes=" onchange='uploadListener();'class='uploadFileName'" /]
[#spring.bind "multiPartBean"/]
</div>
<input type="submit" id="uploadButton" value="upload" />
</form>
javaScript:
function uploadFile(){
document.getElementById('inputFile').click();
}
function uploadListener(){
$('#uploadForm').attr("action","[#spring.url '/assay/designability/uploadFile.htm'/]");
alert($('#uploadForm').attr('action'));
this.document.getElementById("uploadForm").submit = true;
alert("After Submit");
return false;
}
server controller:
#Controller
#PreAuthorize("isAuthenticated()")
#RequestMapping("/assay/designability")
#SessionAttributes({"assayAssessmentsInitializersBean","assayAssessmentsRequestsDetailsBean"})
public class AssayDesignabilityController extends AssayBaseController {
#RequestMapping(value = "/uploadFile",method= RequestMethod.GET)
public String uploadFile(#RequestParam(value = "file")Object file){
MultipartFile multipartFile=(MultipartFile)file;
logger.info(multipartFile.getName());
return multipartFile.getName();
}
}
now when I do all that, the response give me nonsense and when I try to debug I never get to the controller method. any help??
EDIT:
now I try to submit it I've updated code and I have the same behavior no response.
I've solved my problem by avoiding ajax call and re implement my code thanks to #Ian.
here is the code:
Html plus Freemarker
<form id="uploadForm" action="#" method="POST" enctype="multipart/form-data">
<div class="instruction popup_inst">
<span class="popup_logo">[#spring.message "pandaLogo"/]</span>
<div class="float_right">
<input type="button" id="cancelBtn" class="btn" onclick="refreshParentTable();closePopup();" value="[#spring.message "cancelButton"/]" />
<input class="btn" type="submit" id="submit" onclick="validateFileInput();" value="[#spring.message "uploadButton"/]" />
</div>
</div>
<span class="popup_title">[#spring.message "uploadFile"/]</span>
<div class="popup_container">
[#spring.bind "assayAssessmentsRequestBean"/]
[#spring.formInput path="assayAssessmentsRequestBean.designabilityFile.file" fieldType="file" attributes="title='path' class='upload' accept='.txt,.csv,.zip'" /]
[#spring.formHiddenInput path="assayAssessmentsRequestBean.designabilityFile.fileName" attributes="class='uploadFileName'" /]
[#spring.formHiddenInput path="assayAssessmentsRequestBean.dateOfAssessment" attributes="" /]
[#spring.formHiddenInput path="assayAssessmentsRequestBean.id" attributes="" /]
</div>
<input id="uploadfile" type="hidden" value="${uploadfile}"/>
</form>
controller:
#RequestMapping(value = "/uploadFile",method= RequestMethod.POST)
public ModelAndView uploadFile(#ModelAttribute(value = "assayAssessmentsRequestBean")AssayAssessmentsRequestBean assayAssessmentsRequestBean,HttpSession session) throws PanDaApplicationException {
//mycode
}
from this experience I would advice evreyone to avoid sending files via ajax calls for me
I used a popup window to create form and submit upload operation.
Thanks for everyone tried to help
If i see correctly, the submit action points to "uploadfile.HTM"
$('#uploadForm').attr("action","[#spring.url '/assay/designability/uploadFile.htm'/]");
but the method in your controller is mapped only to uploadFile (without .htm)
#RequestMapping(value = "/uploadFile",method= RequestMethod.GET)
Maybe you have another configuration on your web.xml / servlet-spring.xml that makes this possible, but otherwise, this could be the problem.
Hope this helps
Regards

Categories