使用JSP在Mysql中存储图像并在线上传图像

时间:2015-06-24 19:30:43

标签: java mysql jsp servlets

我仍然想知道我做错了什么,我的问题是我不知道是不是我的整个示例代码有na错误或我的数据库连接有问题,因为我站在哪里我不确定是什么让我得到这个错误。 (显示如下)。我试图在这里查看堆栈溢出,但我得到的是使用JSP加载图像但不将它们添加到数据库。如果我们有一个我无法追踪,请帮助我链接。我已经包含了所有需要的库,除了这个输出,我的代码没有错误。我来到这里是因为我陷入困境,需要简要回顾一下你的专业人士认为我的代码错误,如下所示。当我在截止日期前工作时,我将非常感谢任何帮助。 我的数据库名称是

  

AppDB   我想知道我应该使用桌子的名字吗? INSERT INTO?是的   '联系人'

     

错误消息

     
    

HTTP状态404 - / UploadImageOnWeb / uploadServlet类型状态报告             message / UploadImageOnWeb / uploadServlet description请求的             资源不可用。 Apache Tomcat / 8.0.23

  

谢谢

  

Java Servlet代码

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

/**
 * Servlet implementation class FileUploadDBServlet
 */
@MultipartConfig(maxFileSize = 16177215)
@WebServlet("/FileUploadDBServlet")
public class FileUploadDBServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    // database connection settings
    /*private String dbURL = "jdbc:mysql://localhost/AppDB";
    private String dbUser = "root";
    private String dbPass = "mypassword";*/

    protected void doPost(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {

        String firstName = request.getParameter("firstName");
        String lastName = request.getParameter("lastName");

        InputStream inputStream = null; 


        Part filePart = request.getPart("photo");
        if (filePart != null) {

            System.out.println(filePart.getName());
            System.out.println(filePart.getSize());
            System.out.println(filePart.getContentType());


            inputStream = filePart.getInputStream();
        }

        Connection conn = null;
        String message = null;  

        try {
            // connects to the database
            /*DriverManager.registerDriver("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection(dbURL, dbUser, dbPass);*/

           Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection("jdbc:mysql://localhost/AppDB","root","mypassword");




            // constructs SQL statement
            String sql = "INSERT INTO contacts (first_name, last_name, photo) values (?, ?, ?)";
            PreparedStatement statement = conn.prepareStatement(sql);
            statement.setString(1, firstName);
            statement.setString(2, lastName);

            if (inputStream != null) {
                // fetches input stream of the upload file for the blob column
                statement.setBlob(3, inputStream);
            }


            int row = statement.executeUpdate();
            if (row > 0) {
                message = "File uploaded and saved into database";
            }
        } catch (SQLException ex) {
            message = "ERROR: " + ex.getMessage();
            ex.printStackTrace();
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            if (conn != null) {
                // closes the database connection
                try {
                    conn.close();
                } catch (SQLException ex) {
                    ex.printStackTrace();
                }
            }
            // sets the message in request scope
            request.setAttribute("Message", message);

            // forwards to the message page
            getServletContext().getRequestDispatcher("/Message.jsp").forward(request, response);
        }
    }
}

我的.Jsp课程

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>File Upload to Database Demo</title>
</head>
<body>
    <center>
        <h1>File Upload to Database Demo</h1>
        <form method="post" action="uploadServlet" enctype="multipart/form-data">
            <table border="0">
                <tr>
                    <td>Enter First Name: </td>
                    <td><input type="text" name="firstName" size="20"/></td>
                </tr>
                <tr>
                    <td>Enter Last Name: </td>
                    <td><input type="text" name="lastName" size="20"/></td>
                </tr>
                <tr>
                    <td>Portrait Photo: </td>
                    <td><input type="file" name="photo" size="20"/></td>
                </tr>
                <tr>
                    <td colspan="2">
                        <input type="submit" value="Save">
                    </td>
                </tr>
            </table>
        </form>
    </center>
</body>
</html>

显示Jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
    "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Message</title>
</head>
<body>
    <center>
        <h3><%=request.getAttribute("Message")%></h3>
    </center>
</body>
</html>

1 个答案:

答案 0 :(得分:0)

404错误表明表单甚至没有到达servlet。

您在表单中将action属性定义为uploadServlet,这似乎不是您应用的有效网址。

servlet的URL在@WebServlet注释中定义为FileUploadDBServlet

因此,您可以通过更改表单中的操作或更改servlet的URL来解决此问题。