当前位置: 首页 > news >正文

JavaWeb-Servlet

文章目录

    • 一、常见软件系统体系结构
      • C/S架构:
      • B/S架构:
    • 二、JavaWeb(JavaEE):使用java语言编写web程序
    • 三、HTTP/TCP
    • 四、JavaEE(Javaweb):底层原理,必须会
      • 创建java版本的web项目
    • maven的配置
    • servlet的生命周期:
    • 原理:
    • HTTP请求方法的使用频率和特点
    • requst请求常用函数
    • reponse请求常用函数
    • 项目的访问路径

一、常见软件系统体系结构

C/S架构:

缺点
1、安装庞大的客户端
2、升级、维护、安装、部署不方便

优点: 性能极高,安全性好


B/S架构:

优点:
1、无需本地安装客户端,仅需浏览器即可
2、升级是在服务器端升级。用户无感知。移动办公方便

缺点:
性能要弱于c/s架构。百ms级延迟,企业级办公应用来说,可以接受


b/s架构蓬勃发展,常用于开发动态网页应用的语言::

asp,php,java,c#,python...

二、JavaWeb(JavaEE):使用java语言编写web程序

为什么可以用java语言编写web程序?JavaWeb的优势:
1、java语言:严谨、易读、健壮、简单。
2、面向对象。庞大的类库,社区活跃。很多语言使用jvm。
3、国内,java一家独大。

javaEE:java分为三个版本:从jdk1.2开始划分javaEE:就是javaweb
1.javaSE:standard Edition 标准版
2.javaEE:Enterprise Edition专业版
3.javaME:Micro Edition 已经消亡 ios和安卓


java强项:编写web程序


三、HTTP/TCP

HTTP:网络协议、应用层协议
TCP:传输层协议

七层:从上往下:

应用层 ->表示层->会话层->传输层->网络层->链路层->物理层

四、JavaEE(Javaweb):底层原理,必须会

1、Servlet:接受http请求,并进行响应的网络组件,使用Java语言写的。

2、JSP:本质上就是servlet,只不过方便进行html编写 。

服务器:

tomcat,weblogic,websphere,jetty,wildfy,glassfish…

一般都使用tomcat,免费

创建java版本的web项目

在这里插入图片描述
在这里插入图片描述
创建成功的项目结构:

在这里插入图片描述

IDEA的配置是对项目的配置,只是应用于当前项目

maven的配置

maven:依赖管理,及项目构建工具。

maven的conf下的 settings.xml配置文件:

修改本地仓库的位置,配置远程仓库,修改jdk版本

