JSP原理

浏览器向服务器发送请求,不管访问什么资源,其实都是在访问Servlet

JSP 本质也是Servlet,实现了HttpServlet

  1. 判断请求
  2. 内置对象(pageContext,session,application,config,out,page,request,response)
  3. 输出页面前增加的代码
  4. 在JSP中,JAVA代码会原封不动的输出,HTML会被转为out.write("<html>");的格式输出

基础语法

引入JSTL表达式依赖包javax.servlet.jsp.jstl 和standard标签库

<dependency>
  <groupId>javax.servlet.jsp.jstl</groupId>
  <artifactId>jstl-api</artifactId>
  <version>1.2</version>
</dependency>
<dependency>
  <groupId>taglibs</groupId>
  <artifactId>standard</artifactId>
  <version>1.1.2</version>
</dependency>
表达式:<%= 变量或表达式 %>
用来将程序输出到客户端
<%= new java.util.Date()%> //Tue Nov 23 21:19:01 CST 2021
脚本片段:<% java代码 %>
<% out.println("test");%>
代码嵌入HTML元素: ${}
<% for(int i=0;i<10;i++){%>
    <p>${i}</p>
<% }%>
声明:<%! %>
JSP的声明,会被编译到JSP生成的类中;其他会生成到_jspService方法中
<%!
    static {
        System.out.println("test");
    }
%>
注释:<%-- 注释 --%>
<%-- JSP的注释,不会在客户端显示 --%>
指令:<%@ page %> <%@ include %>
<%@ page errorPage="error/500.jsp" %> //指定500页面
标签 <jsp:include />
<jsp:include page="/common/header.jsp"/>

<%@include %>和<jsp:include /> 的区别:1会合并页面 2不会

内置对象

  • PageContext
  • Request
  • Response
  • Session
  • Application (ServletContext)
  • Config (ServletConfig)
  • out
  • page
  • Exception
<%
    pageContext.setAttribute("name1","Name1");//在一个页面中有效
    request.setAttribute("name2","Name2");    //在一次请求中有效
    session.setAttribute("name3","Name3");    //在一次对话中有效
    application.setAttribute("name4","Name4");//在服务器一次开关中有效
%>
<%
    //从底层到高层(作用域):page > request > session > application
    //双亲委派机制:
    String name1 = (String) pageContext.findAttribute("name1");
    String name2 = (String) pageContext.findAttribute("name2");
    String name3 = (String) pageContext.findAttribute("name3");
    String name4 = (String) pageContext.findAttribute("name4");
%>
<h1>${name1}</h1>
<h2>${name2}</h2>
<h3>${name3}</h3>
<h4>${name4}</h4>

EL表达式

EL表达式:获取数据,执行运算,获取web开发的常用对象
<jsp:forward page="/test.jsp">
    <jsp:param name="name" value="xiaoma"/>
    <jsp:param name="phone" value="13511112222"/>
</jsp:forward>
EL表达式获取参数:<%= request.getParameter("name")%>
EL表达式获取表单数据:${param.参数名}

JSTL表达式

JSP标签集货,封装了JSP应用的通用核心功能
  1. 引用核心标签库:

    <%@taglib prefix="c" uri="http://java.sun.com/jstl/core" %>
  2. 常用标签

    <%--判断表单参数--%>
    <c:if test="${param.name} == 'admin'">
        <c:out value="登录成功"></c:out>
    </c:if>
    
    <%--其他--%>
    <c:choose>
    <c:when>
    <c:set>
    <c:forEach var="item" items="${list}">

JavaBean

一般用来做数据库字段做映射ORM(对象关系映射):表 -> 类,字段 -> 属性,行记录 -> 对象
  1. 必须有一个无参构造
  2. 属性必须私有化
  3. 必须有对应的get/set方法
class People {
        private int id;
        private String name;
        private int age;
}

### 过滤器 Filter

  1. 过滤器中的代码,在过滤特定请求时都会执行
  2. 必须要让过滤器继续通行

cn/itxiaoma/filter/TestFilter.java

package cn.itxiaoma.filter;
import javax.servlet.*;
import java.io.IOException;
public class TestFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("过滤器开始");
    }
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        System.out.println("过滤器执行前...");
        chain.doFilter(request, response);//让过滤器继续执行
        System.out.println("过滤器执行后...");
    }
    @Override
    public void destroy() {
        System.out.println("过滤器销毁");
    }
}

src/main/webapp/WEB-INF/web.xml

<filter>
  <filter-name>TestFilter</filter-name>
  <filter-class>cn.itxiaoma.filter.TestFilter</filter-class>
</filter>
<filter-mapping>
  <filter-name>TestFilter</filter-name>
  <url-pattern>/*</url-pattern>
</filter-mapping>

监听器 Listener

public class TestListener implements HttpSessionListener {
    ...
}
<!--注册监听器-->
<listener>
  <listener-class>cn.itxiaoma.listener.TestListener</listener-class>
</listener>

Filter实现权限拦截

src/main/webapp/login.jsp

<form action="servlet/login" method="post">
    <input type="text" name="username"/>
    <input type="submit" value="Login">
</form>

src/main/webapp/WEB-INF/web.xml

<?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"
         metadata-complete="true">
  <servlet>
    <servlet-name>LoginServlet</servlet-name>
    <servlet-class>cn.itxiaoma.servlet.LoginServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>LoginServlet</servlet-name>
    <url-pattern>/servlet/login</url-pattern>
  </servlet-mapping>
  <filter>
    <filter-name>SysFilter</filter-name>
    <filter-class>cn.itxiaoma.filter.SysFilter</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>SysFilter</filter-name>
    <url-pattern>/sys/*</url-pattern>
  </filter-mapping>
</web-app>

cn/itxiaoma/servlet/LoginServlet.java

package cn.itxiaoma.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 LoginServlet extends HttpServlet {
    //get和post只是请求实现的不同方式,业务逻辑一样,因此可以互相调用
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        if (username.equals("admin")) {
            req.getSession().setAttribute("USER_SESSION", req.getSession().getId());
            resp.sendRedirect("/sys/success.jsp");
        }else{
            resp.sendRedirect("/error.jsp");
        }
    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}

cn/itxiaoma/filter/SysFilter.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    HttpServletRequest req = (HttpServletRequest) request;
    HttpServletResponse resp = (HttpServletResponse) response;
    if (req.getSession().getAttribute("USER_SESSION") == null) {
        resp.sendRedirect("/error.jsp");
    }
    chain.doFilter(request, response);
}

IT小马
1.2k 声望166 粉丝

Php - Go - Vue - 云原生