【发布时间】:2020-05-16 11:58:47
【问题描述】:
所以在我的课堂上,我被要求将图像上传到数据库,然后将它们取出并在网站上显示,这在使用 servlet 或 php 时非常简单,但我被要求仅使用 JSP 文件来完成。为此,我必须从用户那里获取图像并将其作为参数传递并获取参数的一部分,这不是问题。
当我尝试运行它并且服务器要求@multipartconfig 注释时,问题就开始了。我找不到将其添加到 jsp 代码中的方法。
这是jsp:
<%@page import="javax.servlet.annotation.MultipartConfig"%>
<%@page import="java.sql.*"%>
<%@page import="java.io.InputStream"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%
request.setCharacterEncoding("UTF-8");
Part p = request.getPart("image");
InputStream inputStream = null;
if (p != null) {
inputStream = p.getInputStream();
}
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/test42";
Class.forName(driver);
Connection con = DriverManager.getConnection(url, "root", "1234");
String sqlString = "INSERT INTO test42.images items(idimages) values(" + inputStream + ");";
String msg = p.toString();
%>
这是上传表单:
<form method="post" action="mainPage.jsp" enctype="multipart/form-data">
choose file :
<input type="file" name="image" />
<input type="submit" value="submit">
</form>
这是来自服务器的消息:
java.lang.IllegalStateException: Request.getPart is called without multipart configuration. Either add a @MultipartConfig to the servlet, or a multipart-config element to web.xml
我尝试将它添加到 web.xml,但它没有工作.... 该应用程序因构建错误而崩溃; 我从这里得到了这个解决方案: http://docs.oracle.com/javaee/6/tutorial/doc/gmhal.html
像这样:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
<multipart-config>
<location>/tmp</location>
<max-file-size>20848820</max-file-size>
<max-request-size>418018841</max-request-size>
<file-size-threshold>1048576</file-size-threshold>
</multipart-config>
</web-app>
【问题讨论】:
-
将代码放在 JSP 中的 scriptlet 中是不好的做法 - 将 Java 代码放在例如 servlet 或其他 Java 类中,而不是放在 JSP 中。