JavaEE8
JavaEE8,是自2013年6月Java企业版的首次更新。JAVAEE8提供了一些新的API,提供了对HTTP/2的新支持。
Servlet4.0
Servlet API是JAVA开发人员最熟悉的API之一。
Servlet在JavaWeb的开发中发挥着重要的作用。JAVAEE8对Servlet进行了重要的更新:
- 服务器推送
- 提供了对Servlet映射的运行时发现。
- 简化了Filter的开发。
其中服务器推送是最主要的更新
配置需要:
- jdk8+
- tomcat9(支持HTTP/2)
- tomcat-native
- openssl
配置tomcat
编辑server.xml
,将原来的port="8080" HTTP/1.1
替换成:
<Connector port="8443" protocol="org.apache.coyote.http11.Http11AprProtocol"
maxThreads="150" SSLEnabled="true" >
<UpgradeProtocol className="org.apache.coyote.http2.Http2Protocol" />
<SSLHostConfig>
<Certificate certificateKeyFile="conf/localhost-rsa-key.pem"
certificateFile="conf/localhost-rsa-cert.pem"
type="RSA" />
</SSLHostConfig>
</Connector>
生成SSL证书
生成私钥和证书文件在tomcat-native目录下:
OpenSSL> genrsa -out localhost-rsa-key.pem 2048
OpenSSL> req -new -x509 -key localhost-rsa-key.pem -out localhost-rsa-cert.pem -days 3650
将localhost-rsa-key.pem
和localhost-rsa-cert.pem
复制到tomcat的conf/
文件夹下。
将tomcat-native中bin/(x64/)
下的tcnative-1.dll
和tcnative-1-src.pdb
复制到JAVA_HOME的/bin
目录下
然后重启tomcat就能用HTTP/2来连接了。
服务器推送
将用户所需的WEB资源提前推送到用户的浏览器缓存中,当用户使用浏览器访问所需WEB资源时,用户不需要再次下载所需的WEB资源,因为用户所需的WEB资源已经存在于用户的浏览器缓存中。
获取:
request.newPushBuilder();
方法:
PushBuilder.path()
设置要推送资源的路径。PushBuilder.push()
推送WEB资源到用户的浏览器缓存中。
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PushBuilder pb = request.newPushBuilder();
pb.path("pic01.jpg");
pb.push();
}
简化:
PushBuilder pb = request.newPushBuilder();
pb.path("pic01.jpg").push();
pb.path("pic02.jpg").push();
HttpServletMapping
在运行时获取Servlet的映射信息(反射机制)
获取:
request.getHttpServletMapping();
方法:
getMappingMatch()
请求路径的类型getMatchValue()
映射的资源名getPattern()
返回Servlet映射的路径getServletName()
返回Servlet的名称
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpServletMapping mapping = request.getHttpServletMapping();
MappingMatch match = mapping.getMappingMatch();
System.out.println(match);
String value = mapping.getMatchValue();
System.out.println(value);
String pattern = mapping.getPattern();
System.out.println(pattern);
String name = mapping.getServletName();
System.out.println(name);
}
HttpFilter
Filter的实现类:
GenericFilter
HttpFilter
,是GenericFilter
的子类。
通过继承HttpFilter
来实现Filter:
@WebFilter(filterName = "FilterDemo",urlPatterns = "/*")
public class FilterDemo extends HttpFilter {
@Override
protected void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
System.out.println("FilterDemo:放行前");
chain.doFilter(request,response);
System.out.println("FilterDemo:放行后");
}
}
原创文章,作者:彭晨涛,如若转载,请注明出处:https://www.codetool.top/article/servlet4-0%e5%88%9d%e8%af%86%e6%80%bb%e7%bb%93/