欢迎光临散文网 会员登陆 & 注册

Java Web,servlet,附件下载,学习笔记,记录,解决服务器启动不了问题【诗书画唱】

2020-10-13 21:04 作者:诗书画唱  | 我要投稿

个人解决服务器启动不了的问题的方法






本地的拷贝

在同一台电脑上进行的操作。例如将一个文件从d盘拷贝到c盘。


一、附件上传


在两台电脑之间进行的拷贝,或者通过网页的方式进行的文件的拷贝


附件上传的步骤:

1、导包(附件上传的包有很多种,我们今天使用的是这些包中的一种)

2、创建附件上传的jsp页面

3、创建附件上传的servlet

在附件上传中,除了type="file"的input标签以外,其他的input的isFormField都是true

 


地址:http://192.168.43.208:8888/j1908021/index.jsp

 


有时要实现的操作:

一、上传图片后显示图片



二、附件下载


将需要下载的文件放到服务器上,然后客户端就可以通过访问网页来下载响应的文件。


1、将需要下载的文件放到服务器上去

2、导包(附件上传的包一样)

3、创建附件下载的jsp页面download.jsp

4、创建一个servlet实现附件下载功能


作业 



1、实现一个附件上传程序,为了避免上传的文件名重复,请在上传以后,给上传的文件名添加一个时间戳。

例如:上传的文件名叫2.png,为了避免跟其他人的文件名相同,将文件名改为2_2020-08-05-15-35-13-876.png进行保存


自己想出关键 



再运行后:





2、将一些文件拷贝到服务器上,将这些文件名保存在一个数据库表中,要求打开一个download.jsp页面,要能够显示数据库表中的下载链接,要求能够下载这些文件。

fileinfo:id,filename






create table fileinfo(

id int primary key auto_increment,



filename varchar(100) 



);


insert into fileinfo(filename) values ("20201012.txt"),('20201013.txt' );


--select * from fileinfo


--drop  table fileinfo


自己想出的好方法:


package bean;


public class Fileinfo {

private Integer id;

private String filename;

public Integer getId() {

return id;

}

public void setId(Integer id) {

this.id = id;

}

public String getFilename() {

return filename;

}

public void setFilename(String filename) {

this.filename = filename;

}

}


package com.SSHC.controller;


import java.io.IOException;

import java.io.InputStream;

import java.io.OutputStream;

import java.util.List;


import javax.servlet.ServletException;

import javax.servlet.annotation.WebServlet;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;


/**

 * Servlet implementation class DownloadServlet

 */

@WebServlet("/ds")

public class DownloadServlet extends HttpServlet {

private static final long serialVersionUID = 1L;

       

    /**

     * @see HttpServlet#HttpServlet()

     */

    public DownloadServlet() {

        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

this.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

//设置响应的字符集编码

response.setCharacterEncoding("utf-8");

response.setContentType("text/html;charset=utf-8");

//获取需要下载的附件的名字

String fileName = request.getParameter("fileName");

System.out.println("需要下载的附件名是:" + fileName);

//获取附件在服务器上的路径

String folder = "/doc/";

//通知浏览器以下载的形式打开一个界面

response.addHeader("Content-type", "appllication/octet-stream");

response.addHeader("Content-Disposition", "attachment;filename=" 

+ fileName);

//读取服务器上的文件

InputStream is = this.getServletContext()

.getResourceAsStream(folder + fileName);

//将流写到客户端去

OutputStream os = response.getOutputStream();

//每次缓存1024字节

byte[]buf = new byte[1024];

//每次读取的字节长度

int len = 0;

while((len = is.read(buf)) != -1) {

os.write(buf,0,len);

}

//清理资源

os.close();

is.close();

}


}

package com.SSHC.controller;


import java.io.IOException;

import java.util.List;


import javax.servlet.ServletException;

import javax.servlet.annotation.WebServlet;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;


import bean.Fileinfo;

import DAO.Dao;


/**

 * Servlet implementation class ELServlet

 */

@WebServlet("/ELServlet")

public class ELDownloadServlet extends HttpServlet {

private static final long serialVersionUID = 1L;

       

    /**

     * @see HttpServlet#HttpServlet()

     */

    public ELDownloadServlet() {

        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

this.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

Dao gd = new Dao();

List<Fileinfo>list = gd.selectAll();


StringBuilder html = new StringBuilder();

html.append("<h1>诗书画唱提醒你!</h1>"

+ "<br>点击链接后可以下载对应的文件哦!");

for(Fileinfo g : list) {


Integer ID= g.getId();

String filename=g.getFilename();

System.out.println(filename);


html.append(" <ul><li><a href='ds?fileName="+filename

+"'>下载"+filename+"</a></li> </ul>");

}


request.setAttribute("html", html);


System.out.println(html);

request.getRequestDispatcher("SSHCdownload.jsp")

    .forward(request, response);

}


}






package DAO;

import java.sql.Connection;

import java.sql.PreparedStatement;

import java.sql.ResultSet;

import java.sql.SQLException;

import java.util.ArrayList;

import java.util.List;


import Utils.DBUtils;


import bean.Fileinfo;




public class Dao {



public List<Fileinfo>selectAll(){


String sql = "select * from fileinfo";


Connection conn = null;


PreparedStatement pstm = null;


ResultSet rs = null;


List<Fileinfo>list = new ArrayList<Fileinfo>();


try {


conn = DBUtils.getConn();


pstm = conn.prepareStatement(sql);


rs = pstm.executeQuery();


while(rs.next()) {


Integer id = rs.getInt("id");


String Filename= rs.getString("filename");



Fileinfo edu = new Fileinfo();


edu.setId(id);


edu.setFilename(Filename);



list.add(edu);


}


} catch (SQLException e) {


// TODO Auto-generated catch block


e.printStackTrace();


}


return list;


}




}

