Servlet(JSP)学习笔记

IDEA配置



然后可以看到默认给你一个Hello World
然后注意端口占用的问题


JSP基本语法

page指令

Language:定义要使用的脚本语言,默认为java
contentType:定义jsp字符的编码和页面相应的MIME类型
pageEncodeing:定义jsp页面的字符集编码

ScriptLet标签

作用:在jsp中嵌入java代码
<%! %> 定义全局变量,方法,类
<% %>定义局部变量,方法,类
<%= %>输出一个变量或者具体内容

注释

html可见

<%-- --%> html不可见

包含

静态包含: <%@include file="文件地址" %> 先包含,再编译处理
动态包含: <jsp:include page="文件地址" > 先编译处理,再包含

跳转

forward1.jsp

    <jsp:forward page="forward2.jsp">
        <jsp:param name="username" value="java"/>
        <jsp:param name="password" value="123456"/>
    </jsp:forward>

forward2.jsp

    username:<%=request.getParameter("username")%>
    password:<%=request.getParameter("password")%>

JSP四大作用域

application

有效范围是整个应用,从应用启动到应用结束

  <%
    application.setAttribute("application","applicationValue");
  %>
    <%
        String applicationValue=(String) application.getAttribute("application");
    %>
    <%=applicationValue%>
    <%
        String applicationValue=(String) application.getAttribute("application");
    %>
    <%=applicationValue%>

session

有效范围是当前会话,从用户打开浏览器开始到用户关闭浏览器这段时间
代码中application换成session
换一个浏览器就会变成null

request

有效范围是一次请求

  <%
    request.setAttribute("request","requestValue");
  %>
    <%
        String requestValue=(String) request.getAttribute("request");
    %>
    <%=requestValue%>
    <jsp:forward page="requestScope2.jsp"></jsp:forward>
    <%
        String requestValue=(String) request.getAttribute("request");
    %>
    <%=requestValue%>

page

有效范围仅限于用户请求的当前页面

JSP九大内置对象

response

response代表的是对客户端的响应,主要是将JSP容器处理过的对象传回到客户端。response对象也具有作用域,它只在JSP页面内有效
自动刷新应用,页面重定向,操作cookie
自动刷新应用(没隔一秒)

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page import="java.util.*"%>
<html>
<head>
    <title>Title</title>
    <%
        response.setHeader("refresh","1");
        Date now=new Date();
    %>
</head>
<body>
当前时间:<%=now.toLocaleString()%>
</body>
</html>

页面重定向(无法传参)

<%
    response.sendRedirect("index.jsp");
%>

简单登录
responseLogin.jsp

<%--
  Created by IntelliJ IDEA.
  User: Initial
  Date: 2024-01-05
  Time: 13:16
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
  <%
    String username=null;
    String password=null;
    Cookie[] cookies=request.getCookies();
    for(int i=0;cookies!=null && i<cookies.length;i++){
      if(cookies[i].getName().equals("userNameAndPassword")){
        username=cookies[i].getValue().split("xxx")[0];
        password=cookies[i].getValue().split("xxx")[1];
      }
    }
    if(username==null){
      username="";
    }
    if(password==null){
      password="";
    }
  %>
</head>
<body>
<form action="responseMain.jsp" method="get">
  <table>
    <tr>
      <td>用户名</td>
      <td><input type="text" name="username" id="username" value="<%=username%>" placeholder="请输入用户名"/> </td>
    </tr>
    <tr>
      <td>密码</td>
      <td><input type="password" name="password" id="password" value="<%=password%>" placeholder="请输入密码"/> </td>
    </tr>
    <tr>
      <td><input type="checkbox" name="remember" id="remember" value="rememberMe"/></td>
      <td>记住密码</td>
    </tr>
    <tr>
      <td><input type="submit" value="登录"/> </td>
      <td><input type="reset" value="重置"/></td>
    </tr>
  </table>
</form>
</body>
</html>

responseMain.jsp

<%--
  Created by IntelliJ IDEA.
  User: Initial
  Date: 2024-01-05
  Time: 13:22
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
    <%
        String username=(String) request.getParameter("username");
        String password=(String) request.getParameter("password");
        String remember=(String) request.getParameter("remember");
        if(remember.equals("rememberMe")){
            Cookie userNameAndPassword=new Cookie("userNameAndPassword",username+"xxx"+password);
            userNameAndPassword.setMaxAge(1*24*60*60);
            response.addCookie(userNameAndPassword);
        }
        System.out.println("到此一游");
        response.sendRedirect("responseLogin.jsp");
    %>
