从网址栏中调用Servlet的get方法

时间:2019-04-09 06:28:40

标签: java url servlet-3.0

我正在尝试使用URL调用servlets类,但是没有被调用。

servlets类的init方法正在执行,但是没有get方法。 请在下面找到servlet类代码示例。

我想通过类似http://localhost:8090/myApp/downloadDoc?id=1的URL来调用servlet类

在检查网络中的请求时,它会给出302响应,例如Request

URL: http://localhost:8090/myApp/downloadDoc
Request Method: GET
Status Code: 302 
Remote Address: [::1]:8090
Referrer Policy: no-referrer-when-downgrade

@WebServlet("/downloadDoc") 
public class FileDownloadServlet extends HttpServlet{
    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    //@Inject
    private FileUploadService fileUploadService;

    public void init(ServletConfig config) throws ServletException{
        System.out.println("==================test============");
    }

    //@Override
     public void doGet(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException
                {
        System.out.println("==================do get============");
    String id = request.getParameter("id");

    // Find this file id in database to get file name, and file type
    FileDetails fileDetails = fileUploadService.findFileById(Integer.parseInt(id));

    ServletOutputStream out = response.getOutputStream();
    ServletContext context = getServletConfig().
            getServletContext();
   // String mimetype = context.getMimeType(fileDetails.getFilePath());

    if(fileDetails!= null) {

        // You must tell the browser the file type you are going to send
        // for example application/pdf, text/plain, text/html, image/jpg
        response.setContentType(fileDetails.getFileType());
        // Make sure to show the download dialog
        response.setHeader("Content-disposition","attachment; filename=\""+fileDetails.getFileName()+"\"");

        // Assume file name is retrieved from database
        // For example D:\\file\\test.pdf

        File my_file = new File(fileDetails.getFilePath());

        // This should send the file to browser
      //  OutputStream out = response.getOutputStream();
        FileInputStream in = new FileInputStream(my_file);
        byte[] buffer = new byte[4096];
        int length;
        while ((length = in.read(buffer)) > 0){
           out.write(buffer, 0, length);
        }
        in.close();
        out.flush();
    }
    }
   // @Override
    public void service(ServletRequest req, ServletResponse resp) throws ServletException, IOException {
        System.out.println("====================service");

    }

    //@Override
    public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("======================doPost");
    }

   // @Override
    public void destroy() {
        System.out.println("==================Destroy servlet");
    }

    }

0 个答案:

没有答案