简体   繁体   English

如何使用Spring MVC在JSP上显示图像

[英]How to show image on JSP using Spring MVC

    //My Controller which handles image and Data
     @RequestMapping(value = "/student/edit/{id}/", method = RequestMethod.GET)
        public ModelAndView editStudent( @PathVariable Integer id,
                                        ModelMap model,
                                        HttpServletRequest request,HttpServletResponse response) throws IOException {

      Student student=studentservice.retieveStudent(id); 
                byte[] studentImage = student.getUserImage();
                response.setContentType("image/png");
                response.getOutputStream().write(studentImage);
                response.getOutputStream().flush();
                model.addAttribute("studentImage","studentImage")
                model.addAttribute("studentName",student.getStudentName);
                model.addAttribute("studentDetails",student.getStudentDetails);
            return new ModelAndView("viewstudent");
        }

student.jsp
<a href=student/edit/12><h1>Edit<h1></a>


 viewstudent.jsp   
<div>
 <table> <tr><td>Student Name=${studentName}</td></tr>
          <tr><td>StudentDetails=${studentDetails}</td></tr>
     <img src=data:image/jpeg;base64,"<c:out value='${studentImage}'/>" alt="my image" />
</table>

when i click on the link Edit only the image is getting shown on browser and viewstudent.jsp page is not getting displayd,How do I show image in viewstudent.jsp along with data After fetching from DB 当我单击链接仅编辑图像时,浏览器中将显示图像,而不能显示viewstudent.jsp页面,如何从数据库中获取数据后在viewstudent.jsp中显示图像以及数据

You don' seem to understand how HTTP and HTML works. 您似乎不了解HTTP和HTML的工作方式。

To display an HTML page containing an image, you need two HTTP requests. 要显示包含图像的HTML页面,您需要两个HTTP请求。 The first one gets the HTML page. 第一个获取HTML页面。 The HTML page contains a tag like HTML页面包含一个标签,例如

<img src="location_of_the_image" />

Then the browser parses the HTML, sees that it contains an img tag, and sendsa second HTTP request to the location of the image. 然后浏览器解析HTML,发现其中包含img标签,然后向图像位置发送第二个HTTP请求。 The response to this second HTTP request contains the bytes of the image. 对第二个HTTP请求的响应包含图像的字节。

So you should have two methods in your controller: one which returns a ModelAndView used to render the HTML page, and a second one which loads the bytes of the image, sets the content type, and sends the bytes to the response OutputStream. 因此,您的控制器中应该有两种方法:一种返回用于渲染HTML页面的ModelAndView,另一种加载图像的字节,设置内容类型并将字节发送到响应OutputStream。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM