Servlet对象

发布时间:2024年01月23日

ServletConfig对象

  • 是什么

    ServletConfig是javax.servlet.包下的一个接口,ServletConfig它是Servlet的一个配置对象;

    ServletConfig是由tomcat容器创建,通过init方法传入给Servlet;

  • ServletConfig对象如何获取?

    在GenericServlet里面定义了:

public ServletConfig getServletConfig() {
    return this.config;
}
  • 常用方法
getInitParameter(String parameterName); //根据参数名称获取指定的参数值
getInitParameterNames(); //获取所有的参数名称
  • 需求:

获取servlet里面定义的参数

    <servlet>
        <servlet-name>servletConfig</servlet-name>
        <servlet-class>com.by.servlet.ServletConfigServlet</servlet-class>
        <!--Servlet的初始化参数-->
        <init-param>
            <param-name>username</param-name>
            <param-value>root</param-value>
        </init-param>
        <init-param>
            <param-name>password</param-name>
            <param-value>root123</param-value>
        </init-param>
    </servlet>
    
    <servlet-mapping>
        <servlet-name>servletConfig</servlet-name>
        <url-pattern>/servletConfig</url-pattern>
    </servlet-mapping>
package com.by.servlet;

import javax.servlet.*;
import javax.servlet.http.HttpServlet;

public class ServletConfigServlet extends HttpServlet {

    @Override
    public void service(ServletRequest servletRequest, 
                        ServletResponse servletResponse) throws ServletException {
        //1.获取ServletConfig对象
        ServletConfig servletConfig = getServletConfig();
        //2.获取Servlet中的初始化参数
        String username = servletConfig.getInitParameter("username");
        System.out.println(username);
        String password = servletConfig.getInitParameter("password");
        System.out.println(password);

    }
}

思考:param参数可不可以在另外的Servlet中获取? 不能

public class ServletConfigServlet2 extends HttpServlet {

    @Override
    public void goGet(ServletRequest servletRequest, 
                      ServletResponse servletResponse) throws ServletException {
        //1.获取ServletConfig对象
        ServletConfig servletConfig = getServletConfig();
        //2.获取Servlet中的初始化参数
        String username = servletConfig.getInitParameter("username");//不能获取
        System.out.println(username);
        String password = servletConfig.getInitParameter("password");//不能获取
        System.out.println(password);
    }
}

ServletContext对象

  • 是什么

    ServletContext是javax.servlet包下的一个接口,又称上下文对象,是配置对象也是一个域对象;

    当服务器启动时,会为服务器中的每一个web应用程序创建一个ServletContext对象;

    在web应用中的servlet要想实现资源的共享,可以通过ServletContext来完成;

  • 如何获取这个对象:

public ServletContext getServletContext() {
    //获取ServletContext对象
    return this.getServletConfig().getServletContext();
}
  • 这个对象里面也有很多方法:
getInitParameter() //获取指定参数名称的全局参数值
getRealPath(String path) //获得当前项目的服务器磁盘路径
getContextPath() //获取项目的根路径
getAttribute(String parameterName) //获取ServletContext域中指定名称的参数值;
setAttribute(String paramterName,Object parameterValue) //存储参数到ServletContext域中;
removeAttribute(String parameterNam) //将ServletContext域中指定名称的参数移除;
  • 需求

获取servlet里面定义的参数

    <context-param>
        <param-name>username</param-name>
        <param-value>root</param-value>
    </context-param>
    <context-param>
        <param-name>password</param-name>
        <param-value>root456</param-value>
    </context-param>
package com.by.servlet;

import javax.servlet.*;
import javax.servlet.http.HttpServlet;

public class ServletContextServlet extends HttpServlet {

    @Override
    public void service(ServletRequest servletRequest, 
                        ServletResponse servletResponse) throws ServletException {
        //获取ServletContext对象
        ServletContext servletContext = getServletContext();
        //1.获取全局初始化参数
        String username = servletContext.getInitParameter("username");
        System.out.println(username);
        String password = servletContext.getInitParameter("password");
        System.out.println(password);
        //2.获取服务器真实路径
        String upload = servletContext.getRealPath("");
        System.out.println(upload);
        //3.获取项目的根路径
        String contextPath = servletContext.getContextPath();
        System.out.println(contextPath);

        //4.往ServletContext域中,存储一个名称为msg的属性,值为"hello"
        String str = "hello";
        servletContext.setAttribute("msg",str);
    }
}

思考:param参数可不可以在另外的Servlet中获取? 不能

package com.by.servlet;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;

public class ServletContextServlet2 extends HttpServlet {

    @Override
    public void doGet(ServletRequest servletRequest, 
                      ServletResponse servletResponse) throws ServletException {
        //从ServletContext域中取出msg的值
        ServletContext servletContext = getServletContext();
         //1.获取全局初始化参数
        String username = servletContext.getInitParameter("username");
        System.out.println(username);
        String password = servletContext.getInitParameter("password");
        System.out.println(password);
        
        //2.获得msg属性
        Object msg = servletContext.getAttribute("msg");//能获取
        System.out.println(msg);
    }
}
package com.by.servlet;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;

