java - 如何使用spring mvc和jsp从mysql数据库显示@Lob图像

标签 java mysql spring-mvc jsp blob

有github链接:https://github.com/Lukszn/ProjectProfile我正在使用 Spring 4.3.7.RELEASE、MySQL Connector Java:5.1.39 和 hibrnate:5.2.9。最后 我有用户和他的帐户模型。在帐户中,我有@Lob accPicture 和一些字符串(+ get/set)。我正在尝试 stackoverflow 和文档中的很多答案来显示帐户图像,但没有成功。最后想想我做了什么:创建自己的 ImageController。我成功地将图像存储在数据库中,但是当我尝试在 jsp 中显示它时,它显示“HTTP Status 400 - 客户端发送的请求在语法上不正确。” 首先我向您展示我的用户模型:

@Entity
@Table(name = "users")
public class User implements Serializable{

    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;

    @Column(unique = true)
    @NotBlank
    @Size(min=4,max=20)
    private String login;

    @NotBlank
    private String password;

    @Column(unique = true)
    @Email
    @NotBlank
    private String email;

    private String permission;

    @OneToMany()
    private List<Account> accounts;


    public User(final String login, final String password, final String email) {
        Preconditions.checkArgument(!Strings.isNullOrEmpty(login));
        Preconditions.checkArgument(!Strings.isNullOrEmpty(password));
        Preconditions.checkArgument(!Strings.isNullOrEmpty(email));
        this.login = login;
        this.password = password;
        this.email = email;
    }

    public User() {
    }
}
+ get/set

帐户模型:

@Entity
@Table(name = "accounts")
public class Account {


    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;

    private boolean ifBasicAccount;

    private String accTitle;

    private String accFirstName;

    private String accLastName;

    private String accBirthdate;

    private String accPhoneNumber;

    private String accEducation;

    private String accExperience;

    private String accAbilities;

    private String accInterests;

    private String accProjects;

    private String accDescription;

    @Lob
    private byte[] accPicture;


    @ManyToOne
    private User user;


    public Account() {
    }

   + get/set

下一个帐户 Controller :

@Controller
public class AccountController {

    @Autowired
    AccountRepository accountRepository;

    @Autowired
    UserRepository userRepository;


    @RequestMapping(method = RequestMethod.GET, value ="addAccount")
    public String addAccount(Model model) {
        Account account = new Account();
        model.addAttribute("account", account);

        return "addAccount";
    }

    @RequestMapping(method = RequestMethod.POST, value ="addAccount")
    public String addAccount(@ModelAttribute Account account, HttpSession session) {
        User user = userRepository.findOne((Long) session.getAttribute("user_id"));
        account.setIfBasicAccount(false);
        account.setUser(user);
        accountRepository.save(account);
        return "redirect:/accounts";
    }

    @RequestMapping("/accounts")
    public String accountList(Model model, HttpSession ses) {
        long userId = (Long) ses.getAttribute("user_id");
        List<Account> accounts = accountRepository.findUserAccounts(userId);
        model.addAttribute("accounts", accounts);
        return "accounts";
    }

    @RequestMapping(value = "/edit/{id}", method = RequestMethod.GET)
    public String editAccountForm(Model model, @PathVariable long id) {
        Account account = accountRepository.findOne(id);
        model.addAttribute("account",account);
        return "editAccountForm";
    }

    @RequestMapping(value = "/edit/{id}", method = RequestMethod.POST)
    public String editAccount(@ModelAttribute Account account, @PathVariable long id) {
        Account accountToUpdate = accountRepository.findOne(id);
        accountToUpdate.setAccTitle(account.getAccTitle());
        accountToUpdate.setAccFirstName(account.getAccFirstName());
        accountToUpdate.setAccLastName(account.getAccLastName());
        accountToUpdate.setAccBirthdate(account.getAccBirthdate());
        accountToUpdate.setAccPhoneNumber(account.getAccPhoneNumber());
        accountToUpdate.setAccEducation(account.getAccEducation());
        accountToUpdate.setAccExperience(account.getAccExperience());
        accountToUpdate.setAccAbilities(account.getAccAbilities());
        accountToUpdate.setAccInterests(account.getAccInterests());
        accountToUpdate.setAccProjects(account.getAccProjects());
        accountToUpdate.setAccDescription(account.getAccDescription());
        accountRepository.save(accountToUpdate);
        return "redirect:/accounts";
    }

