欢迎来到Jsp编程课时十——Servlect+Jsp基础回顾。(二)

简介: 欢迎来到Jsp编程课时十——Servlect+Jsp基础回顾。(二)

模块五Servlect对象五Cookie和Session对象。

package com.Servlect;
/**
 * A202020895
 * 10/29
 * 
 */
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
 * Servlet implementation class Demo01Servlet
 */
@WebServlet("/CookieServlet")
public class CookieServlet extends HttpServlet {
  private static final long serialVersionUID = 1L;
    /**
     * @see HttpServlet#HttpServlet()
     */
    public CookieServlet() {
        super();
        // TODO Auto-generated constructor stub
    }
  /**
   * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
   */
  protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
    response.getWriter().append("Served at: ").append(request.getContextPath());
  }
  /**
   * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
   */
  protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    //获取文本框中的内容
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        //首先判断账号密码是否正确
        if("hug".equals(username) && "123456".equals(password)){
            //登录成功之后判断用户是否点击了记住我
            String remember = request.getParameter("remember");
            if (remember != null) { //因为单选框默认是null,选上了之后value是on
                //如果用户点击了,就存到Cookie中
                Cookie cookie = new Cookie("username",username);
                Cookie cookie1 = new Cookie("password",password);
                //设置访问路径
                cookie.setPath(request.getContextPath()+"/index.html");
                cookie1.setPath(request.getContextPath()+"/index.html");
                //设置生存时间
                cookie.setMaxAge(60);
                cookie1.setMaxAge(60 * 60 * 24);
                //把cookie内容传到浏览器响应头
                response.addCookie(cookie);
                response.addCookie(cookie1);
            }
            //登录成功,跳转到成功页面
            response.sendRedirect("ServlectA");
        }else{
            //登录失败,跳转到失败页面
          System.out.println("登录失败,跳转到失败页面");
            response.sendRedirect("ServlectB");
        }
    }
}
package com.Servlect;
/**
 * 作业:创建一个新项目,仿QQ登录,
完成浏览器上的登录功能,
并使用session对象完成记住密码和
自动登录功能.
 */
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
 * A202020895
 * 10/29
 * 
 */
/**
 * Servlet implementation class sessionDemo1
 */
@WebServlet("/sessionDemo1")
public class sessionDemo1 extends HttpServlet {
  private static final long serialVersionUID = 1L;
    /**
     * @see HttpServlet#HttpServlet()
     */
    public sessionDemo1() {
        super();
        System.out.println("进入sessionDemo1登录界面");
        System.out.println("这里sessionDemo1运行的抽象方方");
        // TODO Auto-generated constructor stub
    }
    @Override
    public void init(ServletConfig config) throws ServletException {
      // TODO Auto-generated method stub
      super.init(config);
      System.out.println("这里是init方法用来加载数据");
    }
  /**
   * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
   */
  protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
    response.getWriter().append("Served at: ").append(request.getContextPath());
  }
  /**
   * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
   */
  protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    //因为有密码,为了安全保障用do-post方法
    response.setContentType("text/html");
    response.setCharacterEncoding("UTF-8");
    //首先获取文本框
     String username = request.getParameter("username");
       String password = request.getParameter("password");
       /*
        * 创建对象HttpSession
        */
       HttpSession session=request.getSession();
       /**
        * 建立二个动态数据
        */
       session.setAttribute("username", "hug");
     session.setAttribute("password", "123");
     /**
      * 获得动态数据
      */
      String a=(String) session.getAttribute("username");
      String b=(String) session.getAttribute("password");
     String aa=request.getParameter("username");
     String bb=request.getParameter("password");
     System.out.println(aa+"获得浏览器index.jsp文件中数据");
     System.out.println(bb+"获得浏览器index.jsp文件中数据");
     PrintWriter pw =response.getWriter();
     if (session.isNew()) {
        pw.print("浏览器是第一次访问服务器");
      }else if (a.equals(aa)&&b.equals(bb)) {
        /**
         * 判断浏览器与我创建的服务器中的数据是否相等
         */
        pw.print("浏览器是第一次访问服务器");
                  response.sendRedirect("ServlectA");
              }else{
                  //登录失败,跳转到失败页面
                System.out.println("登录失败,跳转到失败页面");
                  response.sendRedirect("ServlectB");
                }   
              }
  @Override
  public void destroy() {
    // TODO Auto-generated method stub
    super.destroy();
    System.out.println("运行完毕后销毁servlect");
  }
         }
