JavaWeb

有时候,不是因为你没有能力,也不是因为你缺少勇气,只是因为你付出的努力还太少,所以,成功便不会走向你。而你所需要做的,就是坚定你的梦想,你的目标,你的未来,然后以不达目的誓不罢休的那股劲,去付出你的努力,成功就会慢慢向你靠近。

导读:本篇文章讲解 JavaWeb,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com,来源:原文

一、Servlet

1、servlet是JavaWeb三大组件之一。三大组件分别是:Servlet程序、Filter过滤器、Listener监听器。
2、servlet是运行在服务器上的java小程序,它可以接收客户端发送过来的请求,并响应数据给客户端。

1)Servlet第一个hello程序

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">

    <!--servlet标签给tomcat配置servlet程序-->
    <servlet>
        <!--servlet-name标签 servlet程序别名(一般是类名)-->
        <servlet-name>helloServlet</servlet-name>
        <!--servlet-class是servlet程序的全类名-->
        <servlet-class>com.xc.HelloServlet</servlet-class>
    </servlet>

    <!--servlet-mapping标签给servlet程序配置访问地址-->
    <servlet-mapping>
        <!--servlet-name标签表示当前配置的地址是给哪个servlet程序使用-->
        <servlet-name>helloServlet</servlet-name>
        <!--
        / 斜杠在服务器解析时,表示地址为http://ip:port/工程路径
        /hello            表示地址为http://ip:port/工程路径/hello
        -->
        <url-pattern>/hello</url-pattern>
    </servlet-mapping>
</web-app>
public class HelloServlet implements Servlet {
    public HelloServlet() {
        System.out.println("构造器... ");
    }

    public void init(ServletConfig servletConfig) throws ServletException {
        System.out.println("初始化...");
    }

    public ServletConfig getServletConfig() {
        return null;
    }

    public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException {
        System.out.println("servlet 业务...");
    }

    public String getServletInfo() {
        return null;
    }

    public void destroy() {
        System.out.println("销毁...");
    }
}
结果:
构造器... 
初始化...
servlet 业务...

2)Servlet生命周期

  1. 执行Servlet构造方法(创建servlet程序,第一次访问时候调用)
  2. 执行init初始化方法(创建servlet程序,第一次访问时候调用)
  3. 执行service方法(每次方法调用)
  4. 执行destroy销毁方法(web工程停止时候调用)

3) Servlet的继承关系

JavaWeb

3) ServletConfig配置信息类

  • Servlet程序和ServletConfig对象都是由Tomcat负责创建。
  • Servlet程序默认第一次访问时候创建,ServletConfig是每个Servlet程序创建,就创建一个对应的ServletConfig对象。
public void init(ServletConfig servletConfig) throws ServletException {
    System.out.println("初始化...");
//        1、获取servlet程序的别名servlet-name的值
    System.out.println("HelloServlet程序的别名:"+servletConfig.getServletName());
//        2、获取servlet程序初始化参数username的值
    System.out.println("初始化参数username的值:"+servletConfig.getInitParameter("username"));
//        3、获取servletContext上下文
    System.out.println("servletContext上下文:"+servletConfig.getServletContext());
}
<servlet>
    <!--servlet-name标签 servlet程序别名(一般是类名)-->
    <servlet-name>HelloServlet</servlet-name>
    <!--servlet-class是servlet程序的全类名-->
    <servlet-class>com.xc.HelloServlet</servlet-class>
    <init-param>
        <param-name>username</param-name>
        <param-value>root</param-value>
    </init-param>
</servlet>

结果:
初始化…
HelloServlet程序的别名:HelloServlet
初始化参数username的值:root
servletContext上下文:org.apache.catalina.core.ApplicationContextFacade@43b81667

4) ServletContext类

  1. ServletContext是一个接口,它表示Servlet上下文对象
  2. 一个web工程,只有一个ServletContext对象实例
  3. ServletContext对象是一个域对象(存:setAttribute()、取:getAttribute()、删:removeAttribute())
<!--context-param是上下文参数,属于整个web工程-->
<context-param>
    <param-name>username</param-name>
    <param-value>root123</param-value>
</context-param>
public class HelloServlet1 extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.获取上下文对象和参数
        ServletContext context = getServletContext();
        Object username = context.getInitParameter("username");
        System.out.println("context上下文参数username:"+username);
        //2.获取当前工程路径
        String contextPath = context.getContextPath();
        System.out.println("当前工程路径"+contextPath);
        //3.获取工程部署后在服务器硬盘上的绝对路径
        String realPath = context.getRealPath("/");
        System.out.println("部署绝对路径"+realPath);
        //4.类似map存取数据,整个web工程数据共享
        context.setAttribute("password","123456");
        System.out.println("获取上下文存取数据"+context.getAttribute("password"));
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }
}
结果:
context上下文参数username:root123
当前工程路径/springweb
部署绝对路径D:\workspace\localhost\webProject\springMVC\springmvc-demo1\target\springmvc-demo1-1.0-SNAPSHOT\
获取上下文存取数据123456

二、Http协议

  • GET请求
    JavaWeb
  • POST请求
    JavaWeb
  • 响应
    JavaWeb

1) HttpServletRequest类

  • 基本信息
