How to upload,display,download and delete files using spring mvc - spring

Hi am trying to do operations like uploading a file,displaying a file,downloading a file and deleting a file using spring mvc i got success in uploading file and deleting file all operations working fine but then whats happening is when i do uploading the uploaded file or image displaying or downloading twice and getting
java.lang.IllegalStateException: getOutputStream() has already been called for this response
<form method="post" action="doUpload" enctype="multipart/form-data">
<table border="0">
<tr>
<td>Pick file #1:</td>
<td><input type="file" name="fileUpload" size="50" /></td>
</tr>
<tr>
<td>Pick file #2:</td>
<td><input type="file" name="fileUpload" size="50" /></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" value="Upload" /></td>
</tr>
</table>
</form>
<table border="1" bgcolor="black" width="600px">
<tr style="background-color: teal; color: white; text-align: center;"
height="40px">
<td>File Name</td>
<td>Image</td>
<td>Download</td>
<td>Delete</td>
</tr>
<c:forEach items="${employeeList}" var="user">
<tr style="background-color: white; color: black; text-align: center;"
height="30px">
<td><c:out value="${user.fileName}" /></td>
<td><img src="show?id=${user.id}" /></td>
<td>Download</td>
<td>Delete</td>
</tr>
</c:forEach>
</table>
#Controller
#RequestMapping("/")
public class RegistrationController {
#Autowired
private IRegistrationService registerService;
#RequestMapping(value = "/saveParentAndStudentFromAdmin", method = RequestMethod.POST)
public ModelAndView saveParentAndStudentByAdmin(
#ModelAttribute Student student,
#RequestParam CommonsMultipartFile[] fileUpload) {
if (fileUpload != null && fileUpload.length > 0) {
for (CommonsMultipartFile aFile : fileUpload) {
System.out.println("Saving file: "
+ aFile.getOriginalFilename());
student.setFileName(aFile.getOriginalFilename());
student.setFileType(aFile.getContentType());
student.setData(aFile.getBytes());
registerService.saveParentAndStudentByAdmin(student);
}
}
java.util.List<Student> uploadedFiles = registerService.findAllFiles();
return new ModelAndView("StudentEnrollmentFromAdmin", "employeeList",
uploadedFiles);
}
#RequestMapping("delete")
public ModelAndView deleteUser(#RequestParam int id) {
registerService.deleteRow(id);
java.util.List<Student> uploadedFiles = registerService.findAllFiles();
return new ModelAndView("StudentEnrollmentFromAdmin", "employeeList",
uploadedFiles);
}
#RequestMapping("show")
public ModelAndView displayImage(#RequestParam int id,
HttpServletResponse response, HttpServletRequest request) {
System.out.println("Id to display image: " + id);
Student item = registerService.get(id);
response.setContentType("image/jpeg, image/jpg, image/png, image/gif");
try {
response.getOutputStream().write(item.getData());
} catch (IOException e) {
e.printStackTrace();
}
try {
response.getOutputStream().close();
} catch (IOException e) {
e.printStackTrace();
}
return new ModelAndView("StudentEnrollmentFromAdmin");
}
#RequestMapping("downalod")
public ModelAndView downloadFile(#RequestParam int id,
HttpServletResponse response, HttpServletRequest request) {
System.out.println("Id to download: " + id);
Student student = registerService.get(id);
response.setContentType(student.getFileType());
response.setContentLength(student.getData().length);
response.setHeader("Content-Disposition", "attachment; filename=\""
+ student.getFileName() + "\"");
try {
FileCopyUtils.copy(student.getData(), response.getOutputStream());
} catch (IOException e) {
e.printStackTrace();
}
java.util.List<Student> uploadedFiles = registerService.findAllFiles();
return new ModelAndView("StudentEnrollmentFromAdmin", "employeeList",
uploadedFiles);
}
}

