gpt4 book ai didi

java - 使用 spring mvc 和 hibernate 在 jsp 上显示图像

转载 作者:行者123 更新时间:2023-11-30 03:42:11 24 4
gpt4 key购买 nike

我在mysql数据库中有一个BLOB类型的图像,我想在jsp上显示该图像。我正在使用 Hibernate 和 Spring MVC。这是我的模型类:

@Repository
@Entity
@Table(name = "foto")
public class Image {

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "fk_id_users", nullable = false)
private Users user;

@Id
@Column(name = "id_foto")
@GeneratedValue(strategy = GenerationType.AUTO)
private int id_foto;

@Column(name = "tipo")
private String tipo;

@Column(name = "size")
private String size;

@Column(name = "nome")
private String nome;

@Column(name = "image")
private byte[] image;

//Getters and Setters

这是我的 Controller :

@Controller
@SessionAttributes("UserSession")
public class LoginController {

@Autowired
private UsersService usersService;

@RequestMapping(value = "loginUsers", method = RequestMethod.POST)
public ModelAndView loginUsers(HttpServletRequest request,@RequestParam("username") String username,
@RequestParam("password") String password) {

Users user = usersService.loginUsers(username, password);

if( user == null ) {
ModelAndView MV = new ModelAndView("login");
MV.addObject("erroreLogin", "username e/o password errati");
return MV;
} else if ( user.getAmministratore() == false ){
request.getSession().setAttribute("UserSession",user);
ModelAndView mav = new ModelAndView("homeUtente");
mav.addObject("galleria", usersService.getAllFoto());
return mav;
} else {
request.getSession().setAttribute("UserSession",user);
ModelAndView mav = new ModelAndView("utenti");
mav.addObject("lista", usersService.getAllUtenti());
return mav;
}
}

@RequestMapping(value = "logout", method = RequestMethod.GET)
public ModelAndView logout(HttpServletRequest request) {
request.getSession().invalidate(); //invalido i dati presenti in sessione
return new ModelAndView("login");
}

}

在我的jsp中,我使用它来显示图像列表中的图像,因为每个用户都有一个要显示的图库:

<img alt="Kangoo_image" src="data:image/jpeg;base64,${galleria.image}" />

当我尝试在 jsp 中显示它时。它显示一些二进制文件,例如 [B@59e73b47.我怎样才能在jsp中显示这里的图像?

最佳答案

要在 JSP 上显示图像而不存储到文件系统并链接到它,您必须对字节数组进行 Base64 编码。通过以下几行即可轻松完成

byte[] encodeBase64 = Base64.encodeBase64(usersService.getAllFoto());
String base64Encoded = new String(encodeBase64, "UTF-8");
mav.addObject("galleria", usersService.getAllFoto());

IOUtils 和 Base64 均来自 org.apache.commonsEndFragment

关于java - 使用 spring mvc 和 hibernate 在 jsp 上显示图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26585804/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com