Java Servlet

tech2023-02-19  104

每个访问的web.xml配置

<servlet> <servlet-name>helloSeerlet</servlet-name> <servlet-class>com.servlet.HelloServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>helloSeerlet</servlet-name> <url-pattern>/hello</url-pattern> </servlet-mapping>

输出消息

@Override protected void doGet(HttpServletRequest req, HttpServletResponse response) throws ServletException, IOException { ServletContext servletContext = this.getServletContext(); response.setCharacterEncoding("UTF-8"); //响应的类型:html response.setContentType("text/html"); String name = "zzh"; System.out.println("zzh"); servletContext.setAttribute("name",name); }

get文件传输

@Override protected void doGet(HttpServletRequest req, HttpServletResponse response) throws ServletException, IOException { //1.获取下载文件的位置 String realPath = "E:\\IntelliJ IDEA 2019.3.3\\project\\javaweb\\Javaweb-01-maven\\target\\classes\\1.png"; System.out.println("下载的路径"+realPath); //2.下载的文件名是啥 String fileName = realPath.substring(realPath.lastIndexOf("\\")+1); //3.设置浏览器下载所需要的设置 response.setHeader("Content-Disposition","attachment;fileName="+fileName); //4.获取下载的输入流 FileInputStream in = new FileInputStream(realPath); //5.创建缓存区 int len = 0; byte[] buffer = new byte[1024]; //6.获取outputStream对象 ServletOutputStream out = response.getOutputStream(); //7.将FileOutputStream流写入buffer缓存区中,使用outputStream将缓存区中的数据输出到客户端 while((len = in.read(buffer))>0){ out.write(buffer,0,len); } out.close(); in.close(); }
最新回复(0)