If I correctly understood your question you may do something like this:
public ResponseEntity<InputStreamResource> getFile(#PathVariable("idForm") String idForm)
{
try
{
Student item = registerService.get(id);
HttpHeaders respHeaders = new HttpHeaders();
//Change it with your real content type
MediaType mediaType = new MediaType("img","jpg");
respHeaders.setContentType(mediaType);
respHeaders.setContentLength(file.length());
//I suppose you have a method "getFileName"
//By using attachment you download the file; by using inline you should see the image in the browser
respHeaders.setContentDispositionFormData("attachment", item.getFileName());
InputStreamResource isr = new InputStreamResource(new ByteArrayOutputStream(item.getData()));
return new ResponseEntity<InputStreamResource>(isr, respHeaders, HttpStatus.OK);
}
catch (Exception e)
{
String message = "Error; "+e.getMessage();
logger.error(message, e);
return new ResponseEntity<InputStreamResource>(HttpStatus.INTERNAL_SERVER_ERROR);
}
}
Angelo

Related

BadRequest Error in ajax with Spring MVC

I am trying post a request to my controller and everytime when I hit submit button it gives an error of bad request.
I am not able to find out what is wrong with the code.
Home.jsp
<div id="setReminder">
<label class="generalReminder" style="text-decoration: none;">General
Reminder</label>
<table>
<tr>
<td>Date</td>
<td><input type="text" readonly="readonly"
id="birthdayDate"></td>
</tr>
<tr>
<td>Time</td>
<td><input type="text" readonly="readonly" id="callTime"
></td>
</tr>
<tr>
<td>Message</td>
<td><textarea id="reminderTag" rows="5"></textarea></td>
</tr>
</table>
</div>
<div id="reminderDot" style="margin-top: 24%; position: relative;">
<button class="submitReminder" onclick="saveReminderDetails();">Submit</button>
</div>
Home.js
function saveReminderDetails(){
var x="";
x=scheduleBirthdayReminder();
if(x){
$.ajax({
type:"POST",
url:"submitBirthdayRequest.do",
data : {
birthdayDate :$("#birthdayDate").val(),
birthdayTime : $("#callTime").val(),
birthdayReminder : $("#reminderTag").val()
},
success : function(data) {
alert('data is'+data);
$("#birthdayDate").val('');
$("#callTime").val('');
$("#reminderTag").val('');
}
});
}
}
Controller.java
#RequestMapping(value="submitBirthdayRequest.do",method=RequestMethod.POST)
public #ResponseBody String submitSchedulerDetails(#RequestParam("birthdayDate")String birthdayDate,#RequestParam("callTime")String birthdayTime,#RequestParam("reminderTag")String reminderTag,HttpServletRequest request ){
System.out.println("adding reminder details with birthdayDate "+birthdayDate+"and time"+birthdayTime);
String userIdentity=((UserDetails)request.getSession(false).getAttribute("loginDetails")).getName();
try{
boolean schedulerObj= schedulerService.addSchedulerBirthdayDetails(userIdentity,birthdayDate, birthdayTime,reminderTag);
}catch(Exception e){
e.printStackTrace();
}
return birthdayTime;
}
Error
http://localhost:8083/Testing/submitBirthdayRequest.do 400 (Bad Request)
the names of the parameters in the request don't match the expected. Try changing the
#RequestParam("birthdayTime") String birthdayTime
#RequestParam("birthdayReminder") String reminderTag
or change the param names on the client side

AJAX Call, it returns NOT Acceptable using SPRING MVC Hibernate

