- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我目前正在使用 Java EE 创建一个网站,使用 maven、thymeleaf,并将其托管在 heroku 上(数据库插件是 JawsDBMySQL)。我创建了一个简单的 html 页面以检查它是否正常工作。当然,它非常适合本地上传:文件会转到我设计的文件夹。
在我的数据库中,本地存储的路径存储为字符串。我还添加了一个 longblob 列,但我并没有真正理解如何使用它。
现在我想在我的应用程序在线时将文件存储到我的数据库中。
我没有找到与我的问题完美匹配的解决方案,但我很确定它非常简单。
希望我已经足够清楚了,
感谢您的帮助。
在/home2 上显示带有图片列表的页面的 Servlet
package marquise.servlets;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.WebContext;
import marquise.services.InformationLibrary;
@WebServlet("/home2")
public class HomeServlet extends AbstractGenericServlet2 {
private static final long serialVersionUID = 5402133218271984030L;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
TemplateEngine templateEngine = this.createTemplateEngine(req);
WebContext context = new WebContext(req, resp, getServletContext());
//Country countryFilter = (Country) req.getSession().getAttribute("countryFilter");
context.setVariable("images", InformationLibrary.getInstance().listAllImages());
//context.setVariable("cities", CityService.getInstance().listAllCities(countryFilter));
//context.setVariable("countries", Country.values());
//context.setVariable("countryFilterSelected", countryFilter);
templateEngine.process("home", context, resp.getWriter());
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String countryString = req.getParameter("countryFilter");
resp.sendRedirect("home2");
}
}
路径的Servlet
@WebServlet("/imagepicture")
public class CityPictureServlet extends AbstractGenericServlet2 {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Integer imageId = Integer.parseInt(req.getParameter("id"));
Path picturePath = InformationLibrary.getInstance().getPicturePatch(imageId);
Files.copy(picturePath, resp.getOutputStream());
}
}
打印图像细节的 servlet(现在不重要) 包 marquise.servlets;
@WebServlet("/detail")
public class CityDetailServlet extends AbstractGenericServlet2 {
private static final long serialVersionUID = 8559083626521311046L;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
TemplateEngine templateEngine = this.createTemplateEngine(req);
WebContext context = new WebContext(req, resp, getServletContext());
Integer idImage = Integer.parseInt(req.getParameter("id"));
context.setVariable("image", InformationLibrary.getInstance().getImage(idImage));
//context.setVariable("comments", InformationLibrary.getInstance().listCommentsByCity(idCity));
context.setVariable("comments", InformationLibrary.getInstance().listAllImages());
templateEngine.process("imagedetail", context, resp.getWriter());
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Integer cityId = Integer.parseInt(req.getParameter("id"));
resp.sendRedirect(String.format("detail?id=%d", cityId));
resp.sendRedirect("home2");
}
}
显示我的图片列表的 HTML 页面
<!doctype html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="utf-8">
<title>City Explorer</title>
<link rel="stylesheet" href="bootstrap/bootstrap.min.css">
<link rel="stylesheet" href="fontawesome/css/font-awesome.min.css">
<link rel="stylesheet" href="css/custom.css">
</head>
<body>
<header th:replace="~{common::header}"></header>
<div id="mainContent" class="container-fluid">
<section class="cityfilters">
<h3>Filters</h3>
<form class="form-inline" method="post">
<div class="form-group">
<label for="countryInput">Country</label>
<select class="form-control" id="countryInput" name="countryFilter">
<option value="">All countries</option>
<option th:each="country : ${countries}" th:value="${country}" th:selected="${countryFilterSelected} == ${country}">[[${country.label}]]</option>
</select>
</div>
<input type="submit" class="btn btn-default" value="Filter">
</form>
</section>
<section class="citylist">
<article class="citybox" th:each="image : ${images}">
<h3>
[[${image.name}]]
<a th:href="'deleteimage?id='+${image.id}" class="btn btn-xs btn-danger pull-right">
<i class="fa fa-times" aria-hidden="true"></i>
</a>
</h3>
<p th:text="${image.summary}" class="summary"></p>
<div class="btn-toolbar actionbar" role="toolbar">
<div class="btn-group" role="group">
<a th:href="'detail?id='+${image.id}" class="btn btn-primary"><i
class="fa fa-eye" aria-hidden="true"></i> See details</a>
</div>
</div>
<aside class="cityPhoto">
<img th:src="'imagepicture?id='+${image.id}" th:alt="'Vignette '+${image.name}">
</aside>
</article>
</section>
</div>
</body>
</html>
我的图书馆类和我电脑的路径
public class InformationLibrary {
private static class InformationLibraryHolder{
private final static InformationLibrary instance = new InformationLibrary();
}
public static InformationLibrary getInstance(){
return InformationLibraryHolder.instance;
}
private InformationDao informationDao = new InformationDaoImpl();
private UtilisateurDao utilisateurDao = new UtilisateurDaoImpl();
private CommentaireDao commentaireDao = new CommentaireDaoImpl();
private ArticleDao articleDao = new ArticleDaoImpl();
private IdentifiantDao identifiantDao = new IdentifiantDaoImpl();
private ImageDao imageDao = new ImageDao();
private static final String PICTURE_MAIN_DIRECTORY = "/Users/louiscauvray/git/projet/src/main/resources";
private ElementsSiteDao elementsSiteDao = new ElementsSiteDao();
private InformationLibrary() {
}
//Recuperer les informations sur les utilisateurs
public List<Information> listFilms() {
return informationDao.listInformations();
}
public Information getInformation(Integer id) {
return informationDao.getInformation(id);
}
public Information addInformation(Information information) {
return informationDao.addInformation(information);
}
public List<Utilisateur> listUtilisateurs() {
return utilisateurDao.listUtilisateurs();
}
public Utilisateur getUtilisateur(Integer id) {
return utilisateurDao.getUtilisateur(id);
}
public Utilisateur getUtilisateurByNom(String nom){
return utilisateurDao.getUtilisateurByNom(nom);
}
public Utilisateur addUtilisateur(String nom, String prenom) {
return utilisateurDao.addUtilisateur(nom, prenom);
}
//Gerer les commentaires visible en backoffice
public List<Commentaire> listCommentaires(){
return commentaireDao.listCommentaires();
}
public Commentaire addCommentaire(String email ,String commentaire){
return commentaireDao.addCommentaire(email, commentaire);
}
public List<Article> listArticles(){
return articleDao.listArticles();
}
public Article addArticle(String title, String texte, LocalDate datePublication, String auteur) {
return articleDao.addArticle(title, texte, datePublication, auteur);
}
public Identifiant getIdentifiant(String login, String motDePasse){
return identifiantDao.getIdentifiant(login, motDePasse);
}
//Methode pour appeler les image et les chemins des images
public List<Image> listAllImages() {
return imageDao.listImages();
}
public Image getImage(Integer id) {
if(id == null) {
throw new IllegalArgumentException("Image id must be provided.");
}
return imageDao.getImage(id);
}
public void addImage(Image newImage, Part picture) throws IOException {
if(newImage == null){
throw new IllegalArgumentException("An image must be provided.");
}
if(newImage.getName() == null || "".equals(newImage.getName())) {
throw new IllegalArgumentException("An image must have a name.");
}
if(newImage.getSummary() == null || "".equals(newImage.getSummary())) {
throw new IllegalArgumentException("An image must have a summary.");
}
if(picture == null){
throw new IllegalArgumentException("An image must contain a picture.");
}
Path picturePath = Paths.get(PICTURE_MAIN_DIRECTORY, picture.getSubmittedFileName());
imageDao.addImage(newImage, picturePath.toString());
Files.copy(picture.getInputStream(), picturePath);
}
public Path getPicturePatch(Integer imageId) {
String picturePathString = imageDao.getPicturePath(imageId);
if(picturePathString == null) {
return getDefaultPicturePath();
} else {
Path picturePath = Paths.get(imageDao.getPicturePath(imageId));
if(Files.exists(picturePath)) {
return picturePath;
} else {
return getDefaultPicturePath();
}
}
}
private Path getDefaultPicturePath() {
try {
return Paths.get(this.getClass().getClassLoader().getResource("city-no-photo.png").toURI());
} catch (URISyntaxException e) {
return null;
}
}
// ElementsSite Dao
public void modifierElementTexte(String idElement, String contenuElement) {
elementsSiteDao.modifierElementTexte(idElement, contenuElement);
}
public void modifierElementImage(String idElement, String contenuElement, String cheminElement) {
elementsSiteDao.modifierElementImage(idElement, contenuElement, cheminElement);
}
public ElementsSite getElementById(String id) {
return elementsSiteDao.getElementById(id) ;
}
}
我的 Dao 类,其中定义了显示图像的方法
import marquise.daos.impl.DataSourceProvider;
import marquise.exceptions.CityExplorerRuntimeException;
import marquise.projos.Image;
public class ImageDao {
public List<Image> listImages() {
List<Image> images = new ArrayList<Image>();
try (Connection connection = DataSourceProvider.getInstance().getDataSource().getConnection();
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery("SELECT * FROM image ORDER BY name")) {
while (resultSet.next()) {
images.add(
new Image(resultSet.getInt("id"), resultSet.getString("name"), resultSet.getString("summary")));
}
} catch (SQLException e) {
throw new CityExplorerRuntimeException("Error when getting images", e);
}
return images;
}
public Image getImage(Integer id) {
try (Connection connection = DataSourceProvider.getInstance().getDataSource().getConnection();
PreparedStatement statement = connection.prepareStatement("SELECT * FROM image WHERE id = ?")) {
statement.setInt(1, id);
try (ResultSet resultSet = statement.executeQuery()) {
if (resultSet.next()) {
return new Image(resultSet.getInt("id"), resultSet.getString("name"), resultSet.getString("summary"));
}
}
} catch (SQLException e) {
throw new CityExplorerRuntimeException("Error when getting images", e);
}
return null;
}
public void addImage(Image newImage, String picturePath) {
try (Connection connection = DataSourceProvider.getInstance().getDataSource().getConnection();
PreparedStatement statement = connection.prepareStatement("INSERT INTO image(name, summary, picture) VALUES (?, ?, ?)")) {
statement.setString(1, newImage.getName());
statement.setString(2, newImage.getSummary());
statement.setString(3, picturePath);
statement.executeUpdate();
} catch (SQLException e) {
throw new CityExplorerRuntimeException("Error when getting images", e);
}
}
public String getPicturePath(Integer id) {
try (Connection connection = DataSourceProvider.getInstance().getDataSource().getConnection();
PreparedStatement statement = connection.prepareStatement("SELECT picture FROM image WHERE id = ?")) {
statement.setInt(1, id);
try (ResultSet resultSet = statement.executeQuery()) {
if (resultSet.next()) {
return resultSet.getString("picture");
}
}
} catch (SQLException e) {
throw new CityExplorerRuntimeException("Error when getting images", e);
}
return null;
}
}
最佳答案
终于找到了解决问题的方法:
我在我的数据库表中添加了一个 longblob 列,并稍微改变了我的方法。
如果你需要的话,这是我的最终代码:
道类:
package marquise.daos;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import marquise.daos.impl.DataSourceProvider;
import marquise.exceptions.CityExplorerRuntimeException;
import marquise.projos.Image;
public class ImageDao {
public List<Image> listImages() {
List<Image> images = new ArrayList<Image>();
try (Connection connection = DataSourceProvider.getInstance().getDataSource().getConnection();
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery("SELECT * FROM image ORDER BY name")) {
while (resultSet.next()) {
images.add(
new Image(resultSet.getInt("id"), resultSet.getString("name"), resultSet.getString("summary")));
}
} catch (SQLException e) {
throw new CityExplorerRuntimeException("Error when getting images", e);
}
return images;
}
public Image getImage(Integer id) {
try (Connection connection = DataSourceProvider.getInstance().getDataSource().getConnection();
PreparedStatement statement = connection.prepareStatement("SELECT * FROM image WHERE id = ?")) {
statement.setInt(1, id);
try (ResultSet resultSet = statement.executeQuery()) {
if (resultSet.next()) {
return new Image(resultSet.getInt("id"), resultSet.getString("name"), resultSet.getString("summary"));
}
}
} catch (SQLException e) {
throw new CityExplorerRuntimeException("Error when getting images", e);
}
return null;
}
public void addImage(Image newImage, String picturePath) {
try (Connection connection = DataSourceProvider.getInstance().getDataSource().getConnection();
PreparedStatement statement = connection.prepareStatement("INSERT INTO image(name, summary, picture) VALUES (?, ?, ?)")) {
statement.setString(1, newImage.getName());
statement.setString(2, newImage.getSummary());
statement.setString(3, picturePath);
statement.executeUpdate();
} catch (SQLException e) {
throw new CityExplorerRuntimeException("Error when getting images", e);
}
}
public void addImage(Image img, InputStream is){
try(Connection connection = DataSourceProvider.getInstance().getDataSource().getConnection();
PreparedStatement statement = connection.prepareStatement("INSERT INTO image(name, summary, image) VALUES (?, ?, ?)")) {
statement.setString(1, img.getName());
statement.setString(2, img.getSummary());
statement.setBinaryStream(3, is);
statement.executeUpdate();
} catch (SQLException e) {
throw new CityExplorerRuntimeException("Error when getting images", e);
}
}
public String getPicturePath(Integer id) {
try (Connection connection = DataSourceProvider.getInstance().getDataSource().getConnection();
PreparedStatement statement = connection.prepareStatement("SELECT picture FROM image WHERE id = ?")) {
statement.setInt(1, id);
try (ResultSet resultSet = statement.executeQuery()) {
if (resultSet.next()) {
return resultSet.getString("picture");
}
}
} catch (SQLException e) {
throw new CityExplorerRuntimeException("Error when getting images", e);
}
return null;
}
public InputStream getPicture(Integer id) {
try (Connection connection = DataSourceProvider.getInstance().getDataSource().getConnection();
PreparedStatement statement = connection.prepareStatement("SELECT image FROM image WHERE id = ?")) {
statement.setInt(1, id);
try (ResultSet resultSet = statement.executeQuery()) {
if (resultSet.next()) {
return resultSet.getBinaryStream("image");
}
}
} catch (SQLException e) {
throw new CityExplorerRuntimeException("Error when getting images", e);
}
return null;
}
/*public InputStream getPicture(Integer id) {
try (Connection connection = DataSourceProvider.getInstance().getDataSource().getConnection();
PreparedStatement statement = connection.prepareStatement("SELECT image FROM image WHERE id = ?")) {
statement.setInt(1, id);
try (ResultSet resultSet = statement.executeQuery()) {
if (resultSet.next()) {
return resultSet.getBlob("image") == null ? null : resultSet.getBlob("image").getBinaryStream();
}
}
} catch (SQLException e) {
throw new CityExplorerRuntimeException("Error when getting images", e);
}
return null;
}*/
}
添加图像 servlet:
package marquise.servlets;
import java.io.IOException;
import java.io.InputStream;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.WebContext;
import marquise.projos.Image;
import marquise.services.InformationLibrary;
@WebServlet("/addimage")
@MultipartConfig
public class ImageAddServlet extends AbstractGenericServlet2 {
private static final long serialVersionUID = -3497793006266174453L;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setCharacterEncoding("UTF-8");
TemplateEngine templateEngine = this.createTemplateEngine(req);
WebContext context = new WebContext(req, resp, getServletContext());
if(req.getSession().getAttribute("imageCreationError") != null) {
context.setVariable("errorMessage", req.getSession().getAttribute("imageCreationError"));
context.setVariable("image", (Image) req.getSession().getAttribute("imageCreationData"));
req.getSession().removeAttribute("imageCreationError");
req.getSession().removeAttribute("imageCreationData");
} else {
context.setVariable("image", new Image(null, null, null));
}
context.setVariable("countries", context);
templateEngine.process("connectedUsers/imageadd", context, resp.getWriter());
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String name = req.getParameter("name");
String summary = req.getParameter("summary");
Part imagePicture = req.getPart("picture");
Image newImage = new Image(null, name, summary);
InputStream is = imagePicture.getInputStream();
try {
InformationLibrary.getInstance().addImage(newImage, is);
resp.sendRedirect("certificatsAdmin");
} catch (IllegalArgumentException|IOException e) {
req.getSession().setAttribute("imageCreationError", e.getMessage());
req.getSession().setAttribute("imageCreationData", newImage);
resp.sendRedirect("addimage");
}
}
}
列表图像 servlet:
package marquise.servlets;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.WebContext;
import marquise.services.InformationLibrary;
@WebServlet("/certificatsAdmin")
public class listeCertifServlet extends AbstractGenericServlet2 {
private static final long serialVersionUID = 5402133218271984030L;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setCharacterEncoding("UTF-8");
PrintWriter out = resp.getWriter();
HttpSession session=req.getSession(false);
if(session != null){}
else{
resp.sendRedirect("connexion");
out.println("Veuillez entre un mot de passe correct");
}
TemplateEngine templateEngine = this.createTemplateEngine(req);
WebContext context = new WebContext(req, resp, getServletContext());
//Country countryFilter = (Country) req.getSession().getAttribute("countryFilter");
context.setVariable("images", InformationLibrary.getInstance().listAllImages());
//context.setVariable("cities", CityService.getInstance().listAllCities(countryFilter));
//context.setVariable("countries", Country.values());
//context.setVariable("countryFilterSelected", countryFilter);
templateEngine.process("admin/certificatsAdmin", context, resp.getWriter());
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String countryString = req.getParameter("countryFilter");
resp.sendRedirect("certificatsAdmin");
}
}
关于mysql - jee maven项目的数据库路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43908518/
我试图理解 Maven 模块和 Maven 项目之间的区别。哪一个是什么以及我应该在哪里?谢谢 最佳答案 maven 模块就像一个 maven“子项目”。一个 Maven 项目包含 1 个或多个模块。
我们目前没有自己的存储库。因此,当我们使用 Maven 构建时,它会在当前用户的主目录中创建 .m2 存储库。 现在有两个在 Maven Central 中找不到的第三方 jar。假设其中之一是 ha
我有 Maven 项目,但在其中一台服务器上我必须在没有 Maven 的情况下构建它。 可以使用标准 JDK 命令。在哪里可以看到 Maven 在构建项目时向 JDK 发送了哪些命令? 最佳答案 Ma
我打算将 ImageJ 用于 web 应用程序,但似乎 ImageJ maven 依赖项不在中央 maven 存储库中。 我说得对吗? 当 ImageJ 2.x 发布时,这会改变吗? 最佳答案 您可以
我可以有多个 Maven 实例吗,即 Mave 2.2.1 和 Maven 3 都指向同一个本地存储库? 我的意思是我知道我可以在技术上将每个 settings.xml 指向同一个文件夹,但从长远来看
我有两个项目,项目 A 依赖于项目 B,所以通常,我的 projectA/pom.xml 中有以下部分: projectB blabla version1 我想要实现的目标非常简
在网上的许多地方,我看到它讨论了要使 maven 构建可重现,明确指定所有使用的插件的版本号很重要,这样更新的插件就不会破坏构建。推荐的方法似乎是使用 enforcer 插件。下面是我在网上找到的复制
有没有办法暂停 Maven 执行流程以提供命令提示符,以便用户可以输入文本。 然后我希望将提供的文本存储在 Maven 属性中。 如果用户输入可以被屏蔽,那将是一个奖励。 这对于避免在 pom.xml
我正在尝试使用 maven 插件将 maven java 项目的源文件夹添加到 Eclipse。 尝试使用 org.codehaus.mojo 插件时,我收到以下错误 无法在项目应用程序框架上执行目标
我有两个几乎相同的配置文件。我不想在每个配置文件中复制配置,而是希望一个配置文件从另一个配置文件“继承”,但我没有看到使用 maven 3 执行此操作的明显方法。 在 Maven 中是否可以继承配置文
我是 Maven 新手,花了大约 3 天的时间使用程序集插件生成 zip 文件,引用 http://www.petrikainulainen.net/programming/tips-and-tric
想象一下这种情况。我有一个使用 Maven 管理的开源项目,它依赖于一个不在 Maven 存储库中的知名库(例如 jpathwatch)。我怎样才能让它发挥作用? 直接的方法是将 jpathwatch
我将 Neo4j 和 MongoDB 与 Grails 一起使用,我想知道 Maven Neo4j 插件是否也为我的构建提供了 Neo4j 依赖项。 MongoDB 也是如此。 我很困惑。我应该使用什
我正在尝试同时发布多个 Maven 项目,将它们部署到 oss.sonatype.org,然后将它们发布到 Maven Central。 我有一个构建 pom,用于一起构建多个多模块项目。构建 pom
我有一个带有 maven pom.xml 的项目 4.0.0 Minimal-J Minimal-J 0.1-SNAPSHOT Minimal-J
我需要制作一个下载maven项目并打印其依赖项的小程序 像这样: MavenArtifactRepository repository = new MavenArtifactRepository("t
我有一个关于 maven 在构建过程中如何计算类路径的问题。具体来说,控制何时使用“目标/类”以及何时使用来自存储库(本地/远程)的“jar”。 我有一个版本为 1.0.0-SNAPSHOT 的项目,
我有一个 maven 项目,需要在命令行(-Dmy.property=val)设置一个属性。 我需要做的是将该字符串转换为所有大写,因为该属性是 用于通过 maven-resources-plugin
引用和转义如何对传递给 Maven 插件的参数起作用? 例如,我想将多个文件名作为参数传递给 Maven Exec 插件运行的应用程序: mvnDebug exec:java -Dexec.mainC
我在父 pom 的导入的 dependencyManagement 部分中指定了一个库版本。我确认我的有效 pom 只有一次出现这种依赖。它在依赖管理部分: org.jav
我是一名优秀的程序员,十分优秀!