java-web之ServletContext

百度百科:

ServletContext接口是Servlet中最大的一个接口,呈现了web应用的Servlet视图

我的理解:

ServletContext是一个容器,可以存放你在网页中,你的项目里你你所浏览过的,编写过的东西。可利用这个容器调出来使用。

以下均用代码展示:

 

1. 共享数据

web.xml配置:

    <servlet>
        <servlet-name>hello</servlet-name>
        <servlet-class>top.klxy.servlet.HelloServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>hello</servlet-name>
        <url-pattern>/hello</url-pattern>
    </servlet-mapping>

    <servlet>
        <servlet-name>get</servlet-name>
        <servlet-class>top.klxy.servlet.GetServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>get</servlet-name>
        <url-pattern>/get</url-pattern>
    </servlet-mapping>

HelloServlet.java

package top.klxy.servlet;

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

/**
 * @Author: SmallWang
 * @Date: 2020/7/19 0019 21:54
 * @Version: 1.0
 */
public class HelloServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html");
        resp.setCharacterEncoding("utf-8");
        System.out.println("hello");    //控制台打印
        PrintWriter writer = resp.getWriter();
        writer.print("hello");  //网页里面打印 hello
        ServletContext context = this.getServletContext();
        String name = "王驰";
        context.setAttribute("username",name);  //将一个数据保存在servlet中    名为:usersname   值为: name
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doPost(req, resp);
    }
}

GetServlet.java

package top.klxy.servlet;

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

/**
 * @Author: SmallWang
 * @Date: 2020/7/19 0019 22:33
 * @Version: 1.0
 */
public class GetServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html");
        resp.setCharacterEncoding("utf-8");
        ServletContext context = this.getServletContext();
        String username = (String) context.getAttribute("username");
        PrintWriter writer = resp.getWriter();
        writer.print("名字:"+username);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doPost(req, resp);
    }
}

启动服务器,浏览器先输入:http://localhost:8081/s1/hello     在输入:http://localhost:8081/s2/get

可以获得在HelloServlet中保存的姓名:

注意:如果启动项目直接输入http://localhost:8081/s2/get地址会得的空值    名字:null

 

2. 获取初始化参数

在web.xml中定义个初始化参数

    <context-param>
        <param-name>url</param-name>
        <param-value>jdbc:mysql://localhost:3306/mybatis</param-value>
    </context-param>

web.xml中定义路径

    <servlet>
        <servlet-name>demo03</servlet-name>
        <servlet-class>top.klxy.servlet.ServletDemo</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>demo03</servlet-name>
        <url-pattern>/demo03</url-pattern>
    </servlet-mapping>

ServletDemo.java

package top.klxy.servlet;

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

/**
 * @Author: SmallWang
 * @Date: 2020/7/19 0019 22:43
 * @Version: 1.0
 */
public class ServletDemo extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html");
        resp.setCharacterEncoding("utf-8");
        ServletContext context = this.getServletContext();
        String url = context.getInitParameter("url");
        resp.getWriter().print(url);
    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doPost(req, resp);
    }
}

启动服务器,浏览器输入地址:http://localhost:8081/s2/demo03

 

3. 请求转发(重定向)

web.xml配置:

    <servlet>
        <servlet-name>demo03</servlet-name>
        <servlet-class>top.klxy.servlet.ServletDemo</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>demo03</servlet-name>
        <url-pattern>/demo03</url-pattern>
    </servlet-mapping>

    <servlet>
        <servlet-name>demo04</servlet-name>
        <servlet-class>top.klxy.servlet.ServletDemo04</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>demo04</servlet-name>
        <url-pattern>/demo04</url-pattern>
    </servlet-mapping>

ServletDemo04.java

package top.klxy.servlet;

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

/**
 * @Author: SmallWang
 * @Date: 2020/7/19 0019 22:50
 * @Version: 1.0
 */
