복붙노트

[SPRING] 봄 - jsp 파일에 이미지 표시

SPRING

봄 - jsp 파일에 이미지 표시

내 모델 저장소 이미지는 파일 이름 (String)과 데이터 (바이트 배열)로 설명됩니다. 나는 최대 절전 모드를 사용하며 여기에 내 모델이있다 :

@Entity
public class Image {

    private Long id;
    private String name;
    private byte[] data;

    @Id
    @GeneratedValue
    @Column(name = "IMAGE_ID")
    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    @Column(nullable = false, length = 100)
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Lob
    @Column(nullable = false)
    public byte[] getData() {
        return data;
    }

    public void setData(byte[] data) {
        this.data = data;
    }
}

하지만 웹 사이트에 저장된 이미지를 표시하고 싶습니다.

<img src="${image.data}" alt="car_image"/>

내가 어떻게 할 수 있니?

이미지에 대한 요청을 처리하는 컨트롤러를 작성해야합니까?

모든 코드 예제?

최신 정보

<bean id="viewResolver"
    class="org.springframework.web.servlet.view.UrlBasedViewResolver">
    <property name="viewClass"
        value="org.springframework.web.servlet.view.tiles2.TilesView" />
</bean>

<bean id="tilesConfigurer"
    class="org.springframework.web.servlet.view.tiles2.TilesConfigurer">
    <property name="definitions">
        <list>
            <value>/WEB-INF/configs/tiles.xml</value>
        </list>
    </property>
</bean>

