java-servlet

一、概念

  • 定义
    • 运行在服务端的Java应用程序。
  • 作用
    • 处理客户端发送的请求及响应处理的结果。

二、Idea搭建javaWeb项目

  • javaWeb项目
  • 新建一个servlet类
            /*
          * Copyright (C) Mr.Fu Corp.
          * All Right Reserved.
          */
         package com.example.comjavaweb;
         
         import jakarta.servlet.Servlet;
         import jakarta.servlet.ServletException;
         import jakarta.servlet.http.HttpServlet;
         import jakarta.servlet.http.HttpServletRequest;
         import jakarta.servlet.http.HttpServletResponse;
         
         import java.io.IOException;
         
         /**
          * @author FuShr.2023--5-23
          * @verdion V1.0
          */
         public class DemoServlet extends HttpServlet {
             public DemoServlet()
             {
                 System.out.println("DemoServlet类!");
             }
             @Override
             protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
                 System.out.println("客户端发起了Post请求!");
             }
         
             @Override
             protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
                 System.out.println("客户端发起了Get请求!");
             }
         } 
    
  • 在web.xml文件中创建映射
            <?xml version="1.0" encoding="UTF-8"?>
         <web-app xmlns="https://jakarta.ee/xml/ns/jakartaee"
                  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                  xsi:schemaLocation="https://jakarta.ee/xml/ns/jakartaee https://jakarta.ee/xml/ns/jakartaee/web-app_5_0.xsd"
                  version="5.0">
             <!--配置Servlet类-->
             <servlet>
                 <servlet-name>DemoServlet</servlet-name>
                 <servlet-class>com.example.comjavaweb.DemoServlet</servlet-class>
             </servlet>
         
             <!--配置Servlet类映射-->
             <servlet-mapping>
                 <servlet-name>DemoServlet</servlet-name>
                 <url-pattern>/demo</url-pattern>
             </servlet-mapping>
         </web-app>
    
  • html增加代码
        <form action="demo" method = "get">
           <input type="submit" value="get请求">
        </form> 
    
  • 使用注解的方式映射
     @WebServlet(name = "helloServlet", urlPatterns = "/hello-servlet")
     # name:servlet 名称
     # urlPatterns:servlet 路径
    

三、Servlet的生命周期

  • 生命周期
    • 实例化–初始化[init]–调用分发请求service-- destroy[销毁]

四、请求重定向

  • 概念
    • 地址栏请求,超链接;重定向之后地址栏内容发生变化。
      • 代码如下
       resp.sendRedirect("index.jsp?txt_name="+txt_name+"&txt_pwd="+txt_pwd);
      

五、请求转发

  • 从请求到结束只能发生一次请求,请求过程中地址栏不发生变化。
    • 代码如下
      //设置参数
       req.setAttribute("txt_name",txt_name);
       req.setAttribute("txt_pwd",txt_pwd); 
       //请求转发
       req.getRequestDispatcher("index.jsp").forward(req,resp);
      

六、jsp基本使用

  • JSP实质就一个servlet文件。(jsp->转译java文件)->在编译成.class文件->执行.class文件.
  • jsp的基本结构
    • 代码如下
          <%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %> 页面指令
          <!DOCTYPE html>
          <html>
          <head>
              <title>HOME</title>
          </head>
          <body>
          
          </body>
          </html>
          <%%> --java的小脚本,在这里就和在方法里面编写的代码一样
          <%! %>声明,能够在这个里面定义方法
          <%= %> 表达式
      
      • 使用前提
        • 必须有依赖jsp-api.jar
      • 示例代码
          <%@ page import="java.util.Date" %>
          <%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
          <%! public String  getTime(){
              return new Date().toLocaleString();
          } %>
          <!DOCTYPE html>
          <html>
          <head>
              <title>HOME</title>
          </head>
          <body>
          <!--显示登录的账号和密码-->
          <h1>HOME 页面</h1>
          <p>
             用户名:<%= request.getAttribute("txt_name")%>
          </p>
          <p>
              密码:<%= request.getAttribute("txt_pwd")%>
          </p>
          </body>
          </html>
        

七、JSTL标签库

  • 引入标签库
    • 下载标签库地址
      • mvnrespository.com
  • 在jsp页面引入标签库
    • pom.XML
        <dependency>
            <groupId>org.glassfish.web</groupId>
            <artifactId>jakarta.servlet.jsp.jstl</artifactId>
            <version>2.0.0</version>
        </dependency>
      
        <dependency>
            <groupId>org.apache.taglibs</groupId>
            <artifactId>taglibs-standard-spec</artifactId>
            <version>1.2.5</version>
        </dependency>
      
        <dependency>
            <groupId>org.apache.taglibs</groupId>
            <artifactId>taglibs-standard-impl</artifactId>
            <version>1.2.5</version>
        </dependency>
        
      
      • 注意:对应tomcat的版本为:10.1.16 jdk版本:JDK 21
  • 在jsp页面使用标签库
    • 示例代码
          //引入jstl标签库
          <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
          <table>
            <c:forEach begin="1" end="10" step="1" var="i" >
            <tr>
            <td>${i}</td>
            </tr>
            </c:forEach>
          </table> 
       </html>
      

八、Servlet 过滤器

  • 基本语法
      # 继承Filter 接口,并实现函数
          package Filter;
    
          import jakarta.servlet.*;
          import jakarta.servlet.annotation.WebFilter; 
          import java.io.IOException;
        
          @WebFilter(filterName = "HelloServletFilter",urlPatterns = "/*")
          public class HelloServletFilter implements Filter {
              /**
               * 过滤器初始化
               * @param filterConfig
               * @throws ServletException
               */
              @Override
              public void init(FilterConfig filterConfig) throws ServletException {
                  Filter.super.init(filterConfig);
              }
          
              /**
               *  servlet 请求过滤
               * @param servletRequest
               * @param servletResponse
               * @param filterChain
               * @throws IOException
               * @throws ServletException
               */
              @Override
              public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
                  //将servletRequest,servletResponse 对象强转成为Http的请求和响应对象
                  HttpServletRequest httpServletRequest =  (HttpServletRequest)servletRequest;
                  HttpServletResponse httpServletResponse = (HttpServletResponse)servletResponse;
                  //获取请求路径和ip地址、主机名 端口
                  System.out.println(httpServletRequest.getRemoteAddr());
                  System.out.println(httpServletRequest.getRequestURI());
                  System.out.println(httpServletRequest.getRemotePort());
                  System.out.println(httpServletRequest.getRemoteHost());
                  //设置编码格式
                  httpServletRequest.setCharacterEncoding("UTF-8");
                  httpServletResponse.setContentType("text/html;charset=UTF-8");  
                  //转发给下一个过滤器或者对应的servlet 响应请求
                  filterChain.doFilter(httpServletRequest,httpServletResponse); 
              }
          
              /**
               * 销毁
               */
              @Override
              public void destroy() {
                  Filter.super.destroy();
              }
          }
    
  • 25
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值