<!DOCTYPE html>
<html>
<head>
 <meta charset="UTF-8">
    <title>用户登录</title>
<meta charset="UTF-8">
<title>Insert title here</title>
<style type="text/css">
  .*{
  font-size:20px;
  font-weight: 20px; 
  border: 5px;
  }
</style>
</head> 
<body>
<h2  style='color:green' align ='center'>用户登录</h2>
<form action="CookieServlet" method="post" id="loginForm" style='color:brown' align ='center'>
    <table style='color:brown' align ='center'>
        <tr>
            <td width="60">用户名</td>
            <td><input type="text" name="username" id="username"/></td>
        </tr>
        <tr>
            <td>密码</td>
            <td><input type="password" name="password" id="password"/></td>
        </tr>
        <tr>
            <td>记住我</td>
            <!--没有value属性的前提下,点中它的值是on-->
            <td><input type="checkbox" name="remember" /></td>
        </tr>
        <tr>
            <td colspan="2" align="center"><input type="submit" value="登录"/></td>
        </tr>
    </table>
</form>
</body>
</html>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<style type="text/css">
  .*{
  font-size:20px;
  font-weight: 20px; 
  border: 5px;
  }
</style>
</head>
<body>
<h2  style='color:red' align ='center'>用户登录</h2>
<form action="sessionDemo1" method="post" id="loginForm" style='color:brown' align ='center'>
    <table style='color:brown' align ='center'>
        <tr>
            <td width="60">用户名</td>
            <td><input type="text" name="username" id="username"/></td>
        </tr>
        <tr>
            <td>密码</td>
            <td><input type="password" name="password" id="password"/></td>
        </tr>
        <tr>
            <td>记住我</td>
            <!--没有value属性的前提下,点中它的值是on-->
            <td><input type="checkbox" name="remember"/></td>
             <td>自动登录</td>
            <td><input type="checkbox" name="df"/></td>
        </tr>
        <tr>
            <td colspan="2" align="center"><input type="submit" value="登录"/></td>
        </tr>
    </table>
</form>
</body>
</html>

模块六:Servlect过滤器对象六(对比学习内容)

package co;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
 * Servlet implementation class Servlect2
 */
@WebServlet("/Servlect4")
public class Servlect4 extends HttpServlet {
  private static final long serialVersionUID = 1L;
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Servlect4() {
        super();
        System.out.println("这是Servlect4的抽象方法");
        // TODO Auto-generated constructor stub
    }
    @Override
    public void init() throws ServletException {
      // TODO Auto-generated method stub
      System.out.println("Servlect4加载数据");
      super.init();
    }
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
      // TODO Auto-generated method stub
      System.out.println("这里开始运行Servlect4的方法");
      super.service(req, resp);
    }
    @Override
    protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
      // TODO Auto-generated method stub
      super.doDelete(req, resp);
      System.out.println("Servlect4的删除方法");
    }
   @Override
    public void destroy() {
  // TODO Auto-generated method stub
  super.destroy();
  System.out.println("Servlect4销毁数据");
}
  /**
   * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
   */
  protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
  //response.getWriter().append("Served at: ").append(request.getContextPath());
    response.setContentType("text/html");
    response.setCharacterEncoding("UTF-8");
    PrintWriter pw =response.getWriter();
    pw.print("<h1>我是第一个servlect4</h1>");
  }
  /**
   * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
   */
  protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
    doGet(request, response);
  }
}
package com;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
/**
 * Servlet Filter implementation class MyFilter1
 */