public class ServletDemo04  extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html");
        resp.setCharacterEncoding("utf-8");
        ServletContext context = this.getServletContext();
        System.out.println("ServletDemo04");
        /*
        RequestDispatcher dispatcher = context.getRequestDispatcher("/demo03");//转发的请求路径
        dispatcher.forward(req,resp); //调用forward实现请求转发
        */
        context.getRequestDispatcher("/demo03").forward(req,resp); //等价于上面两句注释
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doPost(req, resp);
    }
}

启动服务器,浏览器输入地址:http://localhost:8081/s2/demo04

4.读取资源文件

要知道,在javaweb项目中,我们的资源文件和src下的源码文件在打包后都在一个classes路径下,俗称:类路径

资源文件:

web.xml配置:

<servlet>
    <servlet-name>demo05</servlet-name>
    <servlet-class>top.klxy.servlet.ServletDemo05</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>demo05</servlet-name>
    <url-pattern>/demo05</url-pattern>
</servlet-mapping>

ServletDemo05.java

package top.klxy.servlet;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
 * @Author: SmallWang
 * @Date: 2020/7/19 0019 23:06
 * @Version: 1.0
 */
public class ServletDemo05 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html");
        resp.setCharacterEncoding("utf-8");
        ServletContext context = this.getServletContext();
        InputStream is = context.getResourceAsStream("/WEB-INF/classes/db.properties");
        Properties pro = new Properties();
        pro.load(is);
        String uer = pro.getProperty("username");
        String pwd = pro.getProperty("password");
        resp.getWriter().println("姓名:" + uer +"\n密码:"+pwd);
    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doPost(req, resp);
    }
}

