javaweb

发布时间 2023-10-21 16:21:23作者: 阿朱朱
web.xml 配置文件

<?xml version="1.0" encoding="UTF-8" ?>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
version="2.4">


<!-- 注册servlet-->
<servlet>
<servlet-name>hello</servlet-name>
<servlet-class>com.kuang.servlet.helloservlet</servlet-class>
</servlet>
<!-- servlet请求路径-->
<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
</web-app>

其中上面的<servlet-mapping>会请求上面的servlet,会进入到路径com.kuang.servlet.helloservlet最后会输出里面的内容。

一、servletContext:

 在servletContext里面存东西,可以在其它类servlet里面取出来

 取出:  记得加入

resp.setContentType("text/html");
resp.setCharacterEncoding("UTF-8");

 2、 获取初始化参数   getInitParameter

 在web.xml中

 在类中通过servletContext的 getInitParameter来获取初始参数

 

 3、getRequestDispatcher 请求转发

这里的gp是web.xml里面的路径 ,这里请求到这个路径,最后通过forward进行转发  所以这里转发的内容是gp路径上的内容

 

4、通过servletContext获取properties上的内容

当在main中新建db.properties , 启动就会在target/classes中出现同样的db.properties

 这里需要注意一个资源导出问题:需要在pom文件中加入:

 再在java类中  : 由于Properties输出需要使用Stream流                                                             如下为db.properties

    

 过程如下:

 最后就是取web.xml做映射