//你要阻止Servlect2
@WebFilter("/Servlect2")
public class MyFilter1 implements Filter {
    /**
     * Default constructor. 
     */
    public MyFilter1() {
        // TODO Auto-generated constructor stub
      System.out.println("构造方法");
    }
  /**
   * @see Filter#destroy()
   */
  public void destroy() {
    // TODO Auto-generated method stub
    System.out.println("销毁数据");
  }
  /**
   * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
   */
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    response.setContentType("text/html");
    response.setCharacterEncoding("UTF-8");
    System.out.println("我是myfilter1开始拦截请求地址哦哦");
    //实施访问
    chain.doFilter(request, response);
  }
  /**
   * @see Filter#init(FilterConfig)
   */
  public void init(FilterConfig fConfig) throws ServletException {
    // TODO Auto-generated method stub
    System.out.println("加载数据");
  }
}

模块七listener对象七

package com.Listener;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
public class MyServlectListener implements ServletContextListener  {
  public MyServlectListener() {
    // TODO Auto-generated constructor stub
    System.out.println("MyServlectListener的构造方法");
  }
  @Override
  public void contextInitialized(ServletContextEvent sce) {
    System.out.println("Listener程序初始化程序开启");
    System.out.println("WEB ServletContextListener程序初始化程序开启ServletContext"
        + "Listener开始@@程序开始运行@@");
  }
  @Override
  public void contextDestroyed(ServletContextEvent sce) {
    System.out.println("Listener程序初始化程序结束");
    System.out.println("WEB contextDestroyed==程序初始化程序in the endontextDestroyed程序结束"
        + "程序在结束中");
  }
}
package com.Listener;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
public class MySessionListener implements  HttpSessionListener {
  private static int count=0;
  public MySessionListener() {
    // TODO Auto-generated constructor stub
    System.out.println("MySessionListener()   构造方法");
  }
  @Override
  public void sessionCreated(HttpSessionEvent se) {
    // TODO Auto-generated method stub
    System.out.println("当sesssion创建时执行程序 sessionCreated()构造方法");
    se.getSession().getServletContext().setAttribute("count", ++count);
  }
  @Override
  public void sessionDestroyed(HttpSessionEvent se) {
    System.out.println("当sesssion销毁时执行程序  sessionDestroyed()构造方法");
  }
}
package com.Listener;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionBindingListener;
public class User  implements HttpSessionBindingListener{
   @Override
      public void valueBound(HttpSessionBindingEvent event) {
          System.out.println("HttpSession 与 User 绑定");
          // 有用户登陆成功
          // 判断是否是第一个登陆的人
          ServletContext servletContext = event.getSession().getServletContext();
          Integer count = (Integer) servletContext.getAttribute("count");
          // 第一个登陆为1,非第一个则++
          count = null == count ? 1 : (count += 1);
          servletContext.setAttribute("count", count);
      }
      @Override
      public void valueUnbound(HttpSessionBindingEvent event) {
          System.out.println("HttpSession 与 User 解绑");
          // 有用户注销登陆
          ServletContext servletContext = event.getSession().getServletContext();
          Integer count = (Integer) servletContext.getAttribute("count");
          // count--是因为在同浏览器下重复登陆时session.setAttribute(name, value)
          // 每次会覆盖value值进而触发监听器valueBound()的count++
          servletContext.setAttribute("count", count);
      }
      //定义三个数据类型 
      private int id;
      private String username;
      private String password;
      public User() {
      }
      public User(int id, String username, String password) {
          this.id = id;
          this.username = username;
          this.password = password;
      }
      public int getId() {
          return id;
      }
      public void setId(int 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;
      }
      @Override
      public String toString() {
          return "User{" +
                  "id=" + id +
                  ", username='" + username + '\'' +
                  ", password='" + password + '\'' +
                  '}';
}
}
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" id="WebApp_ID" version="4.0">
  <display-name>ZhuJie</display-name>
  <welcome-file-list>
  <welcome-file>index.jsp</welcome-file>
  <welcome-file>ZhuJie</welcome-file>
 <!--    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file> -->
    <welcome-file>com.Listener.MyServlectListener</welcome-file>
       <welcome-file>com.Listener.MySessionListener</welcome-file>
  </welcome-file-list>
  <filter>
 <filter-name>MyFilter1</filter-name>
 <filter-class>com.Servlect.MyFilter1</filter-class>
   </filter>
 <filter-mapping>
    <filter-name>MyFilter1</filter-name>
    <!-- 这表示可以拦截任何请求 -->
    <url-pattern>/Servlect2</url-pattern>
  </filter-mapping>
  <!-- listener的注册 -->
  <listener>
  <listener-class>com.Listener.MyServlectListener</listener-class>
  </listener>
   <listener>
  <listener-class>com.Listener.MySessionListener</listener-class>
  </listener>
