I am using Spring controller, jsp as view with javascript and html as front end view. I have popup window, When I submit the button, it should redirect to controller class.
JavaScript code with html:
<%#taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("p").hide();
});
});
loginQB = function(){
var win = window.open('about:blank', 'popup', 'width=640,height=580,resizeable,scrollbars');
<!-- win.document.write('<%#taglib uri="http://www.springframework.org/tags/form" prefix="form"%>');
win.document.write('<form:form id="qblogin" method="POST" action="/asi/mappings">');--!>
win.document.write('<br>Sign in with Intuit Account or CreateOne');
win.document.write('<br><input type="text" name="userName">');
win.document.write('<br><input type="password" name="password">');
win.document.write('<br><input type="submit" value="Submit">');
<!--win.document.write('</form>');-->
}
</script>
</head>
<body>
<form:form id="qblogin" method="POST" onsubmit="loginQB(); return false;">
<select name="quickbooks" id="qb" >
<option value="qb-1">Books Desktop</option>
</select>
<input type="submit" value="Submit">
</form:form>
</body>
</html>
Spring controller class:
#Controller
#SessionAttributes("mappingSession")
public class MappingsController {
#RequestMapping(value="/mappings", method = RequestMethod.POST)
public String dataMappings(Model model) throws Exception {
DefaultHttpClient httpClient = new DefaultHttpClient();
First of all, why don't you use Bootstrap Modal for your pop up.
http://getbootstrap.com/javascript/#modals
Secondly, when you submit, you can get the information from your form, serialize it and then pass it to the controller.
http://api.jquery.com/serialize/
I strongly recommend you to change the implementation of your popup.
Related
I try to upload the content of a folder to the server. But I can't do it, so I made an example where you have to select every single file.
Controller:
#Controller
public class FileUploadController {
#RequestMapping(value = "/save", method = RequestMethod.POST)
public String save(#ModelAttribute("uploadForm") FileUploadForm uploadForm,Model map) {}
}
and the jsp-file
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%#taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<html>
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
<title> - Upload</title>
<script
src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script>
$(document).ready(function() {
//add more file components if Add is clicked
$('#addFile').click(function() {
var fileIndex = $('#fileTable tr').children().length;
$('#fileTable').append(
'<tr><td>'+
' <input type="file" name="files['+ fileIndex +']" />'+
'</td></tr>');
});
});
</script>
</head>
<body>
<div align="center" class="jumbotron">
<h1>dd</h1>
<form:form method="post" action="save.html"
modelAttribute="uploadForm" enctype="multipart/form-data">
<p>Dateien auswählen zum uploaden</p>
<input class="btn btn-success" id="addFile" type="button" value="Datei hinzufügen" />
<table align="center" class="table table-striped" id="fileTable">
<tr>
<td><input name="files[0]" type="file" /></td>
</tr>
<tr>
<td><input name="files[1]" type="file" /></td>
</tr>
</table>
<br/><input class="btn btn-primary" type="submit" value="Upload" />
</form:form>
</div>
</body>
</html>
That works great. I found some examples where I can select multiple files at once(just adding multiple), but couldnt upload them. I got some trouble to get this working. I'm surprised its so "difficult" to do a so "easy" thing. I dont know if I have to change my Controller file or only my jsp file. I hope someone can exaplain me how this works. I'm new so please talk to me like to a little stupid kid.
Greets
Sam
Single file input on form:
If you need just simply to select multiple files and upload them, you almost did it. You just have declare field in you form model as List:
public class FileUploadForm {
private List<MultipartFile> files;
public List<MultipartFile> getFiles() {
return files;
}
public void setFiles(List<MultipartFile> files) {
this.files = files;
}
}
Now in you controller you can access this list:
#Controller
public class FileUploadController {
#RequestMapping(value = "/save", method = RequestMethod.POST)
public String save(#ModelAttribute("uploadForm") FileUploadForm uploadForm, Model map) {
for(MultipartFile file : uploadForm.getFiles()){
try {
file.transferTo(new File(targetPath+file.getOriginalFilename()));
} catch (IOException e) {
throw new RuntimeException();
}
}
}
}
And of cause in your form you have to specify multiple attribute of file input:
<form:form method="post" action="/save" modelAttribute="uploadForm" enctype="multipart/form-data">
<input name="files" type="file" multiple=""/>
<button type="submit">Upload</button>
</form:form>
Note, that in this way you should not use array syntax, like file[], in input name.
Multiple file inputs on form.
Let's consider if you would like to load file, as it shown in your code snippets, when you add new file input for every file. First of all, remove field List<MultipartFile> files from model of form. We will get it by another way. Now the controller method will be as follows:
#RequestMapping(value = "/upload", method = RequestMethod.POST)
public String upload(#ModelAttribute("uploadForm")FileUploadModel uploadForm,
#RequestParam("files[]") List<MultipartFile> fileList, ModelMap model) throws IOException {
for(MultipartFile file : fileList){
try {
file.transferTo(new File(targetPath+file.getOriginalFilename()));
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
As you see, now we declared model of form and list of files separately. Also note, that list has #RequestParam with name of form's field. And this name specified with array syntax - files[].
Now, how form should look like:
<form:form method="post" action="/save" modelAttribute="uploadForm" enctype="multipart/form-data">
<input name="files[]" type="file" multiple=""/>
<input name="files[]" type="file" multiple=""/>
<input name="files[]" type="file" multiple=""/>
<button type="submit">Upload</button>
</form:form>
In this example I added multiple file inputs statically, but you can do it dynamically with javascript, indeed. Pay attention, that you should not specify index of array item in name of input. Just files[], but not files[0] or file[1].
By the way, you can receive list of files as parameter of method in case with single file input, as well. Just remove list of files from model and declare it as parameter of controller's method.
Trying to Use Captcha in my JSP page as below
<%# page import="net.tanesha.recaptcha.ReCaptcha" %>
<%# page import="net.tanesha.recaptcha.ReCaptchaFactory" %>
<html>
<head>
<title>Sample Application JSP Page</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript" language="javascript" src="ajax.js"></script>
</head>
<body bgcolor=white>
<form action="CaptchaServlet">
<table border="0" cellpadding="10">
<tr>
<td width="10" align="center" height="10">
<img src="SimpleServletPath">
</td>
<td>
<h1>Sample Application JSP Page</h1>
</td>
</tr>
<tr>
<td>
Please Enter your Comments
<p>
<%
ReCaptcha c = ReCaptchaFactory.newReCaptcha
("6LdlHOsSAAAAAM8ypy8W2KXvgMtY2dFsiQT3HVq- ", "6LdlHOsSAAAAACe2WYaGCjU2sc95EZqCI9wLcLXY", false);
out.print(c.createRecaptchaHtml(null, null));
%>
<INPUT TYPE="TEXT" NAME="text1">
<input type="submit" value="submit" />
</p>
</td>
</tr>
</table>
</form>
</body>
</html>
The servlet is as follows
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String remoteAddr = request.getRemoteAddr();
ReCaptchaImpl reCaptcha = new ReCaptchaImpl();
reCaptcha.setPrivateKey("6LdlHOsSAAAAACe2WYaGCjU2sc95EZqCI9wLcLXY");
String challenge = request.getParameter("recaptcha_challenge_field");
String uresponse = request.getParameter("recaptcha_response_field");
ReCaptchaResponse reCaptchaResponse = reCaptcha.checkAnswer(remoteAddr, challenge, uresponse);
PrintWriter out= response.getWriter();
if (reCaptchaResponse.isValid()) {
String user = request.getParameter("user");
out.write("CAPTCHA Validation Success! User "+user+" registered.");
} else {
out.write("CAPTCHA Validation Failed! Try Again.");
}
}
This works good, but the JSP page gets refreshed when submit value is clicked. How can we pass the Captcha values to Servlet using AJAX and return a value that the Capcha is valid or not without refreshing the page.
Here is the strategy.
Have your submit tracked by a javascript method. That method will send the captcha data to the server. and on sucesss or error the javascript will update the dom with the error message sent by the server/Servlet.
Follow this link https://gist.github.com/madan712/4972634.
In the link above it uses another jsp to validate ( working like a servlet) but you can give the url mapping name there in the url:[your_servlet_path]
I checked on duplicate threads but did not work. I just need to close browser after I click close. but it is firing Controller [HttpPost] method instead of close the browser.
browser is closing if open the same url from another window.
view
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
.....
....
<td align="right">
<input type="submit" name="btnSave" value="Save" id="btnSave" />
<input type="submit" name="btnCancel" value="Cancel" id="btnCancel" />
</td>
}
JS
<script type="text/javascript">
$(document).ready(function () {
......
$("#btnCancel").click(function (event) { window.close(); });
});
Controller
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Index(List<CustomerCommPreferences> lstcustCommPref, bool chkSolicitation)
{
}
Console warning show Scripts may not close windows that were not opened by script.
JavaScript can only close the windows it has opened. For example:
var yourWindow = window.open('http://google.com');
You could then use yourWindow.close();
The reason why you are hitting the controller is because you have two buttons which are inside a HTML form. When these buttons are clicked the form is submitted back to the server.
I have struts2 with dojo submit button(ajax call) in dialog window.I want to retain the popup window after submit the button.but its not retain the same form.
<div id="dialog-form">
<form action="finder" method="post" id="form1">
<textarea id="products" name="productNo"><s:property value='productNo'/>
</textarea>
<sx:submit targets="dialog-form"></sx:submit>
parent page form:
<div id="form_parent">
<form action="search" method="post">
-------------------------
--------------------------
</form>
</div>
searchaction.java
public String finder()
{
---------------------
return "search" //which is going to return parent page.
}
when i'm submitting the page , its closing the popup window and opening parent page. How to retain the popup window ?
I don't know struts2, but following the documentation at http://struts.apache.org/release/2.3.x/docs/dojo-submit.html, I would try something like :
<form id="form1" action="search">
---------
---------
<sx:submit beforeNotifyTopics="/before" />
</form>
<script type="text/javascript">
dojo.event.topic.subscribe("/before", function(event, widget){
dojo.stopEvent(event);
dojo.xhrPost({
form : dojo.byId("form1")
});
});
</script>
I have a form in a Registeration.jsp page:
form name="users" method="post" onSubmit="return checkCorrect()"
action="Registeration.jsp">
The Script checkCorrect is written at the start of the page, returns true or false based on information submitted to the form (using getElementById if it matters) and the script definitely works (worked on html page without jsp before)
after the form I have this:
<% if(request.getMethod().equals("POST")){...}
And I need that the jsp part will work ONLY if and after the form is successfully submitted, but somehow the javascript script is not called and don't work and the form is always submitted.
What am I doing wrong?
edits:
there's no redirection in my page, the javascript check function, the form, and the JSP part that procces the form after submitting it are at the same page.
the jsp part is used to send the data from the form to a database.
the function:
function checkCorrect(){
var fullname=document.getElementById("fullname").value;
...
if (response.length==0)
{
return true;
}
else
{
alert ("These problems are found in your form:\n\n"+response);
return false;
}
}
then come the body and the form and then
the jsp part:
<%
if(request.getMethod().equals("POST")){
String fullname=request.getParameter("fullname");
and go on.. } % >
Solution:
check the JavaScript part really good people it doesn't have compiler so even a tiny problem there can screw up the entire project.
<% uname=""+request.getAttribute("username"); %>
This variable will get a value only when you load your page or refresh it.
I guess your page flow is as follows.
You have your first page with form, and onsubmit form will call javascript function as
<form name="users" method="post" onSubmit="returncheckCorrect()" action="Registeration.jsp">
then your javascript will check your answer like :
<script type="text/javascript">
function returncheckCorrect() {
var x = document.getElementsByName("userName")
if (your condition) {
alert("Redirecting");
return true;
} else {
alert("Not Redirecting");
return false;
}
}
// return false; // lol, see why indentation is useful ?
</script>
then (if (your condition == true)) your java script will redirect to a second page where you want to get the value in a scriptlet like
<% uname=""+request.getAttribute("username"); %>
Make sure your code is in this manner.
Following is the code which I tried as you said, its working
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script type="text/javascript">
function chkme() {
var x = document.getElementById('textfield');
if (x.value == 'sarin') {
alert("success");
} else {
alert("failed");
}
return true;
}
</script>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form id="form1" name="form1" method="post" onsubmit="chkme();"
action="">
<input type="text" name="textfield" id="textfield" /> <input
type="text" name="textfield2" id="textfield2" /> <input
type="submit" name="button" id="button" value="Submit" />
</form>
<%
if (request.getMethod().equals("POST")) {
String textfield = request.getParameter("textfield");
String textfield2 = request.getParameter("textfield2");
%>
<%=textfield%>
<br />
<%=textfield2%>
<%
}
%>
</body>
</html>