    @RequestMapping("/delete")
    public String deleteAccount(Model model) {
        return "deleteAccount";
    }

    @RequestMapping("/read/{id}")
    public String read(@PathVariable long id) {
        return accountRepository.findOne(id).toString();
    }

    @RequestMapping("/delete/{id}")
    public String delete(@PathVariable long id) {
        Account account = accountRepository.findOne(id);
        accountRepository.delete(account);
        return "redirect:/accounts";
    }
}

最后一个 ImageController:

@Controller
@RequestMapping("/user")
public class ImageController {

    private AccountRepository accountRepository;

    @RequestMapping(value = "/accounts", method = RequestMethod.GET)
    public void showImage(@RequestParam("id") Long id, HttpServletResponse response, HttpServletRequest request)
            throws ServletException, IOException {

        Account account = accountRepository.getOne(id);
        response.setContentType("image/jpeg, image/jpg, image/png, image/gif");
        response.getOutputStream().write(account.getAccPicture());

        response.getOutputStream().close();
    }
}

我的 .jsp 显示帐户:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    <%@ taglib prefix = "c" uri = "http://java.sun.com/jsp/jstl/core" %>
    <%@ taglib prefix = "fmt" uri = "http://java.sun.com/jsp/jstl/fmt" %>
     <%@ page isELIgnored="false" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%@ include file="/WEB-INF/parts/header.jsp" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<div align="center">
<table class="table table-striped">
<h1>Accounts:</h1>
<c:forEach items="${accounts}" var="account" begin="0" varStatus="theCount">

    <tr>
        <td>${theCount.index+1}</td>
        <td><b>Nazwa: </b>${account.accTitle}</td>
        <td><b>Opis: </b>${account.accDescription}</td>
        <td><img src="/ProjectProfile/user/accounts?id=${account.id}"/></td>
        <td><a style="width: 180px;height: 20px;" href="./edit/${account.id}" class="badge badge-primary">Show/Edit</a></td>
        <td><a style="width: 180px;height: 20px;" href="./delete/${account.id}" class="badge badge-danger">Delete</a></td>
    </tr>
</c:forEach>
</table>

     <a href="<c:url value="/addAccount"/>">Add Account</a>

</body>
</html>

也许我需要使用 Base64Encoder,但我不知道如何? ....我使用 pom.xml 和 AppConfig 进行配置。请查看这个项目,也许有人可以提供帮助?

最佳答案

<img id="photo" src="data:image/png;base64,${PHOTOYOUNEED}" />

在负责将图像发送到html的 Controller 中:

(...)
    String photoencodeBase64 = modelX.getStringPhoto();
    modelAndView.addObject("PHOTOYOUNEED", photoencodeBase64 );

我还在模型中使用此方法将 byte[] 转换为 base64 中的字符串:

public static String convertBinImageToString(byte[] binImage) {
    if(binImage!=null && binImage.length>0) {
        return Base64.getEncoder().encodeToString(binImage);
    }
    else
        return "";
}

我在模型内的 getStringPhoto() getter 中调用它。

关于java - 如何使用spring mvc和jsp从mysql数据库显示@Lob图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51062455/

相关文章:

java - 测量垃圾收集时间的阻塞部分

java - 如何使用 Intent 打开电子邮件应用程序

java - 微调框已选择项目选择事件

mysql - 是否可以使用通配符来检查 SQL 中的数字列?

spring - 找不到类型类 User 的属性 findOne()

java - Spring Boot Maven webapp 文件夹和 ResourceHandler

php - 如何使用 mysql PDO 和 OR 表达式计算字段数量?

php - 如何提高mysql查询的性能?

java - 子类实现上的@Required注解

java - 具有不包括静态的上下文路径的Spring Boot