启动服务器,浏览器输入地址:http://localhost:8081/s2/demo05

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
1. 实现登录功能        先把从前台接收的数据封装起来,然后查询数据库,看数据库中是否有这个用户,如果没有则提示登录失败,如果有这个用户则先销毁之前的session,然后再检查此用户是否在其它地方登录,有的话则销毁它的session,强制下线。到这里才算登录成功,将页面跳转到主聊天界面。 2. 检查用户登录信息是否过期的实现        获取session域中的User对象,判断该对象是否为空,如果为空则用户登录信息过期,提示用户重新登录,跳转到登录界面。 3. 注册功能的实现        先把从前台接收的数据封装起来,然后检查用户输入的两次密码是否一致,如果不一致,则提示“登录失败,两次密码不一致”的错误,然后查询数据库是否有用户名一样的用户,如果有,则提示“注册失败,此用户已存在”,否则向数据库中插入用户信息,然后提示注册成功。 4. 聊天功能的实现        发送消息:先获取从前台发送的聊天内容,然后拼接上已发送的聊天记录,再将消息存入到application的范围,最后调用接收消息的方法。         接收消息:从ServletContext中获取消息,如果不为空则输出消息。 5. 在线人员列表显示功能的实现        将登录进系统的用户与其对应的session存储到一个userMap中,然后显示出来 6. 踢人功能的实现        接收前台传来的需要踢下线的用户id,然后在userMap中获取用户并销毁该用户的session    7. 退出聊天室        获得session然后将其销毁,跳转到登录界面
META-INF/MANIFEST.MF META-INF/license.txt org.springframework.remoting.caucho.BurlapClientInterceptor.class org.springframework.remoting.caucho.BurlapProxyFactoryBean.class org.springframework.remoting.caucho.BurlapServiceExporter.class org.springframework.remoting.caucho.Hessian1SkeletonInvoker.class org.springframework.remoting.caucho.Hessian2SkeletonInvoker.class org.springframework.remoting.caucho.HessianClientInterceptor.class org.springframework.remoting.caucho.HessianProxyFactoryBean.class org.springframework.remoting.caucho.HessianServiceExporter.class org.springframework.remoting.caucho.HessianSkeletonInvoker.class org.springframework.remoting.httpinvoker.AbstractHttpInvokerRequestExecutor.class org.springframework.remoting.httpinvoker.CommonsHttpInvokerRequestExecutor.class org.springframework.remoting.httpinvoker.HttpInvokerClientConfiguration.class org.springframework.remoting.httpinvoker.HttpInvokerClientInterceptor.class org.springframework.remoting.httpinvoker.HttpInvokerProxyFactoryBean.class org.springframework.remoting.httpinvoker.HttpInvokerRequestExecutor.class org.springframework.remoting.httpinvoker.HttpInvokerServiceExporter.class org.springframework.remoting.httpinvoker.SimpleHttpInvokerRequestExecutor.class org.springframework.remoting.jaxrpc.JaxRpcPortClientInterceptor.class org.springframework.remoting.jaxrpc.JaxRpcPortProxyFactoryBean.class org.springframework.remoting.jaxrpc.JaxRpcServicePostProcessor.class org.springframework.remoting.jaxrpc.JaxRpcSoapFaultException.class org.springframework.remoting.jaxrpc.LocalJaxRpcServiceFactory.class org.springframework.remoting.jaxrpc.LocalJaxRpcServiceFactoryBean.class org.springframework.remoting.jaxrpc.ServletEndpointSupport.class org.springframework.remoting.jaxrpc.support.AxisBeanMappingServicePostProcessor.class org.springframework.remoting.jaxws.JaxWsPortClientInterceptor.class org.springframework.remoting.jaxws.JaxWsPortProxyFactoryBean.class org.springframework.remoting.jaxws.JaxWsSoapFaultException.class org.springframework.remoting.jaxws.LocalJaxWsServiceFactory.class org.springframework.remoting.jaxws.LocalJaxWsServiceFactoryBean.class org.springframework.remoting.jaxws.SimpleJaxWsServiceExporter.class org.springframework.web.HttpRequestHandler.class org.springframework.web.HttpRequestMethodNotSupportedException.class org.springframework.web.HttpSessionRequiredException.class org.springframework.web.bind.EscapedErrors.class org.springframework.web.bind.MissingServletRequestParameterException.class org.springframework.web.bind.RequestUtils.class org.springframework.web.bind.ServletRequestBindingException.class org.springframework.web.bind.ServletRequestDataBinder.class org.springframework.web.bind.ServletRequestParameterPropertyValues.class org.springframework.web.bind.ServletRequestUtils.class org.springframework.web.bind.WebDataBinder.class org.springframework.web.bind.annotation.InitBinder.class org.springframework.web.bind.annotation.ModelAttribute.class org.springframework.web.bind.annotation.RequestMapping.class org.springframework.web.bind.annotation.RequestMethod.class org.springframework.web.bind.annotation.RequestParam.class org.springframework.web.bind.annotation.SessionAttributes.class org.springframework.web.bind.support.ConfigurableWebBindingInitializer.class org.springframework.web.bind.support.DefaultSessionAttributeStore.class org.springframework.web.bind.support.SessionAttributeStore.class org.springframework.web.bind.support.SessionStatus.class org.springframework.web.bind.support.SimpleSessionStatus.class org.springframework.web.bind.support.WebBindingInitializer.class org.springframework.web.context.ConfigurableWebApplicationContext.class org.springframework.web.context.ContextLoader.class org.springframework.web.context.ContextLoaderListener.class org.springframework.web.context.ContextLoaderServlet.class org.springframework.web.context.ServletConfigAware.class org.springframework.web.context.ServletContextAware.class org.springframework.web.context.WebApplicationContext.class org.springframework.web.context.request.AbstractRequestAttributes.class org.springframework.web.context.request.AbstractRequestAttributesScope.class org.springframework.web.context.request.Log4jNestedDiagnosticContextInterceptor.class org.springframework.web.context.request.RequestAttributes.class org.springframework.web.context.request.RequestContextHolder.class org.springframework.web.context.request.RequestContextListener.class org.springframework.web.context.request.RequestScope.class org.springframework.web.context.request.ServletRequestAttributes.class org.springframework.web.context.request.ServletWebRequest.class org.springframework.web.context.request.SessionScope.class org.springframework.web.context.request.WebRequest.class org.springframework.web.context.request.WebRequestInterceptor.class org.springframework.web.context.support.AbstractRefreshableWebApplicationContext.class org.springframework.web.context.support.ContextExposingHttpServletRequest.class org.springframework.web.context.support.GenericWebApplicationContext.class org.springframework.web.context.support.HttpRequestHandlerServlet.class org.springframework.web.context.support.PerformanceMonitorListener.class org.springframework.web.context.support.RequestHandledEvent.class org.springframework.web.context.support.ServletContextAttributeExporter.class org.springframework.web.context.support.ServletContextAttributeFactoryBean.class org.springframework.web.context.support.ServletContextAwareProcessor.class org.springframework.web.context.support.ServletContextFactoryBean.class org.springframework.web.context.support.ServletContextParameterFactoryBean.class org.springframework.web.context.support.ServletContextPropertyPlaceholderConfigurer.class org.springframework.web.context.support.ServletContextResource.class org.springframework.web.context.support.ServletContextResourceLoader.class org.springframework.web.context.support.ServletContextResourcePatternResolver.class org.springframework.web.context.support.ServletRequestHandledEvent.class org.springframework.web.context.support.StaticWebApplicationContext.class org.springframework.web.context.support.WebApplicationContextUtils.class org.springframework.web.context.support.WebApplicationObjectSupport.class org.springframework.web.context.support.XmlWebApplicationContext.class org.springframework.web.filter.AbstractRequestLoggingFilter.class org.springframework.web.filter.CharacterEncodingFilter.class org.springframework.web.filter.CommonsRequestLoggingFilter.class org.springframework.web.filter.DelegatingFilterProxy.class org.springframework.web.filter.GenericFilterBean.class org.springframework.web.filter.Log4jNestedDiagnosticContextFilter.class org.springframework.web.filter.OncePerRequestFilter.class org.springframework.web.filter.RequestContextFilter.class org.springframework.web.filter.ServletContextRequestLoggingFilter.class org.springframework.web.jsf.DecoratingNavigationHandler.class org.springframework.web.jsf.DelegatingNavigationHandlerProxy.class org.springframework.web.jsf.DelegatingPhaseListenerMulticaster.class org.springframework.web.jsf.DelegatingVariableResolver.class org.springframework.web.jsf.FacesContextUtils.class org.springframework.web.jsf.SpringBeanVariableResolver.class org.springframework.web.jsf.WebApplicationContextVariableResolver.class org.springframework.web.jsf.el.SpringBeanFacesELResolver.class org.springframework.web.jsf.el.WebApplicationContextFacesELResolver.class org.springframework.web.multipart.MaxUploadSizeExceededException.class org.springframework.web.multipart.MultipartException.class org.springframework.web.multipart.MultipartFile.class org.springframework.web.multipart.MultipartHttpServletRequest.class org.springframework.web.multipart.MultipartResolver.class org.springframework.web.multipart.commons.CommonsFileUploadSupport.class org.springframework.web.multipart.commons.CommonsMultipartFile.class org.springframework.web.multipart.commons.CommonsMultipartResolver.class org.springframework.web.multipart.support.AbstractMultipartHttpServletRequest.class org.springframework.web.multipart.support.ByteArrayMultipartFileEditor.class org.springframework.web.multipart.support.DefaultMultipartHttpServletRequest.class org.springframework.web.multipart.support.MultipartFilter.class org.springframework.web.multipart.support.StringMultipartFileEditor.class org.springframework.web.util.CookieGenerator.class org.springframework.web.util.ExpressionEvaluationUtils.class org.springframework.web.util.HtmlCharacterEntityDecoder.class org.springframework.web.util.HtmlCharacterEntityReferences.class org.springframework.web.util.HtmlUtils.class org.springframework.web.util.HttpSessionMutexListener.class org.springframework.web.util.IntrospectorCleanupListener.class org.springframework.web.util.JavaScriptUtils.class org.springframework.web.util.Log4jConfigListener.class org.springframework.web.util.Log4jConfigServlet.class org.springframework.web.util.Log4jWebConfigurer.class org.springframework.web.util.NestedServletException.class org.springframework.web.util.TagUtils.class org.springframework.web.util.UrlPathHelper.class org.springframework.web.util.WebAppRootListener.class org.springframework.web.util.WebUtils.class org/springframework/web/context/ContextLoader.properties org/springframework/web/util/HtmlCharacterEntityReferences.properties

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值