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.
Related
I have a dynamically generated table of data pulled from a database with individual buttons next to each entry for "update" and "delete". I am looking for a way to save table entry data when clicking the individual button next to the entry. With this data I want to pass it to another JSP to be used to auto populate field values.
User clicks button next to entry on table -> user taken to another form -> data from entry on original table is already populating values in new fields on new JSP to be updated and saved.
Ive been told this is possible without use of JavaScript however I am not against the idea of doing so.
JSP:
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="ISO-8859-1">
</head>
<body>
<h1>List of all films</h1>
<form action=insert method ="get">
<button>Insert Film</button>
</form>
<form action=delete method ="get">
<button>Delete Film</button>
</form>
<form action=update method ="get">
<button>Update Film</button>
</form>
<table>
<tr>
<th>Id</th>
<th>Title</th>
<th>Year</th>
<th>Director</th>
<th>Stars</th>
<th>Review</th>
</tr>
<c:forEach items="${films}" var="c">
<tr>
<td>${c.id}</td>
<td>${c.title}</td>
<td>${c.year}</td>
<td>${c.director}</td>
<td>${c.stars}</td>
<td>${c.review}</td>
<td><form action=update method="get"><button>Update Film</button></form>
<td><form action=delete method="get"><button>Delete Film</button></form>
</tr>
</c:forEach>
</table>
</body>
</html>
Update Servlet:
#WebServlet("/update")
public class update extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
RequestDispatcher rd = request.getRequestDispatcher("update.jsp");
rd.include(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
int id = Integer.parseInt(request.getParameter("id"));
String title = request.getParameter("title");
int year = Integer.parseInt(request.getParameter("year"));
String director = request.getParameter("director");
String stars = request.getParameter("stars");
String review = request.getParameter("review");
Film f = new Film (id,title,year,director,stars,review);
FilmDAO dao = new FilmDAO();
try {
dao.updateFilm(f);
}
catch (SQLException e) {
e.printStackTrace();
}
FilmDAO dao1 = new FilmDAO();
ArrayList<Film> allFilms = dao1.getAllFilms();
request.setAttribute("films", allFilms);
RequestDispatcher dispatcher = request.getRequestDispatcher("home.jsp");
dispatcher.include(request, response);
}
}
Update JSP:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert film into database</title>
</head>
<body>
<form action="updateFilms" method ="post">
<label>Insert ID of film to update: <input type="number" name="id"/></label><br/>
<label>Title: <input type="text" name="title"/></label><br/>
<label>Year: <input type="number" name="year"/></label><br/>
<label>Director: <input type="text" name="director"/></label><br/>
<label>Stars: <input type="text" name="stars"/></label><br/>
<label>review: <input type="text" name="review"/></label><br/>
<input type="submit" value="Update film"/>
</form>
</body>
</html>
So I'm using this Ace Editor: https://github.com/ajaxorg/ace-builds/, JSP and Java. I'm using this to send code from ace editor to Java:
editor.session.on('change', function(e) {
document.myform3.userCode.value = editor.getSession().getValue();
});
<form action="/myPage" method="post" name="myform3">
<input type="hidden" name="userCode" value="">
<button type="submit" class="btn btn-default">Submit</button>
</form>
And I'm returing it in Java:
public ModelAndView checkUserCode(String userCode) {
ModelAndView model = new ModelAndView("kurs");
model.addObject("testunio", userCode);
return model;
}
And I'm setting it with this code:
editor.getSession().setValue("${testunio}");
And it doesn't work. I don't see anything, even my editor disapear. I see just "Submit" button and nothing more. But when I display it normally in html:
<html><body>
${testunio}
</body></html>
It works. And also when I do for example in Java:
public ModelAndView checkUserCode(String userCode) {
ModelAndView model = new ModelAndView("kurs");
userCode = "test test test test test";
model.addObject("testunio", userCode);
return model;
}
editor.getSession().setValue("${testunio}"); works ok. Somebody have maybe any idea what I'm doing wrong?
#edit
Maybe it will be better if I will give more my code:
<div id="editor"></div>
<form action="/myPage" method="post" name="myform3">
<input type="hidden" name="userCode" value="">
<button type="submit" class="btn btn-default">Submit</button>
</form>
<script>
var editor = ace.edit("editor");
editor.setTheme("ace/theme/monokai");
editor.getSession().setMode("ace/mode/sh");
editor.getSession().setValue("${testunio}");
editor.session.on('change', function(e) {
document.myform3.userCode.value = editor.getSession().getValue();
});
</script>
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 am trying to add a message in my jsp after the process is done by hitting the submit button.
function onSubmit() {
alert("Master_Data.xlsx and Consistency_Check_Data.xlsx are located under d:/stage/MasterDataReports");
}
</script>
<body>
<form name="input" action="getMasterData" method="get">
<br />
<br />
<h1 align='center'>Master Data File</h1>
<br />
<br />
<table border="0" align='center'>
<tr>
<td>
<h2>Site Name</h2>
</td>
<td align='left'>
<jsp:useBean id="masterDao" class="master.dao.MasterDataDao"/>
<select name="siteId" id="siteId">
<option value="0">ALL</option>
<c:forEach items="${masterDao.allSites}" var="siteDto">
<option value="${siteDto.id}">${siteDto.name}</option>
</c:forEach>
</select></td>
</tr>
<tr>
<td>
<h2>Division</h2>
</td>
<td align='left'>
<jsp:useBean id="masterDaoUtil" class="master.dao.util.MasterDataConstants"/>
<select name="divisionId" id="divisionId">
<option value="33"><%=MasterDataConstants.DIVISION_TYPE_AUDIT_MANAGEMENT_GLOBAL_NAME%></option>
<option value="31"><%=MasterDataConstants.DIVISION_TYPE_CHANGE_MANAGEMENT_GLOBAL_NAME%></option>
<option value="34"><%=MasterDataConstants.DIVISION_TYPE_DEA_MANAGEMENT_GLOBAL_NAME%></option>
<option value="35"><%=MasterDataConstants.DIVISION_TYPE_EHS_MANAGEMENT_GLOBAL_NAME%></option>
<option value="23"><%=MasterDataConstants.DIVISION_TYPE_EVENT_MANAGEMENT_GLOBAL_NAME%></option>
</select></td>
</tr>
</table>
<br />
<br />
<div style="text-align: center">
**strong text**<input type="submit" value="Submit" OnClick="onSubmit()">
</div>
Right now the submit process will only happen after I clear the alert. Is there a way that I can either pop an alert after the submit process is done or if I can add a message to the jsp page?
Thanks in advance
Sonny
Here is my updated Servlet that is causing error:
package master.service;
import java.io.IOException;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
**strong text**import javax.servlet.http.HttpSession;
#SuppressWarnings("serial")
public class MasterDataServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response, HttpSession session)
throws IOException, ServletException {
MasterDataService masterDataService = new MasterDataService();
try {
int siteId = Integer.parseInt(request.getParameter("siteId"));
int divisionId = Integer.parseInt(request.getParameter("divisionId"));
//For master data file
masterDataService.createMasterDataFile(siteId, divisionId,false);
//For consistency checker file
masterDataService.createMasterDataFile(siteId, divisionId,true);
request.getRequestDispatcher("/masterDataQueryScreen.jsp").forward(request, response);
**strong text**session.setAttribute("getAlert", "Yes");//Just initialize a random variable.
**strong text**response.sendRedirect("/masterDataQueryScreen.jsp");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
So let's say after getMasterData servlet will response.sendRedirect to to test.jsp.
In test.jsp
Create a javascript
<script type="text/javascript">
function alertName(){
alert("Form has been submitted");
}
</script>
and than at the bottom
<script type="text/javascript"> window.onload = alertName; </script>
Note:im not sure how to type the code in stackoverflow!.
Edit: I just learned how to
Edit 2:
TO the question:This works perfectly. Another question. How would I get rid of the initial alert when I first start up the JSP? "Form has been submitted" is present the second I execute. It shows up after the load is done to which is perfect.
To do that i would highly recommendation to use session!
So what you want to do is in your servlet:
session.setAttribute("getAlert", "Yes");//Just initialize a random variable.
response.sendRedirect(test.jsp);
than in the test.jsp
<%
session.setMaxInactiveInterval(2);
%>
<script type="text/javascript">
var Msg ='<%=session.getAttribute("getAlert")%>';
if (Msg != "null") {
function alertName(){
alert("Form has been submitted");
}
}
</script>
and than at the bottom
<script type="text/javascript"> window.onload = alertName; </script>
So everytime you submit that form a session will be pass on! If session is not null the function will run!
in your servlet
request.setAttribute("submitDone","done");
return mapping.findForward("success");
In your jsp
<c:if test="${not empty submitDone}">
<script>alert("Form submitted");
</script></c:if>
You can also create a new jsp file sayng that form is submited and in your main action file just write its file name
Eg. Your form is submited is in a file succes.jsp
Then your action file will have
Request.sendRedirect("success.jsp")
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.