其他分享
首页 > 其他分享> > Tomcat中使用servletContext

Tomcat中使用servletContext

作者:互联网

Tomcat中使用servletContext

ServletContext的特点

ServletContext的使用

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

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置编码
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html:charset=utf-8");

        // 获取ServletContext
        // 方式1
        ServletContext servletContext = this.getServletContext();
        // 方式2
        ServletContext servletContext1 = this.getServletConfig().getServletContext();
        // 方式3
        ServletContext servletContext2 = request.getSession().getServletContext();

        // servletcontext设置属性值
        servletContext.setAttribute("name", "zhangsan");

        // 读取servletcontext的属性值
        String name = (String)servletContext.getAttribute("name");

        //  从web和xml中获取参数值
        String chengdu = servletContext.getInitParameter("chengdu");
        System.out.println(chengdu);

        // 获取项目下某个文件的绝对路径
        String realPath = servletContext.getRealPath("web.xml");
        System.out.println(realPath);

        // 获取web项目的上下文路径
        String contextPath = servletContext.getContextPath();
        System.out.println(contextPath);
    }
}

标签:web,String,Tomcat,getServletContext,servletContext,ServletContext,使用,name
来源: https://www.cnblogs.com/shanlei/p/14502009.html