</web-app>

模块七jsp第一课的学习

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<style type="text/css">
*{
font-size: 30px;
}
</style>
<title>Insert title here</title>
</head>
<body>
<!--   application对象数据跟服务器有关 只要服务器不停址 数据都能共享  -->
<%--applicatio  --%>
<%
 //application.setAttribute("d", "我第四个数据");
/*  对象四 application*/
pageContext.setAttribute("d", "我是pageContext最大的数据,数据与服务器的关闭有关", pageContext.APPLICATION_SCOPE);
String d=(String)application.getAttribute("d");
out.write("<br>");
out.write(d);
%>
<%-- 对象三 pageContext --%>
<%
pageContext.setAttribute("aa", "我是pageContext数据中范围第四小的数据只能自己使用");
String aa=(String)pageContext.getAttribute("aa");
out.write("<br>");
out.write(aa);
%>
<%-- 对象二 request --%>
<%
  //request对象中的数据是可以形成多个页面共享数据,但是要通过请求转发的方式打开其他页面才能形成共享数据
  //写法一
  //request.setAttribute("b", "我是request的数据");
  //写法二
  //第一个参数表示要添加的数据的名称 第二个参数表示要存储的数据  第三个参数表示要把数据存储给哪个对象
  pageContext.setAttribute("bb", "我是request的存放的数据可以形成多个页面共享数据,但是要通过请求转发的方式打开其他页面才能形成共享数据", PageContext.REQUEST_SCOPE);
  String bb=(String)request.getAttribute("bb");
  out.write("<br>");
  out.write(bb);
  //通过请求转发的方式跳转至five.jsp
  /* request.getRequestDispatcher("b.jsp").forward(request, response);
 */
%>
<h1>获取到了对象四</h1>
<%
/* application 对象四   */
/* String d=(String)application.getAttribute("d"); */
String d=(String)pageContext.getAttribute("d",pageContext.APPLICATION_SCOPE);
out.write(d);
%>
<h1>获取了对象三</h1>
<%
String b = (String)pageContext.getAttribute("bb",pageContext.REQUEST_SCOPE);
out.write(b);
%>
<h1>对象二</h1>
<%
//方法一    request对象自己直接获得数据
//String b=(String)request.getAttribute("b");
//方法二   pageContext帮request获得数据
String c=(String)pageContext.getAttribute("b", PageContext.REQUEST_SCOPE);
out.write("我获得了four.jsp页面的request对象的数据:"+c);
%>
<form action="index.jsp" method="post" name="form1">
输入用户名称:
<input type="text" name="loginName" size="20"/>
<br>输入用户密码:
<input type="password" name="password" size="20"/>
<br>在次输入密码:
<input type="passwords" name="passwords" size="20"/>
<br>:输入信息:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
<input type="submit" name="submit" value="提交" size="12">
<input type="reset" name="reset" value="重值" size="12">
</form>
<h1 style="background-color: pink;align: center; text-align: center;">九九乘法表</h1>
<br>
<%for(int i=1;i<=9;++i){%>
<%for(int j=1;j<=i;++j){ %>
  <%=i+"*"+j+"="+i*j+" " %>
<%} %>
<br>
<%} %>
<hr>
</body>
</html>

