本文主要是介绍JakartaEE servlet,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
简介
JakartaEE是JavaEE的继承者,Oracle公司将JavaEE的API定义,文档,参考实现,测试TCK和套件都转移给Eclipse开源组织。
JavaSE为J2EE提供了库和语法,J2EE使用Java的库和语法应用在WEB上。这是概念性的区别。
Java SE:标准版Java SE(Java Platform,Standard Edition)。JavaSE以前称为J2SE。
它为开发和部署在桌面,服务器,嵌入式环境和实时环境中使用Java应用程序。
JavaSE包含了支持JavaWeb服务的开发的类,并为Java Platform,Enterprise Edition(Java EE)提供了基础。
企业版Java EE(Java Platform,Enterprise Edition)。这个版本以前称为J2EE。
企业版本帮助开发和部署可移植,健壮,可伸缩切安全的服务器端Java应用程序。
构建 java Enterprise项目
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>com.lihaozhe</groupId><artifactId>servlet</artifactId><version>1.0-SNAPSHOT</version><name>servlet</name><packaging>war</packaging><properties><jdk.version>17</jdk.version><maven.compiler.source>17</maven.compiler.source><maven.compiler.target>17</maven.compiler.target><maven.compiler.compilerVersion>17</maven.compiler.compilerVersion><maven.compiler.encoding>utf-8</maven.compiler.encoding><project.build.sourceEncoding>utf-8</project.build.sourceEncoding><project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding><maven.test.failure.ignore>true</maven.test.failure.ignore><maven.test.skip>true</maven.test.skip><junit.version>5.8.2</junit.version></properties><dependencies><dependency><groupId>jakarta.servlet</groupId><artifactId>jakarta.servlet-api</artifactId><version>5.0.0</version><scope>provided</scope></dependency><dependency><groupId>org.junit.jupiter</groupId><artifactId>junit-jupiter-api</artifactId><version>${junit.version}</version><scope>test</scope></dependency><dependency><groupId>org.junit.jupiter</groupId><artifactId>junit-jupiter-engine</artifactId><version>${junit.version}</version><scope>test</scope></dependency></dependencies><build><!--项目打包文件名--><finalName>servlet</finalName><plugins><plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-war-plugin</artifactId><version>3.3.2</version></plugin><!-- 编译级别 --><plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-compiler-plugin</artifactId><version>3.8.1</version><configuration><!-- 设置编译字符编码 --><encoding>UTF-8</encoding><!-- 设置编译jdk版本 --><source>${jdk.version}</source><target>${jdk.version}</target></configuration></plugin><plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-clean-plugin</artifactId><version>3.2.0</version></plugin><plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-resources-plugin</artifactId><version>3.2.0</version></plugin><!-- 打包的时候跳过测试junit begin --><plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-surefire-plugin</artifactId><version>2.22.2</version><configuration><skip>true</skip></configuration></plugin><!-- tomcat7插件 --><plugin><groupId>org.apache.tomcat.maven</groupId><artifactId>tomcat7-maven-plugin</artifactId><version>2.2</version><configuration><port>6633</port><path>/lhz</path><uriEncoding>UTF-8</uriEncoding><!-- tomcat热部署 --><username>admin</username><password>admin</password><url>http://192.168.18.65:8080/manager/text</url></configuration></plugin><!-- jetty插件 --><plugin><groupId>org.eclipse.jetty</groupId><artifactId>jetty-maven-plugin</artifactId><version>11.0.9</version><configuration><webApp><contextPath>/lhz</contextPath><defaultsDescriptor>${basedir}/src/main/resources/webdefault.xml</defaultsDescriptor></webApp><httpConnector><port>6633</port></httpConnector></configuration></plugin></plugins></build>
</project>
运行项目
访问主页
http://localhost:6633/lhz/
访问Servlet
访问REST接口
http://localhost:6633/lhz/api/hello-world
远程热部署
修改tomca/conf/tomcat-users.xml
<?xml version="1.0" encoding="UTF-8"?>
<!--Licensed to the Apache Software Foundation (ASF) under one or morecontributor license agreements. See the NOTICE file distributed withthis work for additional information regarding copyright ownership.The ASF licenses this file to You under the Apache License, Version 2.0(the "License"); you may not use this file except in compliance withthe License. You may obtain a copy of the License athttp://www.apache.org/licenses/LICENSE-2.0Unless required by applicable law or agreed to in writing, softwaredistributed under the License is distributed on an "AS IS" BASIS,WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.See the License for the specific language governing permissions andlimitations under the License.
-->
<tomcat-users xmlns="http://tomcat.apache.org/xml"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://tomcat.apache.org/xml tomcat-users.xsd"version="1.0">
<!--NOTE: By default, no user is included in the "manager-gui" role requiredto operate the "/manager/html" web application. If you wish to use this app,you must define such a user - the username and password are arbitrary. It isstrongly recommended that you do NOT use one of the users in the commented outsection below since they are intended for use with the examples webapplication.
-->
<!--NOTE: The sample user and role entries below are intended for use with theexamples web application. They are wrapped in a comment and thus are ignoredwhen reading this file. If you wish to configure these users for use with theexamples web application, do not forget to remove the <!.. ..> that surroundsthem. You will also need to set the passwords to something appropriate.
-->
<!--<role rolename="tomcat"/><role rolename="role1"/><user username="tomcat" password="<must-be-changed>" roles="tomcat"/><user username="both" password="<must-be-changed>" roles="tomcat,role1"/><user username="role1" password="<must-be-changed>" roles="role1"/>
-->
<role rolename="manager-gui"/>
<role rolename="manager-script"/>
<role rolename="manager-jmx"/>
<role rolename="manager-status"/>
<role rolename="admin-gui"/>
<role rolename="admin-script"/>
<user username="admin" password="admin" roles="manager-gui,manager-script,manager-jmx,manager-status,admin-gui,admin-script"/>
</tomcat-users>
修改webapps/manager/META-INF/context.xml和webapps/host-manager/META-INF/context.xml
<?xml version="1.0" encoding="UTF-8"?>
<!--Licensed to the Apache Software Foundation (ASF) under one or morecontributor license agreements. See the NOTICE file distributed withthis work for additional information regarding copyright ownership.The ASF licenses this file to You under the Apache License, Version 2.0(the "License"); you may not use this file except in compliance withthe License. You may obtain a copy of the License athttp://www.apache.org/licenses/LICENSE-2.0Unless required by applicable law or agreed to in writing, softwaredistributed under the License is distributed on an "AS IS" BASIS,WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.See the License for the specific language governing permissions andlimitations under the License.
-->
<Context antiResourceLocking="false" privileged="true" ><CookieProcessor className="org.apache.tomcat.util.http.Rfc6265CookieProcessor"sameSiteCookies="strict" /><Valve className="org.apache.catalina.valves.RemoteAddrValve"allow="127\.\d+\.\d+\.\d+|::1|0:0:0:0:0:0:0:1" /><Manager sessionAttributeValueClassNameFilter="java\.lang\.(?:Boolean|Integer|Long|Number|String)|org\.apache\.catalina\.filters\.CsrfPreventionFilter\$LruCache(?:\$1)?|java\.util\.(?:Linked)?HashMap"/>
</Context>
修改后
<?xml version="1.0" encoding="UTF-8"?>
<!--Licensed to the Apache Software Foundation (ASF) under one or morecontributor license agreements. See the NOTICE file distributed withthis work for additional information regarding copyright ownership.The ASF licenses this file to You under the Apache License, Version 2.0(the "License"); you may not use this file except in compliance withthe License. You may obtain a copy of the License athttp://www.apache.org/licenses/LICENSE-2.0Unless required by applicable law or agreed to in writing, softwaredistributed under the License is distributed on an "AS IS" BASIS,WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.See the License for the specific language governing permissions andlimitations under the License.
-->
<Context antiResourceLocking="false" privileged="true" ><CookieProcessor className="org.apache.tomcat.util.http.Rfc6265CookieProcessor"sameSiteCookies="strict" /><Manager sessionAttributeValueClassNameFilter="java\.lang\.(?:Boolean|Integer|Long|Number|String)|org\.apache\.catalina\.filters\.CsrfPreventionFilter\$LruCache(?:\$1)?|java\.util\.(?:Linked)?HashMap"/>
</Context>
新建Servlet
新建Servlet(注解方式)
package com.jdyxk.controller;
/*** @author 李昊哲* @Description* @version 1.0* @createTime 2021/8/31 上午10:45*/import jakarta.servlet.*;
import jakarta.servlet.http.*;
import jakarta.servlet.annotation.*;import java.io.IOException;//@WebServlet(name = "Servlet01", value = "/Servlet01")
@WebServlet(name = "Servlet01", urlPatterns = {"servlet01.action", "servlet01.do"})
public class Servlet01 extends HttpServlet {private static final long serialVersionUID = 5946742088318622256L;/*** @param request 接收用户请求数据* @param response 向用户发送响应数据* @throws ServletException Servlet异常* @throws IOException IO异常*/@Overrideprotected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {// HttpServletRequest 接收用户请求数据// HttpServletResponse 向用户发送响应数据System.out.println("注解方式启动");}
}
访问注解方式编写的Servlet
http://localhost:6633/lhz/servlet01.action
http://localhost:6633/lhz/servlet01.do
新建Servlet(xml方式)
package com.jdyxk.controller;
/*** @author 李昊哲* @Description* @version 1.0* @createTime 2021/8/31 上午10:58*/import jakarta.servlet.*;
import jakarta.servlet.http.*;import java.io.IOException;public class Servlet02 extends HttpServlet {private static final long serialVersionUID = 2878265913197286928L;/*** @param request 接收用户请求数据* @param response 向用户发送响应数据* @throws ServletException Servlet异常* @throws IOException IO异常*/@Overrideprotected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {// HttpServletRequest 接收用户请求数据// HttpServletResponse 向用户发送响应数据System.out.println("web.xml方式访问");}
}
编写web.xml文件
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="https://jakarta.ee/xml/ns/jakartaee"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="https://jakarta.ee/xml/ns/jakartaee https://jakarta.ee/xml/ns/jakartaee/web-app_5_0.xsd"version="5.0"><servlet><servlet-name>Servlet02</servlet-name><servlet-class>com.jdyxk.controller.Servlet02</servlet-class></servlet><servlet-mapping><servlet-name>Servlet02</servlet-name><url-pattern>/Servlet02</url-pattern></servlet-mapping><servlet-mapping><servlet-name>Servlet02</servlet-name><url-pattern>/servlet02.action</url-pattern></servlet-mapping><servlet-mapping><servlet-name>Servlet02</servlet-name><url-pattern>/servlet02.do</url-pattern></servlet-mapping>
</web-app>
访问xml方式编写的Servlet
http://localhost:6633/lhz/servlet02.action
http://localhost:6633/lhz/servlet02.do
Servlet响应用户数据
package com.jdyxk.controller;
/*** @author 李昊哲* @Description* @version 1.0* @createTime 2021/8/31 上午11:03*/import jakarta.servlet.*;
import jakarta.servlet.http.*;
import jakarta.servlet.annotation.*;import java.io.IOException;
import java.io.PrintWriter;@WebServlet(name = "Servlet03", value = "/Servlet03")
public class Servlet03 extends HttpServlet {private static final long serialVersionUID = -4783247332404478078L;/*** @param request 接收用户请求数据* @param response 向用户发送响应数据* @throws ServletException Servlet异常* @throws IOException IO异常*/@Overrideprotected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {System.out.println("love love love");// 处理请求数据中文乱码// 处理post请求的中文乱码request.setCharacterEncoding("utf-8");// 处理响应的字符集中文乱码response.setCharacterEncoding("utf-8");// response.setHeader("Content-Type","text/html;charset=utf-8");response.setContentType("text/html;charset=utf-8");PrintWriter writer = response.getWriter();writer.println("love and peace");writer.println("<br>");writer.println("我爱你中国,亲爱的母亲");writer.flush();writer.close();}}
访问Servlet响应数据
http://localhost:6633/lhz/servlet03
获取网络信息
http://192.168.18.65:6633/lhz/NetworkInfo
NetworkInfo.ajva
package com.jdyxk.http;
/*** @author 李昊哲* @Description* @version 1.0* @createTime 2021/8/31 上午11:42*/import com.jdyxk.commons.localdatetime.BaseLocalDateTime;
import jakarta.servlet.*;
import jakarta.servlet.http.*;
import jakarta.servlet.annotation.*;import java.io.IOException;@WebServlet(name = "NetworkInfo", value = "/NetworkInfo")
public class NetworkInfo extends HttpServlet {private static final long serialVersionUID = 3482094487102418998L;@Overrideprotected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {// 客户端(远程机器)// System.out.println("客户端IP地址 >>> " + request.getRemoteAddr());// System.out.println("客户端IP地址 >>> " + request.getRemoteHost());// System.out.println("客户端口号 >>> " + request.getRemotePort());// 服务器端(本地机器)// System.out.println("服务器IP地址 >>> " + request.getLocalAddr());// System.out.println("服务器端口号 >>> " + request.getLocalPort());// System.out.println("请求的URL >>> " + request.getRequestURL());System.out.println(BaseLocalDateTime.nowString() + "\t客户端:" + request.getRemoteAddr() + ":" + request.getRemotePort() + "\t请求的URL:" + request.getRequestURL());}
}
获取请求行信息
http://192.168.18.65:6633/lhz/RequestLine.jsp
在webapp目录新建页面文件RequestLine.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head><title>查询字符串</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/RequestLine" method="GET"><input type="text" name="account" value="" id="account" autocomplete="off" placeholder="请输入账户"><input type="password" name="password" value="" id="auth_text" autocomplete="off" placeholder="请输入密码"><input type="submit" value="登录">
</form>
</body>
</html>
RequestLine.java
package com.jdyxk.http;
/*** @author 李昊哲* @Description* @version 1.0* @createTime 2021/8/31 上午11:51*/import com.jdyxk.commons.string.StringUtil;
import jakarta.servlet.*;
import jakarta.servlet.http.*;
import jakarta.servlet.annotation.*;import java.io.IOException;
import java.util.HashMap;
import java.util.Map;@WebServlet(name = "RequestLine", value = "/RequestLine")
public class RequestLine extends HttpServlet {private static final long serialVersionUID = -1462573233106677460L;@Overrideprotected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {// 获取请求方式System.out.println("请求方式:" + request.getMethod());// 获取路径(URL、URI)System.out.println("请求的URL:" + request.getRequestURL());System.out.println("请求的URI:" + request.getRequestURI());// 获取协议System.out.println("协议:" + request.getProtocol());// 上下文路径System.out.println("请求的上下文路径:" + request.getContextPath());// jsp中 ${pageContext.request.contextPath}// 获取查询字符串System.out.println("请求的查询字符串:" + request.getQueryString());Map<String, String> map = parseQueryString(request.getQueryString());map.forEach((key, value) -> System.out.println("name = " + key + "\tvalue = " + value));// 回到原页面response.sendRedirect("RequestLine.jsp");}/*** 解析查询字符串** @param queryString* @return*/public Map<String, String> parseQueryString(String queryString) {Map<String, String> map = new HashMap<>();if (StringUtil.isBlank(queryString)) {return map;}String[] split = queryString.split("&");for (String param : split) {// account=admin// auth_text=123456String[] strings = param.split("=");map.put(strings[0], strings[1]);}return map;}
}
获取请求头信息
http://192.168.18.65:6633/lhz/RequestHeader
RequestHeader.java
package com.jdyxk.http;
/*** @author 李昊哲* @Description* @version 1.0* @createTime 2021/8/31 下午12:10*/import cn.hutool.http.useragent.UserAgent;
import cn.hutool.http.useragent.UserAgentParser;
import jakarta.servlet.*;
import jakarta.servlet.http.*;
import jakarta.servlet.annotation.*;import java.io.IOException;
import java.util.Enumeration;@WebServlet(name = "RequestHeader", value = "/RequestHeader")
public class RequestHeader extends HttpServlet {private static final long serialVersionUID = 1349423243847607898L;@Overrideprotected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {// System.out.println(request.getHeader("User-Agent"));System.out.println("++++++++++++++++++++++++++++++++++++++++++++++++++++++");Enumeration<String> headerNames = request.getHeaderNames();while (headerNames.hasMoreElements()){String name = headerNames.nextElement();System.out.println(name + ":" + request.getHeader(name));}System.out.println("++++++++++++++++++++++++++++++++++++++++++++++++++++++");String userAgentString = request.getHeader("User-Agent");UserAgent ua = UserAgentParser.parse(userAgentString);System.out.println("浏览器 >>> " + ua.getBrowser().toString());System.out.println("浏览器版本号 >>> " + ua.getVersion().toString());System.out.println("浏览器内核 >>> " + ua.getEngine().toString());System.out.println("浏览器内核版本号 >>> " + ua.getEngineVersion().toString());System.out.println("操作系统 >>> " + ua.getOs().toString());System.out.println("操作系统 >>> " + ua.getPlatform().toString());if (ua.isMobile()){System.out.println("移动端");} else {System.out.println("PC端");}}}
Servlet生命周期
注解方式验证
package com.jdyxk.lifecycle;import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;import java.io.IOException;/*** @author 李昊哲* @version 1.0* @Description* @createTime 2021/9/1 上午8:47*/
@WebServlet(urlPatterns = {"ServletLifeCycle01"})
public class ServletLifeCycle01 extends HttpServlet {private static final long serialVersionUID = 4267392516924911501L;public ServletLifeCycle01() {System.out.println("ServletLifeCycle01实例化 ServletLifeCycle01()");
这篇关于JakartaEE servlet的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!