首页 新闻 赞助 找找看

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

0
悬赏园豆:15 [已解决问题] 解决于 2017-07-11 10:18
//数据库连接
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:03
< >
分享
最佳答案
0

看一下try  catch 中打印的错误信息啊,没打印任何错误就打断点慢慢调

收获园豆:8
青语 | 小虾三级 |园豆:1000 | 2017-07-06 17:08
其他回答(1)
0

感觉应该是有乱码引起的路径不正确问题

收获园豆:7
吉吉的城 | 园豆:566 (小虾三级) | 2017-07-08 16:27

可以详细说一下吗?我调试好几天了,要崩溃了

支持(0) 反对(0) 四月y | 园豆:142 (初学一级) | 2017-07-10 09:02

我运行整个web项目界面都出不来,一直报错,但是单独运行某一个界面,譬如登录界面、注册界面是可以运行出来的,还可以成功登录、注册

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