Servlet 3.0 特性
Servlet 3.0 了解即可。
在servlet3.0中可以使用注解来替代我们配置文件.简单说:在servlet3.0中可以没有web.xml文件。
版本对应关系
servlet2.5 javaee5.0 tomcat 5.x tomcat6 jdk1.5
servlet3.0 javaee6.0 tomcat7.0 jdk1.6
1.使用注解来替换配置文件
@WebServlet("/hello") 用于配置servlet @WebFilter("/*") 用于配置Filter @WebListener 用于配置Listener
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
注意:属性urlpatterns与values它们都是描述访问当前servlet的路径,但它们不能一起出现,只能使用一个. <servlet> <servlet-name></servlet-name> String name() default ""; <servllet-class></servlet-class> <init-param> WebInitParam[] initParams() default {}; <param-name> <param-value> </init-param> <load-on-startup> int loadOnStartup() default -1; </servlet> <servlet-mapping> <servlet-name></servlet-name> <url-pattern></url-pattern> String[] urlPatterns() default {}; String[] value() default {}; </servlet-mapping> 在servlet中怎样获取初始化参数ServletConfig对象获取. 在web.xml文件中的属性 metadata-complete,可以取值为true,false,如果为false,代表servlet3.0中的注解可以使用,如果为true,代表不可以使用注解。
实例:@WebServlet("/hello") 用于配置servlet
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
@WebServlet(urlPatterns = { "/hello", "/h1" },initParams={@WebInitParam(name="username",value="tom"),@WebInitParam(name="encode",value="utf-8")}) public class MyServlet extends HttpServlet { @Override public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doPost(req, resp); } @Override public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { System.out.println("hello servlet"); // 获取初始化参数 ServletConfig config = this.getServletConfig(); String username = config.getInitParameter("username"); System.out.println(username); } }
2.servlet3.0中的文件上传
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
@WebServlet("/upload") @MultipartConfig public class UploadServlet extends HttpServlet { @Override public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doPost(req, resp); } @Override public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { req.setCharacterEncoding("utf-8");// 解决乱码 Part part = req.getPart("f"); // 得到上传文件信息. // req.getParts(); // 获取上传文件名称 String cd = part.getHeader("Content-Disposition"); System.out.println(cd); // form-data; name="f"; // filename="C:\Users\Administrator\Desktop\鎹曡幏.PNG" String filename = cd.substring(cd.lastIndexOf("\\") + 1, cd.length() - 1); System.out.println(filename); part.write("d:/upload/"+filename);// 完成文件上传. } }
2.1. 关于上传文件中文名称乱码问题。因为上传是post请求,直接使用post乱码解决方案就可以 request.setCharacterEncoding("utf-8");
2.2. 关于获取上传文件名称 通过Part获取一个header;String cd = part.getHeader("Content-Disposition");
在这个header中包含了上传文件名称,直接截取出来就可以。 String filename = cd.substring(cd.lastIndexOf("\\") + 1,cd.length() - 1);
2.3. 如果多文件上传怎样处理?request.getParts();
3.servlet3.0中异步处理
本质就是在服务器端开启一个线程,来完成其它的操作。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
@WebServlet(value = "/reg", asyncSupported = true) public class RegistServlet extends HttpServlet { @Override public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doPost(req, resp); } @Override public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setCharacterEncoding("utf-8"); final PrintWriter out = resp.getWriter(); // 1.注册操作 System.out.println("开始注册"); // try { // Thread.sleep(1000); // } catch (InterruptedException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } System.out.println("注册结束"); // 开启线程。进行发邮件操作. AsyncContext context = req.startAsync();// 获取一个异步 上下文对象. context.addListener(new AsyncListener() { @Override public void onTimeout(AsyncEvent event) throws IOException { } @Override public void onStartAsync(AsyncEvent event) throws IOException { } @Override public void onError(AsyncEvent event) throws IOException { } @Override public void onComplete(AsyncEvent event) throws IOException { // 监听到线程结束。 out.flush(); out.close(); } }); new Thread(new SendEmail(context)).start(); } } class SendEmail implements Runnable { private AsyncContext context; public SendEmail(AsyncContext context) { this.context = context; } @Override public void run() { PrintWriter out; try { out = context.getResponse().getWriter(); // 2.发送邮件---重新开启一个线程来完成。 System.out.println("开始发送邮件"); try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("邮件发送成功"); } catch (IOException e1) { e1.printStackTrace(); } } }
3.1.必须在注解添加一项
@WebServlet(value = "/reg", asyncSupported = true) asyncSupported=true,代表当前servlet支持异步操作.
3.2.需要一个异步上下文对象,通过这个对象,可以获取request,response对象.
AsyncContext context = req.startAsync(); 还可以对异步上下文进行监听,在它的监听器方法中有一个onComplete,可以用于判断结束。