</head>
<body>
username:<%=username%><br>
password:<%=password%><br>
remember:<%=remember%><br>
</body>
</html>

out

out对象用于在web浏览器内输出信息,并且管理应用服务器上的输出缓冲区。在使用out对象输出数据时,可以对数据缓冲区进行操作,及时
清除缓冲区中的残余数据,为其他的输出让出缓冲空间。待数据输出完毕后,要及时关闭输出流。
导入tomcat中的jsp-api和servlet-api包

pageContext

pageContext对象的作用是取得任何范围的参数,通过它可以获取JSP页面的out,request,reponse,session,application等对象
pageContext对象的创建和初始化都是由容器来完成的,在jsp页面可以直接使用pageContext对象

<%
    pageContext.setAttribute("pageContext","pageContext");
    request.setAttribute("request","request");
    session.setAttribute("session","session");
    application.setAttribute("application","application");

    String pageContextValue=(String) pageContext.getAttribute("pageContext");
    String requestValue=(String) pageContext.getRequest().getAttribute("request");
    String sessionValue=(String) pageContext.getSession().getAttribute("session");
    String applicationValue=(String) pageContext.getServletContext().getAttribute("application");
%>
<%=pageContextValue%>
<%=requestValue%>
<%=sessionValue%>
<%=applicationValue%>

config

config对象的主要作用是取得服务器的配置信息。通过pageContext对象的getServletConfig()方法可以获取一个config对象
当一个Servlet初始化时,容器把某些信息通过config对象传递给这个Servlet.开发者可以在web.xml文件中为应用程序环境中的Servlet
程序和JSP页面提供初始化参数
config1.jsp

<%response.sendRedirect("config2");%>

config2.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
    <%
        String a=config.getInitParameter("key");
    %>
</head>
<body>
<%=a%>
</body>
</html>

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">
    <servlet>
        <servlet-name>config2</servlet-name>
        <jsp-file>/config2.jsp</jsp-file>
        <init-param>
            <param-name>key</param-name>
            <param-value>123456</param-value>
        </init-param>
    </servlet>
    <servlet-mapping>
        <servlet-name>config2</servlet-name>
        <url-pattern>/config2</url-pattern>
    </servlet-mapping>
</web-app>

exception

exception.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page errorPage="error.jsp"%>
<html>
<head>
    <title>Title</title>
</head>
<body>
<%
    int a=1;
    int b=0;
    int c=a/b;
%>
</body>
</html>

error.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page isErrorPage="true"%>
<html>
<head>
    <title>Title</title>
</head>
<body>
您的程序出错了
<%
    if(exception!=null){
        out.println("错误信息:");
        out.println(exception.getMessage());
    }
%>
</body>
</html>

JavaBean组件

JavaBean组件引入

JavaBean是使用Java语言开发的一个可重用的组件,在JSP开发中可以使用JavaBean减少重复代码,使得整个JSP代码的开发更加灵活简洁

创建JavaBean

<jsp:userBean id="实例化对象的名称" scope="保存范围(默认page)" class="类完整名称"/>

设置属性值

<jsp:setProperty property="属性名称" name="实例化对象的名称" value="属性的值" param="参数名称"/>
Property="*" 匹配所以的属性



或者

获取属性值

<jsp:getProperty property="属性名称" name="实例化对象的名称"/>

JavaBean的保存范围

page,request,session,application

JavaBean的删除

作用域对象,removeAttribute("javabean的名称");
<%
pageContext.removeAttribute("teacher");
%>

Servlet

HelloWorld

ctrl+o快速调出重写方法
注意编码问题

配置映射

生命周期

Servlet类加载->实例化->服务->销毁

两种页面跳转方式

客户端跳转:不能获取request中的参数,能获取session,application中的参数
response.sendRedirect("目标地址")
服务端跳转:能获取request中的参数,也能获取session,application中的参数

        RequestDispatcher rd=request.getRequestDispatcher("main.jsp");
        rd.forward(request,response);

demo代码

package com.example.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 javax.servlet.http.HttpSession;
import java.io.IOException;

public class ServerSkipServlet extends HttpServlet {

    private static final long serialVersionUID = 6436509275737527901L;

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request,response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setAttribute("request","requestValue");
        HttpSession session= request.getSession();
        session.setAttribute("session","sessionValue");
        ServletContext application= request.getServletContext();
        application.setAttribute("application","applicationValue");
        //客户端跳转 response.sendRedirect("main.jsp");
        //服务端跳转
        RequestDispatcher rd=request.getRequestDispatcher("main.jsp");
        rd.forward(request,response);
    }
}

