如何使用springmvc和jsp显示mysql数据库中的@lob图像

yfjy0ee7  于 2021-06-24  发布在  Mysql
关注(0)|答案(3)|浏览(399)

有到github的链接:https://github.com/lukszn/projectprofile 我使用的是spring4.3.7.release、mysql连接器java:5.1.39和hibrnate:5.2.9。最后,我有用户和他的帐户模型。帐户中有@lob accpicture和一些字符串(+get/set)。我试图从stackoverflow和文档中找到很多答案来显示帐户图像,但没有成功。最后想想我做了什么:创建了自己的imagecontroller。我成功地将图像存储在数据库中,但当我尝试在jsp中显示它时,它显示“http状态400-客户端发送的请求语法不正确”。首先,我向您显示我的用户模型:

  1. @Entity
  2. @Table(name = "users")
  3. public class User implements Serializable{
  4. /**
  5. *
  6. */
  7. private static final long serialVersionUID = 1L;
  8. @Id
  9. @GeneratedValue(strategy = GenerationType.IDENTITY)
  10. private long id;
  11. @Column(unique = true)
  12. @NotBlank
  13. @Size(min=4,max=20)
  14. private String login;
  15. @NotBlank
  16. private String password;
  17. @Column(unique = true)
  18. @Email
  19. @NotBlank
  20. private String email;
  21. private String permission;
  22. @OneToMany()
  23. private List<Account> accounts;
  24. public User(final String login, final String password, final String email) {
  25. Preconditions.checkArgument(!Strings.isNullOrEmpty(login));
  26. Preconditions.checkArgument(!Strings.isNullOrEmpty(password));
  27. Preconditions.checkArgument(!Strings.isNullOrEmpty(email));
  28. this.login = login;
  29. this.password = password;
  30. this.email = email;
  31. }
  32. public User() {
  33. }
  34. }
  35. + get/set

