好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

JavaWeb入门:ServletContext详解和应用

当Servlet 容器启动的时候 会为每个web应用创建一个ServletContext 对象代表当前的web应用。

在web.xml 文件中不止可以配置Servlet的初始化信息 还可以给整个web应用配置初始化信息。

1、获取web 程序启动时初始化参数

web.xml 设置需要初始化的参数

?

1

2

3

4

5

6

7

8

9

<!--1、获取web应用程序初始化参数-->

< context-param >

     < param-name >name</ param-name >

     < param-value >crush</ param-value >

</ context-param >

< context-param >

     < param-name >school</ param-name >

     < param-value >hngy</ param-value >

</ context-param >

写一个Servlet继承HttpServlet

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

/**

  * @Author: crush

  * @Date: 2021-05-09 16:32

  * version 1.0

  */

@WebServlet ( "/servlet" )

public class ServletContextTest extends HttpServlet {

     @Override

     protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

         //设置响应头

         resp.setContentType( "text/html;charset=utf-8" );

         PrintWriter writer = resp.getWriter();

         ServletContext servletContext = this .getServletContext();

         // 根据名称 获取单个初始化参数

         String parameter = servletContext.getInitParameter( "name" );

         writer.print(parameter);

         writer.print( "<br><hr>" );

         // 获取全部初始化参数

         Enumeration<String> initParameterNames = servletContext.getInitParameterNames();

         while (initParameterNames.hasMoreElements()){

             String name = initParameterNames.nextElement();

             String value = servletContext.getInitParameter(name);

             writer.print(name+ ":" +value);

             writer.print( "<hr>" );

         }

     }

     @Override

     protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

         doGet(req, resp);

     }

}

@WebServlet("/servlet6") 作用等于

?

1

2

3

4

5

6

7

8

< servlet >

     < servlet-name >/servlet1</ servlet-name >

     < servlet-class >com.crush.servlet.ServletContextTest</ servlet-class >

</ servlet >

< servlet-mapping >

     < servlet-name >/servlet1</ servlet-name >

     < url-pattern >/servlet1</ url-pattern >

</ servlet-mapping >

2、实现多个Servlet 对象共享数据

一个web 应用中所有Servlet都共享ServletContext对象。在一定时候,ServletContext 也可以拿来传递信息

或者全局都需要的对象或者数据可以放进ServletContext中。

ServletContext接口的方法:这里讲解增加、获取、删除、设置ServletContext 域属性四个方法。

方法 描述
Enumeration getAttributeNames(); 返回一个Enumeration其中包含该ServletContext中所有的属性名称
Object getAttribute(String name); 返回具有给定名称的servlet容器属性;
void removeAttribute(String name); 从此ServletContext中删除具有给定名称的属性。
setAttribute(String name,Object obj) 在此ServletContext中将对象绑定到给定的属性名称。
如果指定的名称已经用于属性,则此方法将使用新的属性替换该属性。
如果在ServletContext上配置了侦听器,则容器会相应地通知它们。

设置值: ServletContextTest1

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

/**

  * @Author: crush

  * @Date: 2021-05-09 16:59

  * version 1.0

  */

@WebServlet ( "/servlet1" )

public class ServletContextTest1 extends HttpServlet {

     @Override

     protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

         // 获取ServletContext对象

         ServletContext servletContext = this .getServletContext();

         //设置值  ServletContext 域属性 name 域属性名 obj是值

         // 往ServletContext 中放进 username=crush 这个键值对

         servletContext.setAttribute( "username" , "crush" );

         // 在控制台给出提示

         System.out.println( "值已经设置完成" );

         // 重定向

//        resp.sendRedirect("/servlet2");

         // 转发

         req.getRequestDispatcher( "servlet2" ).forward(req, resp);

     }

     @Override

     protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

         doGet(req, resp);

     }

}

取出值 :ServletContextTest2

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

/**

  * @Author: crush

  * @Date: 2021-05-09 16:59

  * version 1.0

  */

@WebServlet ( "/servlet2" )

public class ServletContextTest2 extends HttpServlet {

     @Override

     protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

         // 获取ServletContext对象

         ServletContext servletContext = this .getServletContext();

 

         // 通过之前的设置的名字 取出username 的值

         String username =(String) servletContext.getAttribute( "username" );

         PrintWriter writer = resp.getWriter();

         writer.print(username);

         //返回一个Enumeration其中包含该ServletContext中可用的属性名称

