首页新闻找找看学习计划

Java Web文件上传失败,不知哪儿出错了

0
悬赏园豆:15 [已解决问题] 解决于 2017-07-11 10:20
//数据库连接
public class DBConnection {
    String driver="com.mysql.jdbc.Driver";
    String url="jdbc:mysql://localhost:3306/myweb";
    Connection connection;
    Statement statement;
    ResultSet resultset;
    
    public DBConnection(){
        try{
            Class.forName(driver);
            connection=DriverManager.getConnection(url,"root","123456");
            statement=connection.createStatement();
            
        }catch(ClassNotFoundException |SQLException e){
            e.printStackTrace();
        }
    }
    
    public void openConnection(){
        try{
            Class.forName(driver);
            connection=DriverManager.getConnection(url,"root","123456");
            statement=connection.createStatement();
            System.out.println("数据库连接成功");
            
        }catch(ClassNotFoundException |SQLException e){
            e.printStackTrace();
            System.out.println("数据库连接失败");
        }
    }
    
    public void closeConnection(){
        if(statement!=null)
            try {
                statement.close();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        if(connection!=null)
            try {
                connection.close();
                System.out.println("数据库关闭成功");
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                System.out.println("数据库关闭失败");
            }
    }
    /*public static void main(String[] args) {
        new DBConnection().openConnection();
        new DBConnection().closeConnection();
    }*/
}
//数据库具体操作
public class BookOperate {

    private DBConnection dbConnection = new DBConnection();
    private Statement statement = dbConnection.statement;
    private ResultSet resultset;
    
    public void DataBaseOpenConnection(){
        dbConnection.openConnection();
    }
    
    
    /*插入书籍*/
    public int insertBook(String bookName,String bookIntroduce,String imgAddress){
        String insertSql="insert into bookinf (bookName,bookIntroduce,bookImage) values('"
                +bookName+"','"+bookIntroduce+"','"+imgAddress+"')";
        try{
            dbConnection.openConnection();
            int i=statement.executeUpdate(insertSql);
            //测试书籍信息添加
            if(i>0){
                System.out.println("书籍添加成功");
                
            }
                else {
                    System.out.println("书籍添加失败");
                }
            return i;
        }catch(SQLException e){
            e.printStackTrace();
            return -1;
        }
        
    }
    /*查询书籍*/
    public ResultSet selectBook(){
        String selectSql="select * from bookinf";
        try{        
            resultset=statement.executeQuery(selectSql);
            return resultset;
            
        }catch(SQLException e){
            e.printStackTrace();
            return null;
        }
    }
    
    public ResultSet selectBook(int bookId){
        String selectSql="select * from bookinf where bookId="+bookId;
        try{        
            resultset=statement.executeQuery(selectSql);
            return resultset;
            
        }catch(SQLException e){
            e.printStackTrace();
            return null;
        }
    }
    public ArrayList<BookInf> selectBooks(){
        ResultSet rs=this.selectBook();
        BookInf bookInf=new BookInf();
        ArrayList<BookInf> bookInfList=new ArrayList<BookInf>();
        try{
            while(rs.next()){

                bookInf.setBookName(rs.getString(1));
                bookInf.setBookIntroduce(rs.getString(2));
                bookInf.setBookImage(rs.getString(3));
                bookInfList.add(bookInf);
            }
            return bookInfList;
        }catch(SQLException e){
            e.printStackTrace();
        }
        return null;
    }
    