客户模型:

  1. @Entity
  2. @Table(name = "accounts")
  3. public class Account {
  4. @Id
  5. @GeneratedValue(strategy = GenerationType.AUTO)
  6. private long id;
  7. private boolean ifBasicAccount;
  8. private String accTitle;
  9. private String accFirstName;
  10. private String accLastName;
  11. private String accBirthdate;
  12. private String accPhoneNumber;
  13. private String accEducation;
  14. private String accExperience;
  15. private String accAbilities;
  16. private String accInterests;
  17. private String accProjects;
  18. private String accDescription;
  19. @Lob
  20. private byte[] accPicture;
  21. @ManyToOne
  22. private User user;
  23. public Account() {
  24. }
  25. + get/set

下一个帐户控制器:

  1. @Controller
  2. public class AccountController {
  3. @Autowired
  4. AccountRepository accountRepository;
  5. @Autowired
  6. UserRepository userRepository;
  7. @RequestMapping(method = RequestMethod.GET, value ="addAccount")
  8. public String addAccount(Model model) {
  9. Account account = new Account();
  10. model.addAttribute("account", account);
  11. return "addAccount";
  12. }
  13. @RequestMapping(method = RequestMethod.POST, value ="addAccount")
  14. public String addAccount(@ModelAttribute Account account, HttpSession session) {
  15. User user = userRepository.findOne((Long) session.getAttribute("user_id"));
  16. account.setIfBasicAccount(false);
  17. account.setUser(user);
  18. accountRepository.save(account);
  19. return "redirect:/accounts";
  20. }
  21. @RequestMapping("/accounts")
  22. public String accountList(Model model, HttpSession ses) {
  23. long userId = (Long) ses.getAttribute("user_id");
  24. List<Account> accounts = accountRepository.findUserAccounts(userId);
  25. model.addAttribute("accounts", accounts);
  26. return "accounts";
  27. }
  28. @RequestMapping(value = "/edit/{id}", method = RequestMethod.GET)
  29. public String editAccountForm(Model model, @PathVariable long id) {
  30. Account account = accountRepository.findOne(id);
  31. model.addAttribute("account",account);
  32. return "editAccountForm";
  33. }
  34. @RequestMapping(value = "/edit/{id}", method = RequestMethod.POST)
  35. public String editAccount(@ModelAttribute Account account, @PathVariable long id) {
  36. Account accountToUpdate = accountRepository.findOne(id);
  37. accountToUpdate.setAccTitle(account.getAccTitle());
  38. accountToUpdate.setAccFirstName(account.getAccFirstName());
  39. accountToUpdate.setAccLastName(account.getAccLastName());
  40. accountToUpdate.setAccBirthdate(account.getAccBirthdate());
  41. accountToUpdate.setAccPhoneNumber(account.getAccPhoneNumber());
  42. accountToUpdate.setAccEducation(account.getAccEducation());
  43. accountToUpdate.setAccExperience(account.getAccExperience());
  44. accountToUpdate.setAccAbilities(account.getAccAbilities());
  45. accountToUpdate.setAccInterests(account.getAccInterests());
  46. accountToUpdate.setAccProjects(account.getAccProjects());
  47. accountToUpdate.setAccDescription(account.getAccDescription());
  48. accountRepository.save(accountToUpdate);
  49. return "redirect:/accounts";
  50. }
  51. @RequestMapping("/delete")
  52. public String deleteAccount(Model model) {
  53. return "deleteAccount";
  54. }
  55. @RequestMapping("/read/{id}")
  56. public String read(@PathVariable long id) {
  57. return accountRepository.findOne(id).toString();
  58. }
  59. @RequestMapping("/delete/{id}")
  60. public String delete(@PathVariable long id) {
  61. Account account = accountRepository.findOne(id);
  62. accountRepository.delete(account);
  63. return "redirect:/accounts";
  64. }
  65. }

最后一个图像控制器:

  1. @Controller
  2. @RequestMapping("/user")
  3. public class ImageController {
  4. private AccountRepository accountRepository;
  5. @RequestMapping(value = "/accounts", method = RequestMethod.GET)
  6. public void showImage(@RequestParam("id") Long id, HttpServletResponse response, HttpServletRequest request)
  7. throws ServletException, IOException {
  8. Account account = accountRepository.getOne(id);
  9. response.setContentType("image/jpeg, image/jpg, image/png, image/gif");
  10. response.getOutputStream().write(account.getAccPicture());
  11. response.getOutputStream().close();
  12. }
  13. }

显示帐户的my.jsp:

  1. <%@ page language="java" contentType="text/html; charset=UTF-8"
  2. pageEncoding="UTF-8"%>
  3. <%@ taglib prefix = "c" uri = "http://java.sun.com/jsp/jstl/core" %>
  4. <%@ taglib prefix = "fmt" uri = "http://java.sun.com/jsp/jstl/fmt" %>
  5. <%@ page isELIgnored="false" %>
  6. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
  7. <%@ include file="/WEB-INF/parts/header.jsp" %>
  8. <html>
  9. <head>
  10. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  11. <title>Insert title here</title>
  12. </head>
  13. <body>
  14. <div align="center">
  15. <table class="table table-striped">
  16. <h1>Accounts:</h1>
  17. <c:forEach items="${accounts}" var="account" begin="0" varStatus="theCount">
  18. <tr>
  19. <td>${theCount.index+1}</td>
  20. <td><b>Nazwa: </b>${account.accTitle}</td>
  21. <td><b>Opis: </b>${account.accDescription}</td>
  22. <td><img src="/ProjectProfile/user/accounts?id=${account.id}"/></td>
  23. <td><a style="width: 180px;height: 20px;" href="./edit/${account.id}" class="badge badge-primary">Show/Edit</a></td>
  24. <td><a style="width: 180px;height: 20px;" href="./delete/${account.id}" class="badge badge-danger">Delete</a></td>
  25. </tr>
  26. </c:forEach>
  27. </table>
  28. <a href="<c:url value="/addAccount"/>">Add Account</a>
  29. </body>
  30. </html>

也许我需要用Base64编码器,但我不知道怎么用。。。。我使用pom.xml和appconfig进行配置。拜托,看看这个项目,也许有人能帮上忙?

gev0vcfq

gev0vcfq1#

好吧,尤尼托,让我看看。。。已更改的account.java(模型):

  1. @Entity
  2. @Table(name = "accounts")
  3. public class Account {
  4. @Id
  5. @GeneratedValue(strategy = GenerationType.AUTO)
  6. private long id;
  7. private boolean ifBasicAccount;
  8. private String accTitle;
  9. private String accFirstName;
  10. private String accLastName;
  11. private String accBirthdate;
  12. private String accPhoneNumber;
  13. private String accEducation;
  14. private String accExperience;
  15. private String accAbilities;
  16. private String accInterests;
  17. private String accProjects;
  18. private String accDescription;
  19. @Lob
  20. private byte[] accPicture;
  21. private String stringPhoto;
  22. @ManyToOne
  23. private User user;
  24. public Account() {
  25. }
  26. public long getId() {
  27. return id;
  28. }
  29. public void setId(long id) {
  30. this.id = id;
  31. }
  32. public String getAccTitle() {
  33. return accTitle;
  34. }
  35. public void setAccTitle(String accTitle) {
  36. this.accTitle = accTitle;
  37. }
  38. public String getAccFirstName() {
  39. return accFirstName;
  40. }
  41. public void setAccFirstName(String accFirstName) {
  42. this.accFirstName = accFirstName;
  43. }
  44. public String getAccLastName() {
  45. return accLastName;
  46. }
  47. public void setAccLastName(String accLastName) {
  48. this.accLastName = accLastName;
  49. }
  50. public String getAccBirthdate() {
  51. return accBirthdate;
  52. }
  53. public void setAccBirthdate(String accBirthdate) {
  54. this.accBirthdate = accBirthdate;
  55. }
  56. public String getAccPhoneNumber() {
  57. return accPhoneNumber;
  58. }
  59. public void setAccPhoneNumber(String accPhoneNumber) {
  60. this.accPhoneNumber = accPhoneNumber;
  61. }
  62. public String getAccEducation() {
  63. return accEducation;
  64. }
  65. public void setAccEducation(String accEducation) {
  66. this.accEducation = accEducation;
  67. }
  68. public String getAccExperience() {
  69. return accExperience;
  70. }
  71. public void setAccExperience(String accExperience) {
  72. this.accExperience = accExperience;
  73. }
  74. public String getAccAbilities() {
  75. return accAbilities;
  76. }
  77. public void setAccAbilities(String accAbilities) {
  78. this.accAbilities = accAbilities;
  79. }
  80. public String getAccInterests() {
  81. return accInterests;
  82. }
  83. public void setAccInterests(String accInterests) {
  84. this.accInterests = accInterests;
  85. }
  86. public String getAccProjects() {
  87. return accProjects;
  88. }
  89. public void setAccProjects(String accProjects) {
  90. this.accProjects = accProjects;
  91. }
  92. public String getAccDescription() {
  93. return accDescription;
  94. }
  95. public void setAccDescription(String accDescription) {
  96. this.accDescription = accDescription;
  97. }
  98. public byte[] getAccPicture() {
  99. return accPicture;
  100. }
  101. public void setAccPicture(byte[] accPicture) {
  102. this.accPicture = accPicture;
  103. }
  104. public String getStringPhoto() {
  105. return convertBinImageToString(accPicture);
  106. }
  107. public void setStringPhoto(String stringPhoto) {
  108. this.stringPhoto = stringPhoto;
  109. }
  110. public User getUser() {
  111. return user;
  112. }
  113. public void setUser(User user) {
  114. this.user = user;
  115. }
  116. public boolean isIfBasicAccount() {
  117. return ifBasicAccount;
  118. }
  119. public void setIfBasicAccount(boolean ifBasicAccount) {
  120. this.ifBasicAccount = ifBasicAccount;
  121. }
  122. public static String convertBinImageToString(byte[] accPicture) {
  123. if(accPicture!=null && accPicture.length>0) {
  124. return Base64.getEncoder().encodeToString(accPicture);
  125. }
  126. else
  127. return "";
  128. }
  129. }

我有两个控制器(一个仅用于显示图像-我不太确定这是件好事,因为我有两个相同的请求Map)。因此,请参见更改的imagecontroller:

  1. @Controller
  2. @RequestMapping("/admin/user")
  3. public class ImageController {
  4. @Autowired
  5. AccountRepository accountRepository;
  6. @RequestMapping(value = "/accounts", method = RequestMethod.GET)
  7. public void showImage(@RequestParam("id") long id, Model model) {
  8. Account account = accountRepository.findById(id);
  9. String photoencodeBase64 = account.getStringPhoto();
  10. model.addAttribute("accPicture", photoencodeBase64);
  11. }
  12. }

和.jsp来显示图像:

  1. <%@ page language="java" contentType="text/html; charset=UTF-8"
  2. pageEncoding="UTF-8"%>
  3. <%@ taglib prefix = "c" uri = "http://java.sun.com/jsp/jstl/core" %>
  4. <%@ taglib prefix = "fmt" uri = "http://java.sun.com/jsp/jstl/fmt" %>
  5. <%@ page isELIgnored="false" %>
  6. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
  7. <%@ include file="/WEB-INF/parts/header.jsp" %>
  8. <html>
  9. <head>
  10. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  11. <title>Insert title here</title>
  12. </head>
  13. <body>
  14. <div align="center">
  15. <table class="table table-striped">
  16. <h1>Accounts:</h1>
  17. <c:forEach items="${accounts}" var="account" begin="0" varStatus="theCount">
  18. <tr>
  19. <td>${theCount.index+1}</td>
  20. <td><b>Title: </b>${account.accTitle}</td>
  21. <td><b>Description: </b>${account.accDescription}</td>
  22. <td><b>Image: </b><img id="photo" src="data:image/png;base64,${account.accPicture}" /></td>
  23. <td><a style="width: 180px;height: 20px;" href="./edit/${account.id}" class="badge badge-primary">Show/Edit</a></td>
  24. <td><a style="width: 180px;height: 20px;" href="./delete/${account.id}" class="badge badge-danger">Delete</a></td>
  25. </tr>
  26. </c:forEach>
  27. </table>
  28. <a href="<c:url value="/addAccount"/>">Add Account</a>
  29. </body>
  30. </html>

当我添加新帐户->写标题,名字等,从我的浏览器显示的文件中添加图像时,会发生什么 HTTP Status 400 - The request sent by the client was syntactically incorrect. ->我需要查看所有用户帐户。在sts控制台里什么也没发生。在mysql中也是如此。

展开查看全部
41ik7eoe

41ik7eoe2#

为什么不使用spring内容jpa呢?这可以提供存储服务和rest端点,用于管理与jpa实体关联的内容。
pom.xml文件

  1. <!-- Java API -->
  2. <dependency>
  3. <groupId>com.github.paulcwarren</groupId>
  4. <artifactId>spring-content-jpa</artifactId>
  5. <version>0.1.0</version>
  6. </dependency>
  7. <!-- REST API -->
  8. <dependency>
  9. <groupId>com.github.paulcwarren</groupId>
  10. <artifactId>spring-content-rest</artifactId>
  11. <version>0.1.0</version>
  12. </dependency>

配置

  1. @Configuration
  2. @EnableJpaStores
  3. @Import("org.springframework.content.rest.config.RestConfiguration.class")
  4. public class MysqlConfig {
  5. // schema management
  6. //
  7. @Value("/org/springframework/content/jpa/schema-drop-mysql.sql")
  8. private Resource dropRepositoryTables;
  9. @Value("/org/springframework/content/jpa/schema-mysql.sql")
  10. private Resource dataRepositorySchema;
  11. @Bean
  12. DataSourceInitializer datasourceInitializer() {
  13. ResourceDatabasePopulator databasePopulator =
  14. new ResourceDatabasePopulator();
  15. databasePopulator.addScript(dropReopsitoryTables);
  16. databasePopulator.addScript(dataReopsitorySchema);
  17. databasePopulator.setIgnoreFailedDrops(true);
  18. DataSourceInitializer initializer = new DataSourceInitializer();
  19. initializer.setDataSource(dataSource());
  20. initializer.setDatabasePopulator(databasePopulator);
  21. return initializer;
  22. }
  23. }

要关联内容,请向帐户实体添加spring内容注解。
帐户.java

  1. @Entity
  2. public class Account {
  3. // replace @Lob field with
  4. @ContentId
  5. private String contentId;
  6. @ContentLength
  7. private long contentLength = 0L;
  8. // if you have rest endpoints
  9. @MimeType
  10. private String mimeType = "text/plain";

创建“商店”:
accountimagesstore.java文件

  1. @StoreRestResource(path="accountImages)
  2. public interface AccountImagesStore extends ContentStore<Account, String> {
  3. }

这就是创建rest端点所需的全部@ /accountImages . 当您的应用程序启动时,spring内容将查看您的依赖项(查看spring内容jpa/rest),查看您的 AccountImagesStore 接口并为jpa注入该接口的实现。它还将注入 @Controller 将http请求转发给该实现。这就省得你自己去实现我认为你所追求的。
所以。。。 curl -X POST /accountImages/{account-id} 对于多部分/表单,数据请求将图像存储在数据库中,并将其与id为的帐户实体相关联 account-id . curl /accountImages/{account-id} 将再次获取它等等…支持完全积垢。
因此,您只需在jsp中显示一个图像标记:
这里有一些入门指南。参考指南在这里。这里有一个教程视频。编码位大约从1/2开始。
hth公司

展开查看全部
kknvjkwl

kknvjkwl3#

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

在负责将图像发送到html的控制器中:

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

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

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

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

展开查看全部

相关问题