public class ServletRequest extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String uri = request.getRequestURI();
        System.out.println("请求资源路径 uri: "+uri);
        StringBuffer url = request.getRequestURL();
        System.out.println("请求绝对路径 url:"+url);
        String host = request.getRemoteHost();
        System.out.println("客户端IP地址 host: "+host);
        String header = request.getHeader("User-Agent");
        System.out.println("请求头参数 header: "+header);
        String method = request.getMethod();
        System.out.println("获取请求方法 method:"+method);
    }
}
结果:
请求资源路径 uri: /springweb/servletRequest
请求绝对路径 url:http://localhost:8080/springweb/servletRequest
客户端IP地址 host: 0:0:0:0:0:0:0:1
请求头参数 header: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.159 Safari/537.36
获取请求方法 method:GET
  • 请求参数(post请求中文乱码,必须在第一行设置)
public class ServletRequestGETPOST extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        String username = request.getParameter("username");
        String[] hobbies = request.getParameterValues("hobby");
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
    }
}

2) 请求转发

  • 浏览器地址没有变化
  • 是一次请求
  • 它们共享request域中的数据
  • 可以转发到WEB-INF目录下
  • 不能转发工程以外的资源

请求地址

http://localhost:8080/springweb/servletRequestForward1?username=root&password=123456

servlet1

public class ServletRequestForward1 extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取前端请求参数
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        System.out.println("前端请求参数 username:"+username+",  password:"+password);
        //传递给重定向servlet信息
        request.setAttribute("key","info");
        //请求转发的地址
        //请求转发必须以斜杠“/”,表示地址为:http://ip:port/工厂名/,映射的idea的web目录
        RequestDispatcher requestDispatcher = request.getRequestDispatcher("/servletRequestForward2");
        //请求转发执行操作
        requestDispatcher.forward(request,response);
    }
}

servlet2

public class ServletRequestForward2 extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取servlet1请求传来的参数(也是前端传来的)
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        System.out.println("ServletRequestForward1(前端)请求参数 username:"+username+",  password:"+password);
        Object value = request.getAttribute("key");
        System.out.println("ServletRequestForward1 保存的数据 key:"+value);
        System.out.println("执行完毕");
    }
}

配置

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">
    <servlet>
        <servlet-name>ServletRequestForward1</servlet-name>
        <servlet-class>com.xc.ServletRequestForward1</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>ServletRequestForward1</servlet-name>
        <url-pattern>/servletRequestForward1</url-pattern>
    </servlet-mapping>
    <servlet>
        <servlet-name>ServletRequestForward2</servlet-name>
        <servlet-class>com.xc.ServletRequestForward2</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>ServletRequestForward2</servlet-name>
        <url-pattern>/servletRequestForward2</url-pattern>
    </servlet-mapping>
</web-app>

3) 解决响应乱码

public class ServletResponse extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //方式一:
//        //设置服务器字符集UTF-8
//        response.setCharacterEncoding("UTF-8");
//        //通过响应头,设置浏览器使用UTF-8字符集
//        response.setHeader("Content-Type","text/html;charset=UTF-8");
        //方式一:
        //同时设置服务器和客户端都使用UTF-8字符集
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter writer = response.getWriter();
        writer.write("华为牛逼");
    }
}

4) 请求重定向

JavaWeb

public class ServletResponse1 extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("请求入口");
        /*方式一:*/
//        //设置响应状态码
//        response.setStatus(302);
//        //设置响应头,及重定向地址
//        response.setHeader("Location","http://localhost:8080/demo1/servletResponse2");
        /*方式二:*/
        response.sendRedirect("http://localhost:8080/demo1/servletResponse2");
    }
}

public class ServletResponse2 extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("重定向入口");
    }
}

三、jsp

jsp本质是一个servlet程序

1) 九大内置对象

JavaWeb

2) 四大域对象

JavaWeb

3) 输出流对象(out和response)

JavaWeb

四、Listener监听器

  • Listener监听器是javaweb三大组件之一。(servlet程序、Filter过滤器、Listener监听器)
  • Listener它是javaEE的规范,就是接口
  • 监听器作用:监听某种事务变化。通过回调函数,反馈给客户(程序)去做一些响应处理。

1) ServletContextListener 监听器

public class ListenerTest implements ServletContextListener {
    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {
        System.out.println("对象被创建了");
    }

    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) {
        System.out.println("对象被销毁了");
    }
}
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">
    <listener>
        <listener-class>com.xc.ListenerTest</listener-class>
    </listener>
</web-app>

分别在服务启动和停止时输出

五、Filter 过滤器

1) 过滤器及生命周期

public class Filter1 implements Filter {

    public Filter1() {
        System.out.println("Filter1 构造方法");
    }

    public void destroy() {
        System.out.println("Filter1 销毁方法");
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        System.out.println("拦截请求");
        //使程序往下执行
        chain.doFilter(req, resp);
    }

    public void init(FilterConfig config) throws ServletException {
        System.out.println("Filter1 初始化方法");
    }

}
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">
    <!--配置Filter过滤器-->
    <filter>
        <!--配置Filter的一个别名-->
        <filter-name>Filter1</filter-name>
        <!--配置Filter的全类名-->
        <filter-class>com.xc.Filter1</filter-class>
    </filter>
    <filter-mapping>
        <!--表示当前拦截路径给哪个filter使用-->
        <filter-name>Filter1</filter-name>
        <!-- 配置拦截路径
            /          表示http://ip:port/工程路径/  映射到web项目  (不包含.jsp和.jspx)
            /*         表示http://ip:port/工程路径/admin/*        (所有请求)
        -->
        <url-pattern>/*</url-pattern>
    </filter-mapping>
</web-app>
  • 服务启动执行构造方法和初始化方法
  • 服务调用执行拦截方法
  • 服务停止执行销毁方法

2) 多个过滤器执行顺序

JavaWeb

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/148674.html

(0)
小半的头像小半

相关推荐

发表回复

登录后才能评论
极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!