해결법

  1. ==============================

    1.너는 이렇게 할 수 없다. 이미지는 정상적인 URL을 통해 어떻게 든 노출되어야합니다. Spring MVC에서는 특정 URL 아래 이미지 (원시 데이터)를 반환하는 컨트롤러를 생성한다.

    너는 이렇게 할 수 없다. 이미지는 정상적인 URL을 통해 어떻게 든 노출되어야합니다. Spring MVC에서는 특정 URL 아래 이미지 (원시 데이터)를 반환하는 컨트롤러를 생성한다.

    @RequestMapping(value = "/imageController/{imageId}")
    @ResponseBody
    public byte[] helloWorld(@PathVariable long imageId)  {
      Image image = //obtain Image instance by id somehow from DAO/Hibernate
      return image.getData();
    }
    

    이제 JSP 페이지에서 사용하십시오. 이것은 HTTP / HTML 작동 방법입니다.

    <img src="/yourApp/imageController/42.png" alt="car_image"/>
    

    3.1 이전의 Spring MVC에서는 컨트롤러 측에서 조금 더 코딩해야 할 수도있다. 그러나 원리는 같습니다.

  2. ==============================

    2.

    File file = new File("home/user/test.jpg");
    FileInputStream fis=new FileInputStream(file);
    ByteArrayOutputStream bos=new ByteArrayOutputStream();
    int b;
    byte[] buffer = new byte[1024];
    while((b=fis.read(buffer))!=-1){
       bos.write(buffer,0,b);
    }
    byte[] fileBytes=bos.toByteArray();
    fis.close();
    bos.close();
    
    
    byte[] encoded=Base64.encodeBase64(fileBytes);
    String encodedString = new String(encoded);
    
    ModelMap map = new ModelMap();
    map.put("image", encodedString);
    

    이제 다음과 같이 JSP 페이지에서 사용하십시오.

    <img src="data:image/jpeg;base64,${image}" alt="..." width="200" height="200">`
    
  3. ==============================

    3.이 게시물을 확인해야 할 수도 있습니다. 나는 당신과 비슷한 문제가 있고 해결책은 바이트 배열을 문자열로 변환하고 아래의 img 태그에서 설정하는 것입니다.

    이 게시물을 확인해야 할 수도 있습니다. 나는 당신과 비슷한 문제가 있고 해결책은 바이트 배열을 문자열로 변환하고 아래의 img 태그에서 설정하는 것입니다.

     <img src="data:image/jpg;base64,<c:out value='${bean.imageByteArrayString}'/>" />
    
  4. ==============================

    4.나는 며칠 동안 옳은 대답을 찾고 있었기 때문에 나를 위해 좋은 것을 쓸 것입니다.

    나는 며칠 동안 옳은 대답을 찾고 있었기 때문에 나를 위해 좋은 것을 쓸 것입니다.

    내 이미지가 이미 데이터베이스에 저장되었습니다.

    @Entity
    @Table(name="PRODUCT")
    public class Product {
    
     @Lob
     @Column(name="IMG")
     private byte[] img;
    
    // setters getters etc
    }
    

    이제 ShowPicture 예를 들어 내 수업에서 그것을 읽어야합니다.

    String encodedImage = Base64.encode(product.getImg());
    //setters and getters encodedImage
    

    그럼 내 JSP 페이지 :

    <img src='data:image/jpg;base64,<s:property value='encodedImage'/>' alt="my image" />
    

    그만큼 간단 해! :)

  5. ==============================

    5.

    byte[] img = yourImgEntity.getData();
    response.setContentType("image/*"); 
    response.setHeader(HttpHeaders.CACHE_CONTROL, "no-cache");
    //spring-core's FileCopyUtils
    FileCopyUtils.copy(img, response.getOutputStream());
    
    // or just use codes below instead of FileCopyUtils
    //response.getOutputStream().write(img);
    //response.getOutputStream().flush();
    //response.getOutputStream().close();
    
  6. ==============================

    6.어쩌면 늦은 것 같지만, 여기에 나와있는 것을 남겨두고 어쩌면 누군가가 도울 수 있습니다.

    어쩌면 늦은 것 같지만, 여기에 나와있는 것을 남겨두고 어쩌면 누군가가 도울 수 있습니다.

    나는 또한 Spring MVC와 Hibernate를 사용하고있다.

    모델 (엔티티 클래스)에서 String 유형의 변수를 만들어 Base64로 String 유형으로 변환합니다.

    나는 각자의 깃발을 가지고있는 국가들의 테이블을 위해이 작업을 수행했고, 내가 원했던 것은 모든 국가와 측면에 테이블의 테이블에 나열하는 것이 었습니다.

    모델 (엔티티)

    import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;
    import javax.persistence.Column;
    import javax.persistence.Entity;
    import javax.persistence.GeneratedValue;
    import javax.persistence.GenerationType;
    import javax.persistence.Id;
    import javax.persistence.Table;
    import javax.persistence.Transient;
    
    @Entity
    @Table(name = "country")
    public class Country implements java.io.Serializable {
    
    private int id;
    private String name;
    private byte[] flag;
    private String base64; //Variable to store the conversion of a data byte type to String
    
    @Transient //Annotation so it does not persist in the database
    public String getBase64() {
        //Convert the data type byte to String, store it in the variable and return it
        return this.base64 = Base64.encode(this.flag); 
    }
    
    public void setBase64(String base64) {
        this.base64 = base64;
    }
    
    public Country() {
    }
    
    public Country(int id, String name, byte[] flag, String base64) {
        this.id = id;
        this.name = name;
        this.flag = this.flag
        this.base64 = this.base64;
    }
    
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id", unique = true, nullable = false)
    public int getId() {
        return this.id;
    }
    
    public void setId(int id) {
        this.id = id;
    }
    
    @Column(name = "name")
    public String getName() {
        return this.name;
    }
    
    public void setName(String name) {
        this.name = name;
    }
    
    @Column(name = "flag")
    public byte[] getFlag() {
        return this.flag;
    }
    
    public void setFlag(byte[] flag) {
        this.flag = flag;
    }
    
    }
    

    저장소 - Implements는 인터페이스입니다. AbstractDao는 Abstract 클래스입니다.     import org.springframework.stereotype.Repository;     import application.model.Country;     import application.repository.dao.AbstractDao;     import application.repository.dao.CountryDao;     org.hibernate.Criteria 가져 오기;

    @Repository("countryDao")
    public class CountryDaoImpl extends AbstractDao<Integer, Country> implements CountryDao {
    
    @Override
    @SuppressWarnings("unchecked")
    public List<Country> listCountries() {
        Criteria criteria = createEntityCriteria(); //Country.class
        criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
        List<Country> listCountries = criteria.list();
        return listCountries;
    }
    
    }
    

    서비스 - 구현은 인터페이스입니다.

    import application.model.Country;
    import application.repository.dao.CountryDao;
    import application.service.dao.CountryService;
    import java.util.List;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    import org.springframework.transaction.annotation.Transactional;
    
    @Service("countryService")
    public class CountryServiceImpl implements CountryService {
    
    @Autowired
    private CountryDao countryDao;
    
    @Override
    @Transactional(readOnly = true)
    public List<Country> listCountries() {
        return countryDao.listCountries();
    }
    }
    

    제어 장치

    import application.model.Country;
    import application.service.dao.CountryService;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Controller;
    import org.springframework.ui.Model;
    import org.springframework.web.bind.annotation.RequestMapping;
    
    @Controller
    @RequestMapping(value = "/countries")
    public class CountryController {
    
    @Autowired
    private CountryService countryService;
    
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public String ListCountries(Model model) {
        model.addAttribute("listcont", countryService.listCountry());
        return "countries/countries"; //view
    }
    
    }
    

    보기 - countries / countries.jsp

    <%@page contentType="text/html" pageEncoding="UTF-8"%>
    <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
    <!DOCTYPE html>
    <html>
      <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
      </head>
      <body>
        <h3>List Countries</h3>
        <table>
          <thead>
            <tr>
              <th>Name</th>
              <th>Flag</th>
            </tr>
          </thead>
          <tbody>
            <c:forEach items="${listcont}" var="country">
             <tr>
              <td>${country.name}</td>
              <td><img src="data:image/png;base64,${country.base64}" /></
             </tr>
            </c:forEach>
          </tbody>
        </table> 
      </body>
    </html>
    
  7. from https://stackoverflow.com/questions/10066349/spring-display-image-on-jsp-file by cc-by-sa and MIT license