public class ServletContextServlet3 extends HttpServlet {

    @Override
    public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException {
        //1.获取ServletContext对象
        ServletContext servletContext = getServletContext();
        //将ServletContext域中的msg参数移除
        servletContext.removeAttribute("msg");
    }
}
    <servlet>
        <servlet-name>context3=</servlet-name>
        <servlet-class>com.by.servlet.ServletContextServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>context3=</servlet-name>
        <url-pattern>/context=</url-pattern>
    </servlet-mapping>
    

    <servlet>
        <servlet-name>context2</servlet-name>
        <servlet-class>com.by.servlet.ServletContextServlet2</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>context2</servlet-name>
        <url-pattern>/context2</url-pattern>
    </servlet-mapping>
    

    <servlet>
        <servlet-name>context3</servlet-name>
        <servlet-class>com.by.servlet.ServletContextServlet3</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>context3</servlet-name>
        <url-pattern>/context3</url-pattern>
    </servlet-mapping>

Request对象

  • 是什么

ServletRequest是一个接口,用户访问服务器,服务器会生成一个对象包含了http所有请求头,由于使用的是http协议,所以该对象的名字叫HttpServletRequest

  • 常用的方法
getRequestURL() //获取的完整的URL,即统一资源定位符
getRequestURI() //获取资源的名字,即统一资源标识符
getQueryString() //获取一个url参数部分
getRemoteAddr() //返回的是客户端的ip地址
getRemoteUser() //返回的是客户端的用户
getRemotePort() //返回的是客户端的主机的端口号
getRemoteHost() //返回的是客户端的主机地址
getCookie() //获取Cookie对象
getSession() //获取Session对象
getLocalName() //获取Web服务器主机的名字
getServletContext() //获取上下文对象的
setCharacterEncoding() //设置编码集的
getParameter() //获取前端传过来的数据
setAttribute() //将数据设置给request对象
geAttribute() //获取request对象中的数据
  • servlet实例
package com.by.servlet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class RequestServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, 
                          HttpServletResponse response) throws Exception {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, 
                         HttpServletResponse response) throws Exception{
        //获取一个完整的url
        //http://localhost:8080/01_servlet_HelloWorld_war/request1
        System.out.println(request.getRequestURL());
        //获取资源的名字
        //比如:http://localhost:8080/day42_xkh/request1
        System.out.println(request.getRequestURI());///01_servlet_HelloWorld_war/request1
        //获取一个url的参数部分
        //比如 http://localhost:8080/01_servlet_HelloWorld_war/request1?username=goudan
        System.out.println(request.getParameter("username"));

        //获取前端传送过来的数据
        request.setCharacterEncoding("utf-8");//设置请求的编码集
        //给request这个对象设置数据
        request.setAttribute("name","狗蛋");
        //获取request对象的值
        request.getAttribute("name");
        //获取上下文对象
        ServletContext servletContext = request.getServletContext();
        //转发
        request.getRequestDispatcher("target.jsp").forward(request,response);
    }
}
    <servlet>
        <servlet-name>request</servlet-name>
        <servlet-class>com.by.servlet.RequestServlet</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>request</servlet-name>
        <url-pattern>/context</url-pattern>
    </servlet-mapping>

Response对象

  • 是什么

响应对象,把数据返回给客户端
我们的Servlet紧紧围绕着两个点(Request,Response)请求和响应

  • 常用方法
setHeader() //设置响应头的参数
setContentType() //设置字符编码集
getWriter() //获取字符输出流对象
addCookie() //对浏览器新增一个Cookie
sendRedirect() //重定向
  • servlet实例
package com.by.servlet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class ResponseServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, 
                         HttpServletResponse response) throws Exception{
        /**************乱码问题*****/
        //方式一
        response.setHeader("Content-Type", 
                           "text/html;charset=utf-8");//通知浏览器使用utf-8解码
        //方式二
        response.setContentType("text/html;charset=utf-8;aaa=bbb");    //包含方法一的两个功能

        //向客户端发送响应数据
        response.getWriter().write("<h1>hello<h1>");

        /************重定向***********/
        //方式一
        //在响应头中添加302状态码,告诉浏览器需要进行重定向
        response.setStatus(302);
        //在响应头中添加Location,指定重定向的位置
        response.setHeader("Location", "http://www.baidu.com");
        //方式二
        response.sendRedirect("http://www.baidu.com");  //包含方法一的两个功能
    }
}
    <servlet>
        <servlet-name>response</servlet-name>
        <servlet-class>com.by.servlet.ResponseServlet</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>response</servlet-name>
        <url-pattern>/response</url-pattern>
    </servlet-mapping>
文章来源:https://blog.csdn.net/w2144217940/article/details/135787811
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。