AJAX Call, it returns NOT Acceptable using SPRING MVC Hibernate - ajax

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.

Related

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

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

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.

Ajax return form modelattribute

I have the following situation. In controller in method viewUserReminders I pass remindersListWrapper to my uReminder.jsp page.
#RequestMapping(value = "/user/reminders", method = RequestMethod.GET)
public ModelAndView viewUserReminders(Model model, #ModelAttribute("id_users") Long id_users) throws Exception {
ModelAndView mv = new ModelAndView();
mv.setViewName("user/uReminders");
List<Reminders> remindersList=userService.getUserReminders(id_users);
RemindersListWrapper remindersListWrapper=new RemindersListWrapper();
remindersListWrapper.setRemindersList(remindersList);
mv.addObject("remindersListWrapper", remindersListWrapper);
return mv;
}
In my uReminders.jsp file I have a form with modelattribute remindersListWrapper. This jsp page displays table of reminders. Next to every reminder there is a checkbox. The user can check several checkboxes, click button("Mark as read") and using Ajax I submit form and go to controller method
readReminders().
uReminders.jsp
<form:form action="/user/ajax/reminders/readReminders" method="POST" modelAttribute="remindersListWrapper" id="remindersForm">
<div id="main">
<table class="table">
<thead>
<tr>
<th></th>
<th></th>
<th>Reminder</th>
</tr>
</thead>
<tbody>
<c:choose>
<c:when test="${not empty remindersListWrapper.remindersList}">
<c:forEach items="${remindersListWrapper.remindersList}" varStatus="status" var="reminders">
<tr id="row">
<td><form:hidden path="remindersList[${status.index}].idCalendar"/></td>
<td><form:checkbox path="remindersList[${status.index}].isRead"/></td>
<td><form:input path="remindersList[${status.index}].endDate"/></td>
</tr>
</c:forEach>
</c:when>
<c:when test="${empty remindersListWrapper.remindersList}">
<tr>
<td colspan="3">You have no reminders.</td>
</tr>
</c:when>
</c:choose>
</tbody>
</table>
<c:choose>
<c:when test="${not empty remindersListWrapper.remindersList}">
<input type="button" id="reminders" value="Mark as read"/>
</c:when>
</c:choose>
</div>
</form:form>
$(window).load(function () {
$("#reminders").click(function () {
sendAjax('readReminders', $("#remindersForm").serialize());
});
});
In this method I save read reminders and I build newRemindersListWrapper with the new list of reminders(I want to delete checked reminders and display only unchecked). My first question is: How to return to the page newRemindersListWrapper itself.
#RequestMapping(value = "/user/ajax/reminders/readReminders", method = RequestMethod.POST)
#ResponseBody
public String readReminders(#ModelAttribute("remindersListWrapper") RemindersListWrapper remindersListWrapper, #ModelAttribute("id_users") Long id_users) throws Exception {
for(Reminders reminders:remindersListWrapper.getRemindersList()){
if(reminders.getIsRead()){
userDao.saveReadReminders(reminders);
}
}
RemindersListWrapper newRemindersListWrapper=new RemindersListWrapper();
///////////////////
here I want to return the newRemindersListWrapper itself
//////////////////
}
And my second question is: How I can set newRemindersListWrapper as modelattribute in my form.
function sendAjax(ref, data) {
console.log(data);
$.ajax({
url: 'ajax/reminders/' + ref,
type: 'POST',
data: data,
success: function (response) {
////////////////////////////////
I want to get newRemindersListWrapper and set it as modelattribute in form.
////////////////////////////////
console.log("success");
},
error: function (request, status, error) {
console.log('error ' + ref + ' text=' + request.responseText + ' status = ' + status + ' error = ' + error);
}
});
}
Question 1: just change the return type to RemindersListWrapper and return it
Question 2: Since you are using ajax, you can't. You need to use javascript to parse the returned list and update the page as needed.

spring mvc return modelandview after ajax call

in my form I have table to show some of customer data.user can click on row to see all of customer data.
<div class="container">
<table class="table table-bordered" style="direction: rtl">
<thead>
<tr>
<th style="text-align: center">customer name</th>
<th style="text-align: center">customer ID</th>
</tr>
</thead>
<tbody>
<c:forEach items="${customers}" var="customer" varStatus="loop">
<tr onclick="retrieveCustomer('${loop.index}')">
<td id="id-${loop.index}">${customer.customerId}</td>
<td>${customer.customerName}</td>
</tr>
</c:forEach>
</tbody>
</table>
</div>
<script>
function retrieveCustomer(id) {
debugger;
$.ajax({
url: "<%=request.getContextPath()%>/show_selected_customer",
data: {customerId: $('#id-' + id).text()},
type: "GET",
success: function (response) {
},
error: function (xhr, status, error) {
alert(error);
}
});
};
</script>
and in my controller:
#RequestMapping(value = "/show_selected_customer", method = RequestMethod.GET)
public ModelAndView showSelectedCustomer(#RequestParam("customerId") String customerId) {
Map<String, Object> model = new HashMap<>();
Customer customer = coreService.getCustomer(customerId);
model.put("customer", customer);
return new ModelAndView("showCustomerData", model);
}
tiles:
<definition name="showCustomerData" extends="base.definition">
<put-attribute name="title" value="customer data"/>
<put-attribute name="content" value="/WEB-INF/jsp/show_customer_data.jsp"/>
</definition>
until now every thing work correctly.
my problem is, it doesn't show show_customers.jsp page,and even I have no error in my log.
what is my problem,Is because of ajax call? I did`t use #responsebody and want to show customers.jsp page with return modelandview. thank you
Use the response body annotation and convert your entity to JSON and return it instead.

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.

Resources