main.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<%
  String requestValue=(String) request.getAttribute("request");
  String sessionValue=(String) session.getAttribute("session");
  String applicationValue=(String) application.getAttribute("application");
%>
<%=requestValue%>
<%=sessionValue%>
<%=applicationValue%>
</body>
</html>

JSP&Servlet实现用户登录

index.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>用户登录</title>
</head>
<body>
<form action="login" method="post">
    <table>
        <tr>
            <td>用户名:</td>
            <td><input type="text" name="username"/></td>
        </tr>
        <tr>
            <td>密码:</td>
            <td><input type="password" name="password"/></td>
        </tr>
        <tr>
            <td><input type="submit" value="提交"/></td>
            <td><input type="reset" value="重置"/></td>
        </tr>
        <tr>
            <td></td>
            <td>
                <%
                    String msg=(String) request.getAttribute("msg");
                    if(msg==null){
                        msg="";
                    }
                %>
                <%=msg%>
            </td>
        </tr>
    </table>
</form>
</body>
</html>

java

package com.example.servlet;

import com.example.entity.User;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;


public class LoginServlet extends HttpServlet{

    /**
     *
     */
    private static final long serialVersionUID = 1L;

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username=request.getParameter("username");
        String password=request.getParameter("password");
        HttpSession session=request.getSession();
        if(username.equals("admin") && password.equals("123456")){
            User currentUser=new User();
            currentUser.setUsername(username);
            currentUser.setPassword(password);
            session.setAttribute("currentUser", currentUser);
            response.sendRedirect("login.jsp");
        }else{
            request.setAttribute("msg", "用户名或密码错误!");
            RequestDispatcher rd=request.getRequestDispatcher("index.jsp");
            rd.forward(request, response);
        }
    }
}

login.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8"%>
<%@ page import="com.example.entity.User" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>主页</title>
</head>
<body>
欢迎您!!!<%User currentUser=(User)session.getAttribute("currentUser"); %><%=currentUser.getUsername() %>
</body>
</html>

User.java

package com.example.entity;

public class User {

    private Integer id;
    private String username;
    private String password;
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }


}

web.xml

    <servlet>
        <servlet-name>LoginServlet</servlet-name>
        <servlet-class>com.example.servlet.LoginServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>LoginServlet</servlet-name>
        <url-pattern>/login</url-pattern>
    </servlet-mapping>

Servlet过滤器

web.xml添加过滤器

    <filter>
        <filter-name>LoginFilter</filter-name>
        <filter-class>com.example.filter.LoginFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>LoginFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

过滤器demo代码

package com.example.filter;

import com.example.entity.User;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class LoginFilter implements Filter{

    @Override
    public void destroy() {
    }

    @Override
    public void init(FilterConfig arg0) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
            throws IOException, ServletException {
        HttpServletRequest request=(HttpServletRequest)servletRequest;
        HttpServletResponse response=(HttpServletResponse)servletResponse;
        HttpSession session=request.getSession();
        User currentUser=(User)session.getAttribute("currentUser");
        String path=request.getServletPath();
        if(currentUser==null&& !path.contains("login")){
            RequestDispatcher rd=request.getRequestDispatcher("index.jsp");
            rd.forward(request, response);
        }else{
            filterChain.doFilter(servletRequest, servletResponse);
        }
    }
}

Servlet监听器

web.xml中配置

    <listener>
        <listener-class>com.example.listener.SessionListener</listener-class>
    </listener>

监听器demo代码

package com.example.listener;

import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;

public class SessionListener implements HttpSessionAttributeListener {
    @Override
    public void attributeAdded(HttpSessionBindingEvent event) {
        System.out.println("在session里面添加了值,键为: "+event.getName()+" 值为: "+event.getValue());
    }

    @Override
    public void attributeRemoved(HttpSessionBindingEvent event) {

    }

    @Override
    public void attributeReplaced(HttpSessionBindingEvent event) {

    }
}

EL表达式

内置对象

EL表达式访问范围属性

page->request->session->application

EL表达式接收请求参数

param:单个参数
paramValues:数组参数



EL表达式对象操作

EL表达式集合操作

EL表达式运算符操作

posted @ 2024-01-05 21:44  BattleofZhongDinghe  阅读(10)  评论(0编辑  收藏  举报