<?xml version="1.0" encoding="UTF-8"?><!--
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements.  See the NOTICE file
distributed with this 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
with the 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,
software distributed 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 and limitations
under the License.
--><!--| This is the configuration file for Maven. It can be specified at two levels:||  1. User Level. This settings.xml file provides configuration for a single user,|                 and is normally provided in ${user.home}/.m2/settings.xml.||                 NOTE: This location can be overridden with the CLI option:||                 -s /path/to/user/settings.xml||  2. Global Level. This settings.xml file provides configuration for all Maven|                 users on a machine (assuming they're all using the same Maven|                 installation). It's normally provided in|                 ${maven.conf}/settings.xml.||                 NOTE: This location can be overridden with the CLI option:||                 -gs /path/to/global/settings.xml|| The sections in this sample file are intended to give you a running start at| getting the most out of your Maven installation. Where appropriate, the default| values (values used when the setting is not specified) are provided.||-->
<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0 http://maven.apache.org/xsd/settings-1.0.0.xsd"><!-- localRepository| The path to the local repository maven will use to store artifacts.|| Default: ${user.home}/.m2/repository<localRepository>/path/to/local/repo</localRepository>-->
<localRepository>D:/maven/repository</localRepository><!-- interactiveMode| This will determine whether maven prompts you when it needs input. If set to false,| maven will use a sensible default value, perhaps based on some other setting, for| the parameter in question.|| Default: true<interactiveMode>true</interactiveMode>--><!-- offline| Determines whether maven should attempt to connect to the network when executing a build.| This will have an effect on artifact downloads, artifact deployment, and others.|| Default: false<offline>false</offline>--><!-- pluginGroups| This is a list of additional group identifiers that will be searched when resolving plugins by their prefix, i.e.| when invoking a command line like "mvn prefix:goal". Maven will automatically add the group identifiers| "org.apache.maven.plugins" and "org.codehaus.mojo" if these are not already contained in the list.|--><pluginGroups><!-- pluginGroup| Specifies a further group identifier to use for plugin lookup.<pluginGroup>com.your.plugins</pluginGroup>--></pluginGroups><!-- proxies| This is a list of proxies which can be used on this machine to connect to the network.| Unless otherwise specified (by system property or command-line switch), the first proxy| specification in this list marked as active will be used.|--><proxies><!-- proxy| Specification for one proxy, to be used in connecting to the network.|<proxy><id>optional</id><active>true</active><protocol>http</protocol><username>proxyuser</username><password>proxypass</password><host>proxy.host.net</host><port>80</port><nonProxyHosts>local.net|some.host.com</nonProxyHosts></proxy>--></proxies><!-- servers| This is a list of authentication profiles, keyed by the server-id used within the system.| Authentication profiles can be used whenever maven must make a connection to a remote server.|--><servers><!-- server| Specifies the authentication information to use when connecting to a particular server, identified by| a unique name within the system (referred to by the 'id' attribute below).|| NOTE: You should either specify username/password OR privateKey/passphrase, since these pairings are|       used together.|<server><id>deploymentRepo</id><username>repouser</username><password>repopwd</password></server>--><!-- Another sample, using keys to authenticate.<server><id>siteServer</id><privateKey>/path/to/private/key</privateKey><passphrase>optional; leave empty if not used.</passphrase></server>--></servers><!-- mirrors| This is a list of mirrors to be used in downloading artifacts from remote repositories.|| It works like this: a POM may declare a repository to use in resolving certain artifacts.| However, this repository may have problems with heavy traffic at times, so people have mirrored| it to several places.|| That repository definition will have a unique id, so we can create a mirror reference for that| repository, to be used as an alternate download site. The mirror site will be the preferred| server for that repository.|--><mirrors><!-- mirror| Specifies a repository mirror site to use instead of a given repository. The repository that| this mirror serves has an ID that matches the mirrorOf element of this mirror. IDs are used| for inheritance and direct lookup purposes, and must be unique across the set of mirrors.|<mirror><id>mirrorId</id><mirrorOf>repositoryId</mirrorOf><name>Human Readable Name for this Mirror.</name><url>http://my.repository.com/repo/path</url></mirror>--><!--配置具体的仓库的下载镜像-->
<mirror><id>alimaven</id><name>aliyun maven</name><url>http://maven.aliyun.com/nexus/content/groups/public/</url><mirrorOf>central</mirrorOf>
</mirror></mirrors><!-- profiles| This is a list of profiles which can be activated in a variety of ways, and which can modify| the build process. Profiles provided in the settings.xml are intended to provide local machine-| specific paths and repository locations which allow the build to work in the local environment.|| For example, if you have an integration testing plugin - like cactus - that needs to know where| your Tomcat instance is installed, you can provide a variable here such that the variable is| dereferenced during the build process to configure the cactus plugin.|| As noted above, profiles can be activated in a variety of ways. One way - the activeProfiles| section of this document (settings.xml) - will be discussed later. Another way essentially| relies on the detection of a system property, either matching a particular value for the property,| or merely testing its existence. Profiles can also be activated by JDK version prefix, where a| value of '1.4' might activate a profile when the build is executed on a JDK version of '1.4.2_07'.| Finally, the list of active profiles can be specified directly from the command line.|| NOTE: For profiles defined in the settings.xml, you are restricted to specifying only artifact|       repositories, plugin repositories, and free-form properties to be used as configuration|       variables for plugins in the POM.|<profiles>|--><!-- profile| Specifies a set of introductions to the build process, to be activated using one or more of the| mechanisms described above. For inheritance purposes, and to activate profiles via <activatedProfiles/>| or the command line, profiles have to have an ID that is unique.|| An encouraged best practice for profile identification is to use a consistent naming convention| for profiles, such as 'env-dev', 'env-test', 'env-production', 'user-jdcasey', 'user-brett', etc.| This will make it more intuitive to understand what the set of introduced profiles is attempting| to accomplish, particularly when you only have a list of profile id's for debug.|| This profile example uses the JDK version to trigger activation, and provides a JDK-specific repo.<profile><id>jdk-1.4</id><activation><jdk>1.4</jdk></activation><repositories><repository><id>jdk14</id><name>Repository for JDK 1.4 builds</name><url>http://www.myhost.com/maven/jdk14</url><layout>default</layout><snapshotPolicy>always</snapshotPolicy></repository></repositories></profile>--><!--| Here is another profile, activated by the system property 'target-env' with a value of 'dev',| which provides a specific path to the Tomcat instance. To use this, your plugin configuration| might hypothetically look like:|| ...| <plugin>|   <groupId>org.myco.myplugins</groupId>|   <artifactId>myplugin</artifactId>||   <configuration>|     <tomcatLocation>${tomcatPath}</tomcatLocation>|   </configuration>| </plugin>| ...|| NOTE: If you just wanted to inject this configuration whenever someone set 'target-env' to|       anything, you could just leave off the <value/> inside the activation-property.|<profile><id>env-dev</id><activation><property><name>target-env</name><value>dev</value></property></activation><properties><tomcatPath>/path/to/tomcat/instance</tomcatPath></properties></profile>
</profiles>--><profiles><profile><id>jdk-21</id><activation><activeByDefault>true</activeByDefault><jdk>21</jdk></activation><properties><maven.compiler.source>21</maven.compiler.source><maven.compiler.target>21</maven.compiler.target><maven.compiler.compilerVersion>21</maven.compiler.compilerVersion></properties></profile>
</profiles><!-- 让增加的 profile生效 -->
<activeProfiles><activeProfile>jdk-21</activeProfile>
</activeProfiles><!-- activeProfiles| List of profiles that are active for all builds.|<activeProfiles><activeProfile>alwaysActiveProfile</activeProfile><activeProfile>anotherAlwaysActiveProfile</activeProfile></activeProfiles>-->
</settings>

在这里插入图片描述

IDEA的配置是对项目的配置,只是应用于当前项目

全局配置:

在这里插入图片描述

但是全局配置并不是每次都能生效。

关于中文编码:

在这里插入图片描述

本机:127.0.0.1
本机:localhost

servlet的生命周期:

1.普通的servlet在第一次请求时创建
2.调用init函数进行初始化
3.持续对提供服务
4.当tomcat服务器关闭时,servlet销毁

原理:

在这里插入图片描述

HTTP请求方法的使用频率和特点

service可以接收任意类型的请求。

1.get使用频率最高。除了post请求之外的全部是get请求。比如:浏览器地址 ,超链接,link,script,image,ifram.更侧重获取。传递参数只能写在地址之后,语法:?a=b&c=d&e=f…。传递的参数数据容量有局限,且是明文

2.post使用频率最高,只能通过form表单来提交,更侧重提交。传递数据容理论上无限,且是隐式传输(不在地址栏后面,看不见)

(浏览器只能发出get和post请求,都遵循HTTP协议)

二者总结:请求协议:客户端发送给服务器的格式

格式:

请求首行
请求头信息
空行
请求体

分类:

GET
可以在请求的URL地址后以?的形式带上交给服务器的数据,多个数据之间以&进行分隔;
在URL地址后附带的参数是有限制的,其数据容量通常不能超过1K;
GET请求没有请求体。
POST
传送的数据量无限制;
传输的数据在请求体内。

以下三种浏览器不能发出,需要借助其他方式。
3.put
4.path
5.delete
(1-5使用频率高。)
6options 使用频率很低
7.head 几乎不用 8trace 几乎不用

requst请求常用函数

1.getMethod 获取请求的类型
2.getServletPath 获取请求路径
3.getContextPath 获取上下文路径
4.getRequestURL 统一资源定位符
5.getRequestURI  统一资源描述符
6.getPathInfo 只有@WebServlet("/hello/*")中出现*时有效,返回*代表的地址
7.getQueryString 查询参数,请求地址栏问号后面的内容
8.getParameter(“xxx”)获取地址栏xxx的内容

9.这个是reponse的响应对象的:setCharacterEncoding(“UTF-8”)给请求对象和响应对象设置字符集

package com.situ.demo01_0723;
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;
import java.io.PrintWriter;
//@WebServlet("/hello/*")
@WebServlet("/hello")
public class HelloWorldServlet extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {//1、获取请求的类型;String method = req.getMethod();System.out.println(method);//2、获取请求路径String servletPath = req.getServletPath();System.out.println(servletPath);//3、获取上下文路径:String contextPath = req.getContextPath();System.out.println(contextPath);//5、返回String类型的URL:统一资源定位符StringBuffer requestURL = req.getRequestURL();System.out.println(requestURL);//5、返回String类型的,URI:统一资源描述符String requestURI = req.getRequestURI();System.out.println(requestURI);//6、pathInfo只有出现*才有意义:@WebServlet("/hello/*")String pathInfo = req.getPathInfo();System.out.println(pathInfo);//7、查询参数String queryString = req.getQueryString();System.out.println(queryString);//8、获取参数String parameter = req.getParameter("name");String parameter2 = req.getParameter("pwd");System.out.println(parameter);System.out.println(parameter2);//9、设置编码:req.setCharacterEncoding("UTF-8");resp.setCharacterEncoding("UTF-8");//设置响应内容的内容resp.setContentType("text/html;charset=utf-8");PrintWriter out = resp.getWriter();out.println("<h1> 你好,我是Servlet</h1>");out.println("<form method=\"post\" action=\"/hello\"><input type='text' name='age' value='100'><button type='submit'>提交</form>");out.flush();}@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {//获取请求的类型;String method = req.getMethod();System.out.println(method);resp.setContentType("text/html;charset=utf-8");}}

reponse请求常用函数

package com.situ.demo01_0723;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;
import java.io.PrintWriter;
@WebServlet("/response")
public class ResponseServlet extends HttpServlet {@Overrideprotected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {//执行代码是有顺序的,要先设置响应内容和中文编码//设置响应内容:resp.setContentType("text/html;charset=utf-8");//resp.setContentType("text/css;charset=utf-8");//设置中文编码:resp.setCharacterEncoding("utf-8");//重定向:打开这个默认直接跳转.客户端重新发起一个新的请求,地址栏改变//获取上下文路径
//        resp.sendRedirect(req.getContextPath() + "/hello");//向域中存储数据req.setAttribute("aaa","bbb");//请求转发:服务器端转发,客户端无感知,不会创建新的请求req.getRequestDispatcher("hello").forward(req,resp);req.getRequestDispatcher("hello.jsp").forward(req,resp);//一个请求只能有一个响应,上面的重定向就是一个响应,所以下面写的响应:返回一个字符流不会执行//返回一个字符流:
//        PrintWriter out = resp.getWriter();
//        out.println("<h1>你好</h1>");
//        out.flush();//输出到浏览器}
}

项目的访问路径

关于访问路径:协议://主机名:端口号/项目名/资源协议:一般是http或https
主机名:localhost或者一个其他的域名
端口号:Tomcat默认的是8080
项目名:和webapps下项目所在目录的目录名一致
资源:静态资源或动态资源位置,如果资源在某个目录中,此处也要包含目录的名字。
注意:WEB-INF目录中的资源无法直接访问。
http://www.dtcms.com/a/294922.html

相关文章:

  • 内外网互传文件 安全、可控、便捷的跨网数据交换
  • 服务器版本信息泄露-iis返回包暴露服务器版本信息
  • Node.js 倒计时图片服务部署与 Nginx 反向代理实战总结
  • RCE随笔-奇技淫巧(2)
  • Android热修复实现方案深度分析
  • AI面试如何提升物流行业招聘效率?实战案例解析
  • ESP32-S3学习笔记<5>:SPI的应用
  • JDK 介绍与使用指南
  • CMake进阶:检查头文件存在性(check_include_file 和 check_include_fileCXX)
  • uniapp拦截返回事件
  • 应该切换到 NVMe 吗?
  • 学习 Pandas 库:Series 与 DataFrame 核心操作指南
  • c语言:预处理详解
  • CRMEB 单商户PRO多商户通用去版权教程
  • 二叉树解析
  • 51c大模型~合集158
  • RockyLinux 9.6 解决删除home后无法开机问题
  • 视觉BPE统一多模态理解-北大
  • Python+大模型 day03
  • 面试实战,问题四,介绍一下dubbo框架,如何回答
  • 河南萌新联赛2025第二场-河南农业大学
  • 解决uniapp 使用uview生成小程序包太大无法上传的问题
  • 亚马逊广告优化技巧:如何减少预算浪费
  • Tang Prime 20K板I2S输入输出例程
  • lumerical——光纤布拉格光栅(Fiber Bragg gratings)
  • AI驱动攻防升级,API安全走到关键档口
  • MyBatis整合SpringBoot终极指南
  • 设备维修记录可追溯:管理系统选型指南
  • ESP32-S3 小电视学习笔记2:Arduino开发环境搭建(垃圾)
  • PyTorch深度学习入门记录2