I'm using Spring MVC Hibernate, I'm retrieving districts and blocks from the database. District is successfully displayed but when it comes to Blocks i'm not able to display them, what can be the problem?? please help
$(document).ready(function()
{
$('#districtcode').change(function()
{
$.ajax({
type: "POST",
url: "./districtenrollment.htm",
data: "categoryCode="+ this.value,
success : function (data){
$('#blockcode').empty();
$('#blockcode').append($("<option>").val("-1").text("Select"));
for (var i = 0; i < data.length; i++) {
$('#blockcode').append($("<option>").val(data[i][1]).text(data[i][0]));
}
},
error: function(jqXHR, textStatus, errorThrown) {
alert("error:" + textStatus + " - exception:" + errorThrown);
}
});
});
});
<form:form method="POST" modelAttribute="disblo" autocomplete="off" >
<h3 id="heading"><u>Please Select</u></h3>
<table id="tab">
<tr>
<td>
User Id:
</td>
<td>
<form:input path="myid"/>
</td>
</tr>
<tr>
<td>
User name:
</td>
<td>
<form:input path="username"/>
</td>
</tr>
<tr>
<td>Select District</td>
<td>
<form:select path="mDistricts.districtcode" id="districtcode">
<form:option value="-1">Select </form:option>
<c:forEach var="c" items="${districtlist}">
<form:option value="${c.districtcode}" >${c.districtname}
</form:option>
</c:forEach>
</form:select>
</td>
</tr>
<tr>
<td>Select Block</td>
<td>
<form:select path="mBlocks.blockcode" id="blockcode">
<form:option value="-1">Select </form:option>
<c:forEach var="c" items="${blocklist}">
<form:option value="${c.blockcode}" >${c.blockname}
</form:option>
</c:forEach>
</form:select>
</td>
</tr>
</table>
</form:form>
`
This is my controller
#Autowired
private D_BDAO d_bdao;
#RequestMapping(value="Dist_Block.htm", method = RequestMethod.GET)
public ModelAndView getmodel(#ModelAttribute("disblo") usertestDisBlock db, HttpSession session) {
List<MDistricts> districtlist = d_bdao.getAllCategory();
org.springframework.web.servlet.ModelAndView model = new org.springframework.web.servlet.ModelAndView("Dist_Block");
model.addObject("districtlist", districtlist);
System.out.println("after model");
return model;
}
#RequestMapping(value = "/districtenrollment.htm", method = RequestMethod.POST)
public #ResponseBody
List<MBlocks> getmodel1(#RequestParam("categoryCode") Integer categoryCode) {
System.out.println("categoryCode="+categoryCode);
List<MBlocks> blocklist;
System.out.println("i'm here in ajax controller ");
blocklist = d_bdao.getAllBlocks(categoryCode);
System.out.println("i'm here after b_dao ");
System.out.println("c " + blocklist);
return blocklist;
}
This is my DAO Implementation
#Override
public List<MDistricts> getAllCategory() {
org.hibernate.Session session = sessionFactory.openSession();
session.beginTransaction();
String hql = "from MDistricts";
Query query = session.createQuery(hql);
List<MDistricts> districtlist = query.list();
session.close();
return districtlist;
}
#Override
public List<MBlocks> getAllBlocks(Integer districtcode) {
org.hibernate.Session session = sessionFactory.openSession();
session.beginTransaction();
SQLQuery q = session.createSQLQuery("select blockname, blockcode from test_schema.m_blocks where districtcode=:districtcode ORDER BY blockname");
q.setParameter("districtcode", districtcode);
List<MBlocks> blocklist = q.list();
session.close();
System.out.println("blocklist" + blocklist);
return blocklist;
}
I am not a telepath. But I can make an assumption (cause you don't provide enough information: stacktrace of the error, entity classes).
This code is incorrect
SQLQuery q = session.createSQLQuery("select blockname, blockcode from test_schema.m_blocks where districtcode=:districtcode ORDER BY blockname");
q.setParameter("districtcode", districtcode);
List<MBlocks> blocklist = q.list();
session.createSQLQuery() doesn't return List<MBlocks>, but List<Object[]>. Try this code with HQL:
Query q = session.createQuery(
"from MBlocks where districtcode = :districtcode order by blockname");
q.setParameter("districtcode", districtcode);
List<MBlocks> blocklist = q.list();
And try to log errors.

org.springframework.web.util.NestedServletException Netbeans

I am using Spring Framework to develop a web app.
The problem is when i tried to add an article in my database It shows a NestedServlet exception. Can any one help me ?
This is my controler class :
#Controller
public class Controler {
ArticleFacadeLocal articleModel;
CategorieFacadeLocal categorieModel;
ConnexionFacadeLocal connexionModel;
public Controler(){
articleModel = new ArticleModel();
categorieModel = new CategorieModel();
connexionModel = new ConnexionModel();
}
#RequestMapping("/home.do")
public String home(HttpServletRequest request){
if(isConnected(request))
return addPage(request);
else return "page:login";
}
#RequestMapping("login.do")
public String login(HttpServletRequest request){
String login=request.getParameter("login");
String password=request.getParameter("password");
if(ConnexionModel.connect(login, password)){
request.getSession().setAttribute("login",login);
ServletContext application=request.getServletContext();
application.setAttribute("categories", categorieModel.findAll());
return addPage(request);}
else
request.setAttribute("error",true);
return "forward:/home.do";
}
#RequestMapping("logout.do")
public String logout(HttpServletRequest request) {
request.getSession(false).invalidate();
return "forward:/home.do";
}
#RequestMapping("articles.do")
public String list(HttpServletRequest request){
request.setAttribute("articles",articleModel.findAll());
return "page:articles";
}
#RequestMapping("addPage.do")
public String addPage(HttpServletRequest request){
request.setAttribute("categories", categorieModel.findAll());
return "page:add";
}
#RequestMapping("add.do")
public String add(HttpServletRequest request){
try{
Article a=getArticleFromView(request);
articleModel.create(a);
request.setAttribute("error", false);
}catch(Exception e){request.setAttribute("error", true);}
return "forward:/addPage.do";
}
#RequestMapping("modifyPage.do")
public String modiyPage(HttpServletRequest request){
int idArticle=Integer.parseInt(request.getParameter("idArticle"));
request.setAttribute("categories", categorieModel.findAll());
Article article = articleModel.find(idArticle);
request.setAttribute("article", article);
return "page:modify";
}
#RequestMapping("modify.do")
public String modify(HttpServletRequest request){
try{
Article a=getArticleFromView(request);
articleModel.edit(a);
return "forward:/articles.do";
}catch(Exception e){
request.setAttribute("error", true);
return "forward:/modifyPage.do";
}
}
#RequestMapping("searchPage.do")
public String searchPage(HttpServletRequest request){
return "page:search";
}
#RequestMapping("search.do")
public String search(HttpServletRequest request){
String libelle=request.getParameter("libelle");
request.setAttribute("article",articleModel.find(libelle));
return "page:search";
}
public boolean isConnected(HttpServletRequest request){
HttpSession session = request.getSession(false);//recupere une session sans la creer
return (session!=null && session.getAttribute("login")!=null);
}
public Article getArticleFromView(HttpServletRequest request){
Article a = new Article();
String libelle = request.getParameter("libelle");
String description = request.getParameter("description");
String prix = request.getParameter("prix");
String qte = request.getParameter("qte");
String categorie = request.getParameter("categorie");
a.setLibelle(libelle);
a.setDescription(description);
a.setPrix(Double.parseDouble(prix));
a.setQte(Integer.parseInt(qte));
a.setCategorie(new Categorie(categorie));
return a;
}
}
And this is my jsp file
<%#include file="include.jsp" %>
<form action="add.do" method="post">
<table align="center">
<tr >
<td>Libelle :
<td><input type="text" required="required" name="libelle"/>
</tr>
<tr >
<td>Description :
<td><input type="text" required="required" name="description">
</tr>
<tr>
<td>Prix :
<td><input type="text" required="required" name="prix">
</tr>
<tr>
<td>Quantité :
<td><input type="text" required="required" name="qte">
</tr>
<tr >
<td> Catégorie :
<td>
<select name="categorie" >
<c:forEach items="${categories}" var="c">
<option value="${c.idCategorie}"> ${c.libelleCategorie} </option>
</c:forEach>
</select>
</tr>
<tr align="center" >
<td colspan="2"><button type="submit" id="btn">Ajouter</button></td>
</tr>
</table>
</form>
<c:if test="${not empty error && error}"> <p style="color: red;"> Echec d'ajout de l'article </p></c:if>
<c:if test="${not empty error && not error}"> <p style="color: green;">Article ajouté avec succes </p></c:if>
This is error exception :
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.hibernate.AssertionFailure: null id in model.beans.Article entry (don't flush the Session after an exception occurs)
cause première
org.hibernate.AssertionFailure: null id in model.beans.Article entry (don't flush the Session after an exception occurs)
I am not using Maven.

Passing image to JSP in Spring MVC java with mango

Hi I am reading image from MongoDB and trying to pass that to JSP page but it is not passing properly from my controller. i am thinking i am almost edge to the solution but not getting exactly where i am doing mistake. Please let me know if you find any mistake.
here insertMedia method reading image from file and storing into DB and then returning back that image.
i am passing userMediaSave as image value to JSP, you can get that at tag like
img src=${userMediaSave} alt="Profile images"
My Controller:
#RequestMapping(value = "/userMediaSave", method = RequestMethod.GET)
public ModelAndView mediaLoadSuccess(HttpServletRequest request,HttpServletResponse response,
#ModelAttribute("mediaBean") MediaBean mediaBean) throws IOException, ServletException {
ModelAndView model = null;
File filePart = mediaBean.getMediaImage();
if (filePart != null) {
InputStream inputStream = new FileInputStream(filePart);
GridFSDBFile imageForOutput = null;
try {
imageForOutput = loginDelegate.insertMedia(inputStream, request.getContentType(), filePart.getName());
mediaBean.setExistedMedia(imageForOutput);
OutputStream out= null;
if(imageForOutput!=null){
InputStream is = imageForOutput.getInputStream();
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
int nRead;
byte[] data = new byte[16384];
while ((nRead = is.read(data, 0, data.length)) != -1) {
buffer.write(data, 0, nRead);
}
byte[]imagenEnBytes = buffer.toByteArray();
buffer.flush();
response.setContentType("image/jpg" );
response.setContentLength(imagenEnBytes.length);
model = new ModelAndView("userMedia");
request.setAttribute("userMediaSave", imagenEnBytes);
return model;
} else {
System.out.println("inside uploadMedia page -ve");
}
} catch (SQLException e) {
e.printStackTrace();
} finally{
//out.close();
}
}
return model;
}
JSP is:
<body onload="checkMessage()">
<form:form id="mediaForm" method="get" action="userMediaSave" modelAttribute="mediaBean">
<table border="1" cellpadding="1" cellspacing="1"
style="width: 500px;" align="center">
<tbody>
<tr>
<td colspan="4" align="center">Name : Welcome to Media App</td>
</tr>
<tr>
<td rowspan="3">Profile Image</td>
<td>Upload Images</td>
<td><input type="file" name="mediaImage" /></td>
</tr>
<tr>
<td> </td>
<td><input name="upload" type="submit" value="Upload" /></td>
</tr>
</tbody>
</table>
<table border="1" cellpadding="1" cellspacing="1"
style="width: 500px;" align="center">
<tbody>
<tr>
<td>User has some existed Media Album</td>
</tr>
<tr>
<td>
<img src=${userMediaSave} alt="Profile images" style="width:100px;height:100px;">
</td>
</tr>
</tbody>
</table>
</form:form>
am i passing image from controller to JSP properly? if not please let me know which way i have to pass it.

Data not populating on page after processing post request

it shows data when get request is send properly but when i save data with post requset then again the page is rendered data is not coming on page
This is my controller code
#RequestMapping(value = "/incident", method = RequestMethod.GET)
public String add_incident(Model model,HttpSession session) {
try{
List<AddIncident> fetchincident = incService.fetchIncident();
String user_id = ""+session.getAttribute("session");
List<AddIncident> fetchuserincident = incService.fetchuserincident(user_id);
//group work
User user = new User();
model.addAttribute("user", user);
List<User> fetchListByUsername = userService.findListByUserName(user_id);
String department = fetchListByUsername.get(0).getDepartment();
List<AddIncident> fetchgroupincident = incService.fetchgroupincident(department);
System.out.println(fetchgroupincident.get(0).getAssignTo());
System.out.println(fetchgroupincident.get(0).getSeverity());
model.addAttribute("fetchincident", fetchincident);
model.addAttribute("fetchgroupincident", fetchgroupincident);
model.addAttribute("fetchuserincident", fetchuserincident);
}catch(Exception e){
e.printStackTrace(); }
AddIncident incident = new AddIncident();
model.addAttribute("incident", incident);
return "incident";
}
#RequestMapping(value = "/incident", method = RequestMethod.POST)
public String add_incident(
#Valid #ModelAttribute("incident") AddIncident incident,
BindingResult result, Model model,HttpSession session) {
if (result.hasErrors()) {
return "incident";
} else {
User user=new User();
System.out.println(""+session.getAttribute("session"));
String user_id = ""+session.getAttribute("session");
System.out.println(user_id);
List<User> fetchListByUsername = userService.findListByUserName(user_id);
String department = fetchListByUsername.get(0).getDepartment();
System.out.println(department);
try{
List<User> fetchgroupuser = userService.findListByGroup(department);
ArrayList<String> email=new ArrayList<String>();
System.out.println(email);
for(User use:fetchgroupuser){
email.add(use.getEmail());
}
String[] to = new String[email.size()];
to = email.toArray(to);
System.out.println(to);
/*new String[]{"irasoftwares6#gmail.com","bluemagictest#gmail.com"};*/
String from = "Anurag.yv19#gmail.com";
String sub= "Incident Management System";
String msgBody="New Incident created";
incService.save(incident);
emailService.sendEmail(to , from, sub, msgBody);
}catch(ArrayIndexOutOfBoundsException e){e.printStackTrace();}
incident_logger.log(INCIDENT, incident.getRef_id()+" \n Assigned to :"+session.getAttribute("session"));
model.addAttribute("message", "Saved incident details");
return "incident";
}
}
my jsp code
<div class="table-responsive" id="inc-table" style="min-height: 280px;">
<form action="" method="get">
<div class="input-group">
<!-- USE TWITTER TYPEAHEAD JSON WITH API TO SEARCH -->
<input class="form-control" id="system-search" name="q" placeholder="Search for" required>
<span class="input-group-btn">
<button type="submit" class="btn btn-default"><i class="glyphicon glyphicon-search"></i></button>
</span>
</div>
</form>
<table class="table table-list-search table-bordered table-stripped table-hover">
<thead>
<tr>
<th>Ref. No.</th>
<th>Created</th>
<th>Severity</th>
<th>State</th>
<th>Assigned</th>
<th>Est</th>
<th>Description</th>
<th>Location</th>
<th>Config-item</th>
<th>Symptom Code</th>
<th>Closure Code</th>
<th>Submitted BY</th>
</tr>
</thead>
<tbody>
<c:forEach var="fetchuserincident" items="${fetchuserincident}">
<tr>
<td id="1" class="click" ><a href=""/>${fetchuserincident.ref_id}</td>
<td>${fetchuserincident.created}</td>
<td>${fetchuserincident.severity}</td>
<td>${fetchuserincident.state}</td>
<td>${fetchuserincident.assignTo}</td>
<td>${fetchuserincident.escalation}</td>
<td>${fetchuserincident.description}</td>
<td>${fetchuserincident.location}</td>
<td>${fetchuserincident.config_Item}</td>
<td>${fetchuserincident.symptom_code}</td>
<td>${fetchuserincident.closure_code}</td>
<td>${fetchuserincident.submittedby}</td>
<td> <button id="editbtn" class="fa fa-pencil">Edit</button></td>
</tr>
</c:forEach>
</tbody>
</table>
</div>
<hr>
<br>
My Group Work
Ref. No.
Created
Severity
State
Assigned
Est
Description
Location
Config-item
Symptom Code
Closure Code
Submitted BY
${fetchgroupincident.ref_id}
${fetchgroupincident.created}
${fetchgroupincident.severity}
${fetchgroupincident.state}
${fetchgroupincident.assignTo}
${fetchgroupincident.escalation}
${fetchgroupincident.description}
${fetchgroupincident.location}
${fetchgroupincident.config_Item}
${fetchgroupincident.symptom_code}
${fetchgroupincident.closure_code}
${fetchgroupincident.submittedby}
Edit

Resources