servlet3.0的问题
- Servlet3.0与Servlet2.5提供了三个新特性:
* 注解开发 :方便
* 文件上传 :有些API不是特别全.
* 异步请求 :多线程的实现
注解开发:
注解的开发是的整个开发过程中不需要web.xml配置文件。
web层
Servlet @WebServlet("访问路径")
Filter @WebFilter("访问路径")
Listener @WebListener("访问路径")
service层
@WebService
文件上传:
这个上传过程是特别繁琐的,其中获取文件名字需要从发送过来的头部进行String的方法进行截取。使得整个过程繁琐;对于流的对接也不是特别友好。
使用fileUpload工具包来开发有特定的文件项的流的对接。整个开发过程大大节约了时间。
代码: @WebServlet("/UploadServlet") @MultipartConfig//表示文件上传注解 public class UploadServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 接收普通数据: request.setCharacterEncoding("UTF-8"); String filedesc = request.getParameter("filedesc"); System.out.println("文件描述"+filedesc); // 接收文件: Part part = request.getPart("upload"); long size = part.getSize();// 获得文件大小: System.out.println("文件大小:"+size); String name = part.getName(); System.out.println("文件表单中的name属性的名称"+name); // 获得文件名: String header = part.getHeader("Content-Disposition"); int idx = header.lastIndexOf("filename=""); String fileName = header.substring(idx+10, header.length()-1); System.out.println("文件名:"+fileName); // 获得文件内容: InputStream is = part.getInputStream(); // 获得upload的路径: String path = this.getServletContext().getRealPath("/upload"); OutputStream os = new FileOutputStream(path+"/"+fileName); byte[] b = new byte[1024]; int len = 0; while((len = is.read(b))!=-1){ os.write(b, 0, len); } is.close(); os.close(); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
异步:异步的实现其实是一个多线程。
/** * 异步请求的Servlet */ @WebServlet(urlPatterns="/AsyncServlet",asyncSupported=true) public class AsyncServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { AsyncContext context = request.startAsync(request, response); context.start(new MyRunnable(context)); for(int i = 1;i<=10;i++){ System.out.println(i); try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } } } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } } class MyRunnable implements Runnable{ private AsyncContext context; public MyRunnable(AsyncContext context) { this.context = context; } @Override public void run() { for(char i='a';i<='z';i++){ try { context.getResponse().getWriter().println(i); Thread.sleep(100); } catch (Exception e) { e.printStackTrace(); } } } }