    public void DataBaseCloseConnection(){
        dbConnection.closeConnection();
    }
}
//Servlet
/**
 * Servlet implementation class BookServlet
 */
@WebServlet("/BookServlet")
public class BookServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public BookServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
     *      response)
     */
    protected void doGet(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        doPost(request, response);
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
     *      response)
     */
    protected void doPost(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        //图片上传后存储在服务器端的目录名称
        String savePath = this.getServletConfig().getServletContext()
                .getRealPath("/")
                + "uploads/";
        System.out.println(savePath);
        
        //MultipartReques类主要是对文件上传进行的处理,在上传文件时,编码格式为enctype="multipart/form-data"格式,以二进制形式提交数据,提交方式为post方式。
        //第一个参数为传过来的请求HttpServletRequest,
        //第二个参数为上传文件要存储在服务器端的目录名称
        //第三个参数是用来限制用户上传文件大小
        //第四个参数可以设定用何种编码方式来上传文件名称,可以解决中文问题
        MultipartRequest mul = new MultipartRequest(request, savePath,
                10 * 1024 * 1024, "gbk");
        request.setCharacterEncoding("gbk");

        String bookName = mul.getParameter("bookName");
        String bookIntroduce = mul.getParameter("bookIntroduce");
        String imgAddress = null;
        
        //Enumeration是java.util中的一个接口类,在Enumeration中封装了有关枚举数据集合的方法。
        //在Enumeration中提供了方法hasMoreElement()来判断集合中是否还有其它元素和方法nextElement()来获取下一个元素。利用这两个方法可以依次获得集合中元素。
        //传回所有文件输入类型的名称
        Enumeration files = mul.getFileNames();
        while (files.hasMoreElements()) {
            
            String fileName = (String) files.nextElement();
            //用此方法得到上传文件的真正的文件名,这里的fileName指文件输入类型的名称
            String filedName = mul.getFilesystemName(fileName);
            imgAddress = "uploads/" + filedName;// 存在数据库中的路径
            // imgAddress=fileName;

            System.out.println(fileName);
            System.out.println(filedName);

        }
        
        BookInf bookInf=new BookInf();
        bookInf.setBookName(bookName);
        bookInf.setBookIntroduce(bookIntroduce);
        bookInf.setBookImage(imgAddress);

        BookOperate bookOperate=new BookOperate();
    
        bookOperate.insertBook(bookName, bookIntroduce, imgAddress);
        ServletConfig config=getServletConfig();
        ServletContext context=config.getServletContext();
        RequestDispatcher dispatcher=context.getRequestDispatcher("/DisplayBook.jsp");
        dispatcher.forward(request,response);
    }

}
//界面AddBook.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>Add Book</title>
</head>
<body>
<form action="AddBook" name="BookForm" method="post" enctype="multipart/form-data">
<table align=center width=600 border=1>
    <tr>
        <th colspan=2>添加书籍</th>
    </tr>
    <tr>
        <td>书籍名称</td>
        <td><input type=text name=bookName size=90/></td>
    </tr>
    <tr>
        <td>书籍简介</td>
        <td><textarea rows="10" cols="72" name=bookIntroduce></textarea></td>
    </tr>
    <tr>
        <td>书籍图片</td>
        <td><input type=file name=bookImage/></td>
    <tr>
        <td align="center" colspan="2"><input type=submit value="提交"/></td>
    </tr>
</table>
</form>
</body>
</html>
//界面DisplayBooks
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8" import="java.util.*,java.sql.*"%>
    <jsp:useBean id="bookInf" class="com.myweb.database.BookOperate" scope="session"/>
<!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>Insert title here</title>
</head>
<body>
<%
        int bookId = Integer.parseInt(request.getParameter("bookId"));
        ResultSet rs=bookInf.selectBook(bookId);
        if(rs.next())
        {
            
%>
    <p align="center">
    <h1><%=rs.getString(2) %></h1>
    <font color="red"><%=rs.getString(3) %></font><br>
    <img src="<%=rs.getString(4)%>"/>
    </p>
<%
    } 
%>    
</body>
</html>
四月y的主页 四月y | 初学一级 | 园豆:142
提问于:2017-07-06 17:14
< >
分享
最佳答案
0

报错信息贴一下,

收获园豆:15
苍枫露雨 | 小虾三级 |园豆:1027 | 2017-07-06 17:25

HTTP Status 404 - /MyWeb/


type Status report

message /MyWeb/

description The requested resource is not available.

四月y | 园豆:142 (初学一级) | 2017-07-07 08:12

这里可以获取到savaPath

四月y | 园豆:142 (初学一级) | 2017-07-07 08:32

@四月y: 

在处理完成,跳转之前,添加一个输出,看是不是跳转出的问题。

ServletContext context=config.getServletContext();

//TODO: sout message

RequestDispatcher dispatcher=context.getRequestDispatcher("/DisplayBook.jsp"); dispatcher.forward(request,response);

苍枫露雨 | 园豆:1027 (小虾三级) | 2017-07-07 11:02

@苍枫露雨: 嗯嗯,可是我不明白的是,界面跳转不出来不能显示信息,应该不影响信息插入数据库,现在是文件插不进去数据库

四月y | 园豆:142 (初学一级) | 2017-07-07 11:21

@四月y:

数据库插入的语句是否已经执行了,执行了是否报错了,所以打印日志看下,

还有就是 后台是否报错,报什么错误, 最好给出打印的错误栈信息,

苍枫露雨 | 园豆:1027 (小虾三级) | 2017-07-07 14:06
其他回答(1)
0

看不懂,

BookServlet不加@MultipartConfig 吗?

form action="AddBook" 不应该是form action="BookServlet" 吗?

很多属性值不加引号?,如<input type=text name=bookName size=90/>

TCG2008 | 园豆:1145 (小虾三级) | 2017-07-06 18:56

跟这些都没有关系,弄了好几天,终于出来了

支持(0) 反对(0) 四月y | 园豆:142 (初学一级) | 2017-07-11 10:19
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册