目录
打赏
0
0
0
0
6
分享
相关文章
掌握JSP页面编程:动态生成Web内容
【4月更文挑战第3天】Java Server Pages (JSP) 是一种用于创建动态Web内容的Java技术,它结合HTML并允许在页面中嵌入Java代码。JSP支持代码片段、表达式语言(EL)和JSTL标签库,简化动态内容生成。当服务器接收到请求时,执行JSP中的Java代码并将结果嵌入HTML返回给客户端。示例展示了如何显示当前日期和时间。JSP可与Servlet、JavaBeans、数据库等结合,用于构建功能丰富的交互式Web应用。
180 5
JSP考试质量分析系统myeclipse开发mysql数据库bs框架java编程web网页结构
JSP 考试质量分析系统是一套完善的web设计系统,对理解JSP java编程开发语言有帮助,系统具有完整的源代码和数据库,开发环境为TOMCAT7.0,Myeclipse8.5开发,数据库为Mysql5.0,使用java语言开发,系统主要采用B/S模式开发。
243 1
JSP考试质量分析系统myeclipse开发mysql数据库bs框架java编程web网页结构
JSP 考试质量分析系统是一套完善的web设计系统,对理解JSP java编程开发语言有帮助,系统具有完整的源代码和数据库,开发环境为TOMCAT7.0,Myeclipse8.5开发,数据库为Mysql5.0,使用java语言开发,系统主要采用B/S模式开发。
177 0
JSP考试报名管理系统myeclipse开发mysql数据库bs框架java编程web网页结构
二、功能介绍 (1)权限管理:对权限信息进行添加、删除、修改和查看 (2)用户管理:对用户信息进行添加、删除、修改和查看 (3)公告管理:对公告信息进行添加、删除、修改和查看 (4)考试科目管理:对考试科目信息进行添加、删除、修改和查看 (5)考试安排管理:对考试安排信息进行添加、删除、修改和查看 (6)报名管理:对报名信息进行添加、删除、修改和查看,审核, (7)用户登录、身份验证 三、注意事项 1、管理员账号:admin密码:admin 数据库配置文件DBO.java 角色:普通用户,管理员 2、开发环境为TOMCAT7.0,Myeclipse8.5开发,数据库为Mysql
173 0
JSP在线客户服务支持管理系统myeclipse开发mysql数据库bs框架java编程jdbc
JSP 在线客户服务支持管理系统是一套完善的web设计系统,对理解JSP java编程开发语言有帮助,系统具有完整的源代码和数据库,系统主要采用B/S模式开发。
92 0
JSP 科研管理系统myeclipse开发mysql数据库bs框架java编程jdbc
JSP 科研管理系统是一套完善的web设计系统,对理解JSP java编程开发语言有帮助,系统具有完整的源代码和数据库,开发环境为TOMCAT7.0,Myeclipse8.5开发,数据库为Mysql5.0,使用java语言开发。系统主要采用B/S模式开发。
69 0
JSP实践教学平台系统myeclipse开发mysql数据库bs框架java编程jdbc
JSP 实践教学平台系统是一套完善的web设计系统,对理解JSP java编程开发语言有帮助,系统具有完整的源代码和数据库,开发环境为TOMCAT7.0,Myeclipse8.5开发,数据库为Mysql5.0,数据库文件名是jspskcsjpt.sql,系统名称kcsjpt,使用java语言开发系统主要采用B/S模式开发。
93 0
|
4月前
|
【学习笔记】Jsp与Servlet技术
【学习笔记】Jsp与Servlet技术
113 0
在Java服务器端开发的浩瀚宇宙中,Servlet与JSP犹如两颗璀璨的明星,它们联袂登场,共同编织出动态网站的绚丽篇章。
在Java服务器端开发的浩瀚宇宙中,Servlet与JSP犹如两颗璀璨的明星,它们联袂登场,共同编织出动态网站的绚丽篇章。
41 0
JSP+servlet+mybatis+layui服装库存管理系统(大三上学期课程设计)
这篇文章通过一个服装库存管理系统的实例,展示了在Spring Boot项目中使用Ajax、JSON、layui、MVC架构和iframe等技术,涵盖了注册登录、权限管理、用户管理、库存管理等功能,并提供了系统运行环境和技术要求的详细说明。
JSP+servlet+mybatis+layui服装库存管理系统(大三上学期课程设计)

相关实验场景

更多
AI助理

你好,我是AI助理

可以解答问题、推荐解决方案等