JakartaEE servlet

2023-10-10 17:10
文章标签 servlet jakartaee

本文主要是介绍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的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/181907

相关文章

Servlet中配置和使用过滤器的步骤记录

《Servlet中配置和使用过滤器的步骤记录》:本文主要介绍在Servlet中配置和使用过滤器的方法,包括创建过滤器类、配置过滤器以及在Web应用中使用过滤器等步骤,文中通过代码介绍的非常详细,需... 目录创建过滤器类配置过滤器使用过滤器总结在Servlet中配置和使用过滤器主要包括创建过滤器类、配置过滤

JavaEE7 Servlet 3.1(JSR 340)规范中文版

http://www.iteye.com/news/27727-jinnianshilongnian     Jave EE 7中的部分规范已正式获得批准通过,其中包括JSR340 Java Servlet 3.1规范,去年翻译了该规范,在此分享出来,希望对某些朋友有所帮助,不足之处请指正。   点击直接下载    在线版目录   Servlet3.1规范翻译

请解释Java Web应用中的前后端分离是什么?它有哪些好处?什么是Java Web中的Servlet过滤器?它有什么作用?

请解释Java Web应用中的前后端分离是什么?它有哪些好处? Java Web应用中的前后端分离 在Java Web应用中,前后端分离是一种开发模式,它将传统Web开发中紧密耦合的前端(用户界面)和后端(服务器端逻辑)代码进行分离,使得它们能够独立开发、测试、部署和维护。在这种模式下,前端通常通过HTTP请求与后端进行数据交换,后端则负责业务逻辑处理、数据库交互以及向前端提供RESTful

Jasperreports+jaspersoft studio 实现单个或多个jrxml(jasper)文件生成一个pdf文件,并利用Servlet发送该pdf文件到浏览器中展示

Jasperreports+jaspersoft studio 实现单个或多个jrxml(jasper)文件生成一个pdf文件,并利用Servlet发送该pdf文件到浏览器中展示; 代码如下: Demo07.jrxml <?xml version="1.0" encoding="UTF-8"?><!-- Created with Jaspersoft Studio version 6.6.

servlet用反射代替if..else

String methodName = request.getParameter("method"); Method method = this.getClass().getDeclaredMethod(methodName,HttpServletRequest.class, HttpServletResponse.class); method.invoke(this, request, re

【Servlet】基础入门

1、使用 IDEA 建 javaWeb 及 Servlet http://blog.csdn.net/u012532559/article/details/51013400 2、doget与dopost的区别 http://www.cnblogs.com/cyy-13/p/5711235.html

Servlet mapping specifies an unknown servlet name Action

看一下web.xml中<servlet-mapping>有没有配错

怎么通过Servlet向浏览器发送中文

1.通过Servlet向浏览器发送中文,会出现以下的乱码: 2.为什么通过Servlet向浏览器发送中文会产生乱码呢?          在Servlet编程中,经常需要通过response对象将一些信息返回给浏览器,给我们的客户端,而我们在服务器端显示的中文,但是响应给客户端浏览器却是乱码,这主要是由于response对象的getWriter()方法返回的PrintWriter对象默认

请解释Java Web中的Filter的作用和使用场景。什么是Java Web中的JSP?请解释其与Servlet的关系及各自优势。

请解释Java Web中的Filter的作用和使用场景。 Java Web中的Filter(过滤器)是一个重要的组件,它在客户端与服务器端之间扮演着关键角色。Filter的主要作用是在请求到达Servlet或JSP之前,或者响应返回给客户端之前,对请求和响应进行预处理和后处理。以下是Filter的详细作用和使用场景: Filter的作用 请求预处理:在请求到达目标资源(如Servlet、J

音乐播放器javaweb项目近日总结,用js,css,HTML,servlet,mybatis来写注册登录忘记密码(还没写好)

这几天学了js,css,HTML,servlet,mybatis,还有axios,目前axios还没有用到,学的比较慢因为那个servlet,axios我看不懂,可能看懂了然后不会用,之后给我们上了一节课,感觉每一个东西单独拆开好像学过,但是放在一起听的很懵,今天我就到处翻博客反复看了点代码,终于知道了一点前后端交互就赶紧写了点。 因为是小白所以写的有些感觉没必要写的比较详细方便自己记忆