Question: How to fix displaying the same image for item of each ?
thymleaf.html
<div th:each="goals : ${goals}">
<div th:text="${goals.getId()}"></div>
<img th:src="#{'image/'+ ${goals.getId()}}" width="100px;"
height="100px;"/>
<div th:text="${goals.title}"></div>
controller of image
#GetMapping(value = "/image/{id}")
public void showProductImage(#PathVariable String id,
HttpServletResponse response) throws IOException{
Goals goals = goalsRepository.findById(UUID.fromString(id));
logger.info("I got id--"+id);
response.setContentType("image/jpeg, image/jpg, image/png,
image/gif");
response.getOutputStream().write(goals.getImage());
response.getOutputStream().close();
controller of view page
#GetMapping(value = "/goals")
public String read(Model model) {
model.addAttribute("login", new LogIn()); //it for bottom menu
model.addAttribute("currentlyPage","goals"); // it for top menu
model.addAttribute("addNewGoal", new addNewGoal()); //another page
//get all goals
List<Goals> goals = new ArrayList<>();
goalsRepository.findAll().forEach(goals::add);
model.addAttribute("goals",goals);
return "goals";
log4j
I got id--bc8c9820-9500-
I got id--5ba1d0d0-9504-
I got id--bff1d8a0-94ff-
I got id--1f0da4f0-94ff-11e9-970f-0bfed788288d
I got id--d76dd9b0-9500-11e9-81ae-c9c1d3b67a0f
I got id--4aaaac80-9512-11e9-b98b-7deb4e16d250
I got id--608dae20-94ff-11e9-89b4-83a8b92aa5c9
I expect different images, but everywhere same images.enter image description here
I found the solution.
I changed image type of entity to ByteBuffer
I changed controller by next code:
#GetMapping(value = "/image/{id:.+}")
public #ResponseBody ResponseEntity<byte[]> showProductImage(#PathVariable String id, HttpServletResponse response) throws IOException {
Goals goals = goalsRepository.findById(UUID.fromString(id));
ByteBuffer buffer =goals.getImage();
byte[] bytes = buffer.array();
return ResponseEntity.ok().contentType(MediaType.IMAGE_JPEG).body(bytes);
}
I changed some valueOf type for converting .
Related
I have 2 methods that return a ModelAndView Object.
The first one gets the mapping from the browser and returns a modelandview that links to to an html file.
On that html file on the end I link a script tag to a spring root like this:
<!-- Calendar Js -->
<script type="text/javascript" src="../../../static/assets/vendor/netcorr/calendar/calendar.js"
th:src="#{/customer/web/wall/calendarItems(wallId=${wallId})}"></script>
In the controller, I have the second method that loads based on this call that I'm making just above:
/customer/web/wall/calendarItems(wallId=${wallId})
This method throws into the modelandview some objects that i need in the view.
This modelandview has root to a js file.
The problem is that the html does not load the js file that is called above.
Tried some solutions found on Stackoverflow, the solutions were to handle all of this in the mvdconfig controller.
And go throw the dependencies and make sure the dependencies are for Spring 4.
I m using Spring 1.5.9 and spring-boot-starter-thymeleaf
#GetMapping(value = "/customer/web/wall/calendar", params = {"wallId"})
public ModelAndView calendar(#RequestParam(value = "wallId") long wallId,
Authentication auth,
RedirectAttributes redirectAttributes){
ModelAndView modelAndView = new ModelAndView("/customer/wall/calendar");
modelAndView.addObject("wallId",wallId);
return modelAndView;
}
#GetMapping(value = "/customer/web/wall/calendarItems", params = {"wallId"})
public ModelAndView calendarItems(#RequestParam(value = "wallId") long wallId,
Authentication auth,
RedirectAttributes redirectAttributes){
User currentUser = (User) auth.getPrincipal();
Set<Long> wallIds = new HashSet<>();
wallIds.add(wallId);
PlaybookFilters playbookFilters = new PlaybookFilters();
playbookFilters.setCustomerId(currentUser.getCustomerId());
playbookFilters.setWallIds(wallIds);
List<Playbook> playbooks = playbookService.getPlaybooks(playbookFilters);
Date dateBegin = calendarService.getDateBegin();
Date dateEnd = calendarService.getDateEnd();
List<CalendarItem> calendarItems = calendarService.fetchPbiForPlaybooks(playbooks, dateBegin, dateEnd);
ArrayNode items = objectMapper.createArrayNode();
calendarItems.forEach(item -> items.add(item.toJsonNode()));
ModelAndView modelAndView = new ModelAndView("/customer/wall/calendarItems");
modelAndView.addObject("events", items);
return modelAndView;
}
I want to set the data inside a cell to be a link :
public class TestExcelExport extends AbstractXlsxView {
#Override
protected void buildExcelDocument(Map<String, Object> model, Workbook workbook, HttpServletRequest request, HttpServletResponse response) throws Exception {
response.setHeader("Content-Disposition", "attachment; filename=\"export.xlsx\"");
Sheet sheet = workbook.createSheet("test");
Row row_1 = sheet.createRow(1);
row_1.createCell(0).setCellValue("some data");
}
}
How to make the cell data to be a link pointing to a file in the system directory ?
CreationHelper createHelper = workbook.getCreationHelper();
Cell cell = row_1.createCell((short)0);
cell.setCellValue("System File Link");
link = createHelper.createHyperlink(Hyperlink.LINK_FILE);
link.setAddress("/usr/somedir/somefile.someext");
cell.setHyperlink(link);
This would do.
When I click on any link the content should be downloaded
But this is what I get.
MastercourseController.java
#RequestMapping(value = { ControllerUriConstant.download_file }, method = RequestMethod.GET)
#ResponseBody
public void downloadingAFileById(#RequestParam("id") String id, Model model, HttpServletRequest request)
throws TechnoShineException, IOException {
String filePath = "D:/dev/testFIle.txt";
long download = Long.parseLong(id);
byte[] b = masterCourseFileFormService.getAllDownloadable(download);
OutputStream outputStream = new FileOutputStream(filePath);
outputStream.write(b);
outputStream.close();
}
MasterCourseService
public byte[] getAllDownloadable(long id) throws TechnoShineException
{
return masterCourseFormUploadDao.getAllDownloadableFiles(id);
}
MasterCourseDao
public byte[] getAllDownloadableFiles(long id) throws TechnoShineException
{
return masterCourseFormUploadMapper.getAllDownloadable(id);
}
MasterCourseMapper
public byte[] getAllDownloadable(long id) throws TechnoShineException;
You are writing the data returned by getAllDownloadable(..) to a hard-coded file. Are you sure that is what you want? I think you want to write the content returned by getAllDownloadable(..) to be written into the response. That can be done by adding a method parameter of the type HttpServletResponse to your mapping and writing into the output stream returned by HttpServletResponse#getOutputStream() and flushing (not closing!) that stream at the end.
Furthermore you have to remove the #ResponseBody annotation as this is meant to be used if the value that is returned by the mapping method returns the data that should directly be sent to the client (i.e. when sending a JSON data object or a string) without passing it to the template engine. As you are not returning anything you can remove this annotation.
Furthermore you have to set the content type of your response by invoking HttpServletResponse#setContentType(contentType: String).
In your case, the invocation would be the following:
response.setContentType("text/plain");
You complete method would look like this:
#RequestMapping(
value = ControllerUriConstant.download_file,
method = RequestMethod.GET
)
public void downloadingAFileById(#RequestParam("id") String id, HttpServletResponse response)
throws TechnoShineException, IOException {
long download = Long.parseLong(id);
byte[] b = masterCourseFileFormService.getAllDownloadable(download);
response.getOutputStream().write(b);
response.getOutputStream().flush();
}
I need to return image in my Spring controller.
I try answer in this Spring MVC: How to return image in #ResponseBody? but it's not working
my code is like this
#RequestMapping(value = "cabang/photo", method = RequestMethod.GET)
#ResponseBody
public ResponseEntity<byte[]> getPhoto() throws IOException {
File imgPath = new File("D:\\test.jpg");
byte[] image = Files.readAllBytes(imgPath.toPath());
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.IMAGE_JPEG);
headers.setContentLength(image.length);
return new ResponseEntity<>(image, headers, HttpStatus.OK);
}
but when I access it in browser, it doesn't show anything (just no picture icon). But if I read the image byte array, it is not empty.
Do I miss anything in my code?
Your code looks ok. Make sure you added ByteArrayHttpMessageConverter to your application's list of http message converters.
Java Config :
#Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
ByteArrayHttpMessageConverter byteConverter = new ByteArrayHttpMessageConverter();
converters.add(byteConverter);
super.configureMessageConverters(converters);
}
I have this problem in my Spring MVC 2.5 apps and I am not sure what should I do.
Here is my code:
public class AddStationController extends SimpleFormController {
private SimpleStationManager stationManager;
protected ModelAndView onSubmit(HttpServletRequest request,
HttpServletResponse response, Object command, BindException errors)
throws Exception {
StationDetails detail = (StationDetails) command;
//add to DB
int return = stationManager.addStation(detail);
//return value: 1 = successful,
// if not = unsuccessful
if(return != 1){
//how can I add error so that when I display my formview ,
//I could notify the user that saving to the db is not successful?
showform();
}
return new ModelAndView("redirect:" + getSuccessView());
}
}
How is it possible to add some message when I display my formview again so that I could tell the user that adding the station was not successful?
And how to handle that in my jsp?
I at first thought you might want to use Validators but instead I think you can do the following:
public class AddStationController extends SimpleFormController {
private SimpleStationManager stationManager;
protected ModelAndView onSubmit(HttpServletRequest request,
HttpServletResponse response, Object command, BindException errors)
throws Exception {
StationDetails detail = (StationDetails) command;
//add to DB
int return = stationManager.addStation(detail);
//return value: 1 = successful,
// if not = unsuccessful
if(return != 1){
//Account for failure in adding station
errors.reject("exception.station.submitFailure", "Adding the station was not successful");
showform(request, response, errors);
}
return new ModelAndView("redirect:" + getSuccessView());
}
}
Then in your JSP you can do the following:
<form:errors path="*">
Then any errors you bind will show up there.
There are a couple ways to do that. I prefer not to use the showForm() method b/c I want more control. So I do one of the following, I'm sure there will be several alternative answers given for your question.
If you don't want to fail b/c of a specific field you can just send back an error on the model like this:
ModelAndView mav = new ModelAndView(this.getFormView());
mav.addObject(this.getCommandName(), command);
mav.addObject("errorMessage", "The thing you tried to do failed");
return mav;
Then in your jsp you would do this:
<c:if test="${not empty errorMessage}">
${errorMessage}
</c:if>
If you have a specific field that has caused the error you can attach an error to the specific field like this (this rejects the length of a field called "alternateid":
errors.rejectValue("alternateId", "longerThan",
new Object[] { Integer.valueOf(2) }, "Please enter at least two characters.");
ModelAndView mav = new ModelAndView(this.getFormView());
mav.addAllObjects(errors.getModel());
mav.addObject(this.getCommandName(), command);
return mav;
Then in your jsp you would use the form tag library and do this:
<form:errors path="alternateId"/>
That's assuming you're using the spring form tag library.