         // Enumeration<String> attributeNames = servletContext.getAttributeNames();

         //从此ServletContext中删除具有给定名称的属性。

//        servletContext.removeAttribute("");

     }

     @Override

     protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

         doGet(req, resp);

     }

}

测试:

先访问 /servlet1 存值进去

再访问 /servlet2 取值出来

3、读取web应用下的资源

使用ServletContext 可以读取web应用下的资源

常用方法

方法 描述
String getRealPath(String path); 获取与给定虚拟路径相对应的真实路径。
InputStream getResourceAsStream(String path); 返回位于指定路径处的资源作为InputStream对象。
URL getResource(String path) 返回映射到给定路径的资源的URL。

mysql.properties

?

1

2

3

4

user =root

password =123456

url=jdbc:mysql://localhost:3306/mysql

drive=com

读取资源文件

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

/**

  * 读取资源内容

  * @Author: crush

  * @Date: 2021-05-09 16:59

  * version 1.0

  */

@WebServlet ( "/servlet3" )

public class ServletContextTest3 extends HttpServlet {

     @Override

     protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

         resp.setContentType( "text/html;charset=utf-8" );

         ServletContext servletContext = this .getServletContext();

         // 获取相对路径中的输入流对象  是要获取web应用程序的路径

         InputStream inputStream = servletContext.getResourceAsStream( "\\WEB-INF\\classes\\mysql.properties" );

         // 资源类对象

         Properties properties = new Properties();

         // load 从输入字节流中读取属性列表(键和元素对)

         properties.load(inputStream);

         PrintWriter writer = resp.getWriter();

         writer.print( "user" +properties.getProperty( "user" )+ "<br>" );

         writer.print( "password" +properties.getProperty( "password" )+ "<br>" );

         writer.print( "url" +properties.getProperty( "url" )+ "<br>" );

         writer.print( "drive" +properties.getProperty( "drive" )+ "<br>" );

     }

     @Override

     protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

         doGet(req, resp);

     }

}

对于mysql. properties 为什么是从WEB-INF/classes/ 目录下取的解释

resources和java文件夹下的 在web程序下的路径都是classes的路径下的 到之后我们会学到classpath的 一个路径

会更了解一些。

第二种方式

直接将mysql.properties文件放在WEB-INF/目录下

这个时候取的路径就产生了变化了,可以直接那么取到

这个时候我们发现 如果文件是放在WEB-INF 下面 的话 编译完后 是直接就在WEB-INF 下面 而不是在classes目录下的。这个内容是maven 里的内容,好奇可以去查一查。

4、请求转发

ServletContextTest5 转发到 ServletContextTest 去

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

/**

  * 请求转发

  * @Author: crush

  * @Date: 2021-05-09 16:59

  * version 1.0

  */

@WebServlet ( "/servlet5" )

public class ServletContextTest5 extends HttpServlet {

     @Override

     protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

         resp.setContentType( "text/html;charset=utf-8" );

         ServletContext servletContext = this .getServletContext();

         // RequestDispatcher对象可用于将请求转发到资源或将资源包括在响应中。 资源可以是动态的也可以是静态的。

         //路径名必须以/开头,并被解释为相对于当前上下文根。 使用getContext获取外部上下文中资源的RequestDispatcher

         servletContext.getRequestDispatcher( "/servlet" ).forward(req,resp);

         //forward:将请求从servlet转发到服务器上的另一个资源(servlet,JSP文件或HTML文件)

     }

     @Override

     protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

         doGet(req, resp);

     }

}

乱码解决

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

/**

  * 乱码问题

  * @Author: crush

  * @Date: 2021-05-09 16:59

  * version 1.0

  */

@WebServlet ( "/servlet6" )

public class ServletContextTest6 extends HttpServlet {

     @Override

     protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

         // 解决乱码 只是解决单独的响应乱码 如果有请求 还要设置请求的编码

         req.setCharacterEncoding( "utf-8" );

         resp.setContentType( "text/html;charset=utf-8" );

         PrintWriter writer = resp.getWriter();

         writer.print( "你好啊,JavaWeb" );

     }

     @Override

     protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

         doGet(req, resp);

     }

}

总结

本篇文章就到这里了,希望能给你带来帮助,也希望能够您能够关注的更多内容!

原文链接:https://blog.csdn.net/weixin_45821811/article/details/116571600

查看更多关于JavaWeb入门:ServletContext详解和应用的详细内容...

  阅读:15次