package Utils;


import java.io.IOException;

import java.io.InputStream;

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.PreparedStatement;

import java.sql.ResultSet;

import java.util.Properties;


public class DBUtils {

private static String driverName;

    private static String url;

    private static String user;

    private static String pwd;

    

    static {

    //读取properties文件

    Properties prop = new Properties();

    //将db.properties文件读取到内存中去

    InputStream is = DBUtils.class.getClassLoader()

    .getResourceAsStream("db.properties");

    //加载内容

    try {

prop.load(is);

//读取内容

driverName = prop.getProperty("dn");

//System.out.println(driverName);

url = prop.getProperty("url");

user = prop.getProperty("un");

pwd = prop.getProperty("up");

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

    }

    

    //获取数据库连接对象的方法

    public static Connection getConn(){

    Connection conn = null;

    try {

Class.forName(driverName);

conn = DriverManager

.getConnection(url,user,pwd);

} catch (Exception e) {

// TODO Auto-generated catch block

e.printStackTrace();

}   

    return conn;

    }

    

    public static void close(ResultSet

    rs,PreparedStatement pstm

    ,Connection conn){

        try {

        if(rs != null) {

            rs.close();

            }

            if(pstm != null) {

            pstm.close();

            }

            if(conn != null) {

            conn.close();

            }

        } catch(Exception e) {

        e.printStackTrace();

        }

    }

}

dn=com.mysql.jdbc.Driver

url=jdbc:mysql://localhost:3306/firstjsp?useUnicode=true&characterEncoding=UTF-8

un=root

up=root

<%@ page language="java" contentType="text/html; charset=UTF-8" 

pageEncoding="UTF-8"%>

<%

    String path = request.getContextPath();

    String basePath = request.getScheme()+"://"+

    request.getServerName()+":"+request.getServerPort()+path+"/";

%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>

    <head>

        <base hreff="<%=basePath%>">

        <title></title>

        <meta http-equiv="pragma" content="no-cache">

        <meta http-equiv="cache-control" content="no-cache">

        <meta http-equiv="expires" content="0">

        <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">

        <meta http-equiv="description" content="This is my page">

        <style type="text/css">

            * {

                font-size: 50px;

            }

        </style>

    </head>

    <body>

      ${html }

    </body>

</html>



————————————————————————————


附件下载的例子:


package com.jy.controller;


import java.io.IOException;

import java.io.InputStream;

import java.io.OutputStream;


import javax.servlet.ServletException;

import javax.servlet.annotation.WebServlet;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;


/**

 * Servlet implementation class DownloadServlet

 */

@WebServlet("/ds")

public class DownloadServlet extends HttpServlet {

private static final long serialVersionUID = 1L;

       

    /**

     * @see HttpServlet#HttpServlet()

     */

    public DownloadServlet() {

        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

this.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

//设置响应的字符集编码

response.setCharacterEncoding("utf-8");

response.setContentType("text/html;charset=utf-8");

//获取需要下载的附件的名字

String fileName = request.getParameter("fileName");

System.out.println("需要下载的附件名是:" + fileName);

//获取附件在服务器上的路径

String folder = "/doc/";

//通知浏览器以下载的形式打开一个界面

response.addHeader("Content-type", "appllication/octet-stream");

response.addHeader("Content-Disposition", "attachment;filename=" 

+ fileName);

//读取服务器上的文件

InputStream is = this.getServletContext()

.getResourceAsStream(folder + fileName);

//将流写到客户端去

OutputStream os = response.getOutputStream();

//每次缓存1024字节

byte[]buf = new byte[1024];

//每次读取的字节长度

int len = 0;

while((len = is.read(buf)) != -1) {

os.write(buf,0,len);

}

//清理资源

os.close();

is.close();

}


}


1、实现附件上传功能。尝试对上传文件的类型进行限制,只能传图片(png,jpg)文件。

2、在两台电脑之间进行附件上传的操作。

3、学会使用cmd命令:ipconfig查看服务器的ip地址,ping检查跟指定的ip地址的电脑是否连接在同一个网内的

ping 192.168.42.133就是检查你的电脑跟这个ip地址的电脑是否连接在一起了。


abc.txt.png

1、实现一个附件上传程序,为了避免上传的文件名重复,请在上传以后,给上传的文件名添加一个时间戳。

例如:上传的文件名叫2.png,为了避免跟其他人的文件名相同,将文件名改为2_2020-08-05-15-35-13-876.png进行保存




2、将一些文件拷贝到服务器上,将这些文件名保存在一个数据库表中,要求打开一个download.jsp页面,要能够显示数据库表中的下载链接,要求能够下载这些文件。

fileinfo:id,filename

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>

<%

    String path = request.getContextPath();

    String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";

%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>

    <head>

        <base hreff="<%=basePath%>">

        <title></title>

        <meta http-equiv="pragma" content="no-cache">

        <meta http-equiv="cache-control" content="no-cache">

        <meta http-equiv="expires" content="0">

        <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">

        <meta http-equiv="description" content="This is my page">

        <style type="text/css">

            * {

                font-size: 50px;

            }

        </style>

    </head>

    <body>

        <ul>

        

            <li><a href="ds?fileName=20201012.txt">20201012作业</a></li>

            <li><a href="ds?fileName=20201013.txt">20201013作业</a></li>

        </ul>

    </body>

</html>





Java Web,servlet,附件下载,学习笔记,记录,解决服务器启动不了问题【诗书画唱】的评论 (共 条)

分享到微博请遵守国家法律