【NEW10】Servlet高级的综合案例及JDBC入门

回顾上节课的知识


演示Filer程序如何对Servlet程序的调用进行拦截:

在这里插入图片描述
用于拦截myServlet类的myFilter类:

在这里插入图片描述
在web.xml里设置它所能拦截的资源。

在这里插入图片描述

使用Filter实现用户的自动登录


在这里插入图片描述

1.准备登录和主页面:login.jsp index.jsp

在这里插入图片描述

<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8" import="java.util.*"
%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<head>
<title>显示登录的用户信息</title>
</head>
<body>
	<br />
	<center>
		<h3>欢迎光临</h3>
	</center>
	<br />
		<c:choose>
			<c:when test="${sessionScope.user==null }">
					<a href="http://localhost:9999/chapter08/login.jsp">用户登录</a>
			
			</c:when>
			<c:otherwise>
				欢迎您:${sessionScope.user.username}    <a href="http://localhost:9999/chapter08/LogoutServlet">退出</a>
			</c:otherwise>
		</c:choose>
	<hr />
</body>
</html>

在这里插入图片描述

<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8" import="java.util.*"%>
<html>
<head></head>
<center><h3>用户登录</h3></center>
<body style="text-align: center;">
<form action="${pageContext.request.contextPath }/LoginServlet" 
method="post">
<table border="1" width="600px" cellpadding="0" cellspacing="0" 
align="center" >
	<tr>
		<td height="30" align="center">用户名:</td>
		<td>&nbsp;&nbsp;
        <input type="text" name="username" />${errorMsg }</td>
	</tr>
	<tr>
		<td height="30" align="center">&nbsp; 码:</td>
		<td>&nbsp;&nbsp;
          <input type="password" name="password" /></td>
	</tr>
	<tr>
		<td height="35" align="center">自动登录时间</td>
		<td><input type="radio" name="autologin" 
                  value="${60*60*24*31 }" />一个月
			<input type="radio" name="autologin" 
                  value="${60*60*24*31*3 }" />三个月
			<input type="radio" name="autologin" 
                  value="${60*60*24*31*6 }" />半年
			<input type="radio" name="autologin" 
                  value="${60*60*24*31*12 }" />一年
		</td>
	</tr>
	<tr>
		<td height="30" colspan="2" align="center">
			      <input type="submit" value="登录" />
              &nbsp;&nbsp;&nbsp;&nbsp;
			<input type="reset" value="重置" />
		</td>
	</tr>
</table>
</form>
</body>
<html>

2.创建一个User类,来封装用户名和密码。

在这里插入图片描述

package cn.itcast.chapter08.filter;

public class User {
	private String username;
	private String password;
	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;
	}
	

}

3.创建LoginServlet,处理登录请求。

在这里插入图片描述

package cn.itcast.chapter08.filter;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class LoginServlet
 */
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
  
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// 1.获取用户名和密码
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		//2.判断用户名和密码是否正确
		if("dashuju".equals(username) && "123".equals(password)){
			//用户名和密码正确
			User u = new User();
			u.setUsername(username);
			u.setPassword(password);
			//在index.jsp主页面,回显用户信息
			request.getSession().setAttribute("user",u);
			//3.获取用户是否登录的标识符
			String autologin = request.getParameter("autologin");
			if(autologin!=null){
				//点击自动登录,把用户信息保存到cookie里面,在AutoLoginFilter使用
				Cookie c= new Cookie("autoLogin",username+"-"+password);
				int time = Integer.parseInt(autologin);
				c.setMaxAge(time);
				c.setPath(request.getContextPath());
				response.addCookie(c);
				
			}
			//重定向主页面,回显用户信息
			response.sendRedirect(request.getContextPath()+"/index.jsp");
			
		}else{
			//登录失败
			request.setAttribute("errorMsg", "用户名或密码错误");
			RequestDispatcher rd = request.getRequestDispatcher("/login.jsp");
			rd.forward(request, response);
			
		}
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
	}

	/**
	 * @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);
	}

}

4.创建一个LogoutServlet,处理退出请求。

在这里插入图片描述

package cn.itcast.chapter08.filter;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class LogoutServlet
 */
public class LogoutServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
   

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// 1.清除session保存的用户信息
		 request.getSession().removeAttribute("user");
		//2. 清除cookie
		 Cookie c =  new Cookie("autoLogin","");
		 c.setMaxAge(0);
		 c.setPath(request.getContextPath());
		 response.addCookie(c);
		 //3.重定向到主页面
		  response.sendRedirect("/chapter08/index.jsp");
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

}

5.创建一个AutoLoginFilter,完成自动登录。

在这里插入图片描述

package cn.itcast.chapter08.filter;

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.http.Cookie;
import javax.servlet.http.HttpServletRequest;

/**
 * Servlet Filter implementation class AutoLoginFilter
 */
public class AutoLoginFilter implements Filter {

  

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
		// TODO Auto-generated method stub
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		//1.获取所有的cookie
		HttpServletRequest req = (HttpServletRequest)request;
		Cookie[] cs = req.getCookies();
		//2.遍历cookie,找到保存用户名和密码的那个cookie
		String autoLogin=null;
		for(int i =0;cs!=null && i<cs.length;i++){
			String cookieName = cs[i].getName();
			if("autoLogin".equals(cookieName)){
				//找到了保存用户名和密码的cookie
				autoLogin = cs[i].getValue();
			}
			
		}
		//3.如果获取到用户名密码不为空,实现自动登录
		if(autoLogin!=null){
			//判断用户名和密码是否正确
			String[]  strs = autoLogin.split("-");
			String username =strs[0];
			String password =strs[1];
			
			System.out.println("username"+username);
			
			System.out.println("password"+password);
			
			
			
			if("dashuju".equals(username) && "123".equals(password)){
				//用户名和密码正确
				User u = new User();
				u.setUsername(username);
				u.setPassword(password);
				//在index.jsp主页面,回显用户信息
				req.getSession().setAttribute("user",u);
			}
		}
		
		
		chain.doFilter(request, response);
		
		
		
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
		// TODO Auto-generated method stub
	}

}

运行结果:

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

Listenter 监听器


在这里插入图片描述

package cn.itcast.chapter08.listener;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

/**
 * Application Lifecycle Listener implementation class myListenr
 *
 */
public class myListenr implements ServletContextListener, HttpSessionListener, ServletRequestListener {

    /**
     * Default constructor. 
     */
    public myListenr() {
        // TODO Auto-generated constructor stub
    	System.out.println("监听器被创建了-----");
    }

	/**
     * @see HttpSessionListener#sessionCreated(HttpSessionEvent)
     */
    public void sessionCreated(HttpSessionEvent arg0)  { 
         // TODO Auto-generated method stub
    	System.out.println("sessionCreated-----");
    }

	/**
     * @see ServletRequestListener#requestDestroyed(ServletRequestEvent)
     */
    public void requestDestroyed(ServletRequestEvent arg0)  { 
         // TODO Auto-generated method stub
    	System.out.println("requestDestroyed-----");
    }

	/**
     * @see ServletRequestListener#requestInitialized(ServletRequestEvent)
     */
    public void requestInitialized(ServletRequestEvent arg0)  { 
         // TODO Auto-generated method stub
    	System.out.println("requestInitialized-----");
    }

	/**
     * @see HttpSessionListener#sessionDestroyed(HttpSessionEvent)
     */
    public void sessionDestroyed(HttpSessionEvent se)  { 
         // TODO Auto-generated method stub
    	System.out.println("sessionDestroyed-----");
    }

	/**
     * @see ServletContextListener#contextDestroyed(ServletContextEvent)
     */
    public void contextDestroyed(ServletContextEvent arg0)  { 
         // TODO Auto-generated method stub
    	System.out.println("contextDestroyed-----");
    }

	/**
     * @see ServletContextListener#contextInitialized(ServletContextEvent)
     */
    public void contextInitialized(ServletContextEvent arg0)  { 
         // TODO Auto-generated method stub
    	System.out.println("contextInitialized-----");
    }
	
}

在这里插入图片描述

<%@ 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>
</head>
<body>

测试监听对象的请求

<br/>

<a href="destroy.jsp">销毁session</a>
</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>
</head>
<body>
<%session.invalidate(); %>
</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>
</head>
<body>
测试域对象属性值的页面:
<%

application.setAttribute("username", "itcast");
application.setAttribute("username", "heima");
application.removeAttribute("username");


session.setAttribute("username", "itcast");
session.setAttribute("username", "heima");
session.removeAttribute("username");


request.setAttribute("username", "itcast");
request.setAttribute("username", "heima");
request.removeAttribute("username");
%>






</body>
</html>

在这里插入图片描述

package cn.itcast.chapter08.listener;

import javax.servlet.ServletContextAttributeEvent;
import javax.servlet.ServletContextAttributeListener;
import javax.servlet.ServletRequestAttributeEvent;
import javax.servlet.ServletRequestAttributeListener;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;

/**
 * Application Lifecycle Listener implementation class MyAttributeListener
 *
 */
public class MyAttributeListener implements ServletContextAttributeListener, HttpSessionAttributeListener, ServletRequestAttributeListener {

    /**
     * Default constructor. 
     */
    public MyAttributeListener() {
        // TODO Auto-generated constructor stub
    }

	/**
     * @see ServletContextAttributeListener#attributeAdded(ServletContextAttributeEvent)
     */
    public void attributeAdded(ServletContextAttributeEvent arg0)  { 
         // TODO Auto-generated method stub
    	System.out.println("Context---attributeAdded");
    }

	/**
     * @see ServletContextAttributeListener#attributeRemoved(ServletContextAttributeEvent)
     */
    public void attributeRemoved(ServletContextAttributeEvent arg0)  { 
         // TODO Auto-generated method stub
    	System.out.println("Context---attributeRemoved");
    }

	/**
     * @see ServletRequestAttributeListener#attributeRemoved(ServletRequestAttributeEvent)
     */
    public void attributeRemoved(ServletRequestAttributeEvent arg0)  { 
         // TODO Auto-generated method stub
    	System.out.println("Request---attributeRemoved");
    }

	/**
     * @see ServletRequestAttributeListener#attributeAdded(ServletRequestAttributeEvent)
     */
    public void attributeAdded(ServletRequestAttributeEvent arg0)  { 
         // TODO Auto-generated method stub
    	System.out.println("Request---attributeAdded");
    }

	/**
     * @see ServletRequestAttributeListener#attributeReplaced(ServletRequestAttributeEvent)
     */
    public void attributeReplaced(ServletRequestAttributeEvent arg0)  { 
         // TODO Auto-generated method stub
    	System.out.println("Request---attributeReplaced");
    }

	/**
     * @see HttpSessionAttributeListener#attributeAdded(HttpSessionBindingEvent)
     */
    public void attributeAdded(HttpSessionBindingEvent arg0)  { 
         // TODO Auto-generated method stub
    	System.out.println("Session---attributeAdded");
    }

	/**
     * @see HttpSessionAttributeListener#attributeRemoved(HttpSessionBindingEvent)
     */
    public void attributeRemoved(HttpSessionBindingEvent arg0)  { 
         // TODO Auto-generated method stub
    	System.out.println("Session---attributeRemoved");
    }

	/**
     * @see HttpSessionAttributeListener#attributeReplaced(HttpSessionBindingEvent)
     */
    public void attributeReplaced(HttpSessionBindingEvent arg0)  { 
         // TODO Auto-generated method stub
    	System.out.println("Session---attributeReplaced");
    }

	/**
     * @see ServletContextAttributeListener#attributeReplaced(ServletContextAttributeEvent)
     */
    public void attributeReplaced(ServletContextAttributeEvent arg0)  { 
         // TODO Auto-generated method stub
    	System.out.println("Context---attributeReplaced");
    }
	
}

运行结果:
在这里插入图片描述
在这里插入图片描述
所用到的web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>chap08</display-name>
  <welcome-file-list>
    <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>default.jsp</welcome-file>
  </welcome-file-list>
  <servlet>
    <description></description>
    <display-name>LoginServlet</display-name>
    <servlet-name>LoginServlet</servlet-name>
    <servlet-class>cn.itcast.chapter08.filter.LoginServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>LoginServlet</servlet-name>
    <url-pattern>/LoginServlet</url-pattern>
  </servlet-mapping>
  <servlet>
    <description></description>
    <display-name>LogoutServlet</display-name>
    <servlet-name>LogoutServlet</servlet-name>
    <servlet-class>cn.itcast.chapter08.filter.LogoutServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>LoginServlet</servlet-name>
    <url-pattern>/LogoutServlet</url-pattern>
  </servlet-mapping>
  <filter>
    <display-name>AutoLoginFilter</display-name>
    <filter-name>AutoLoginFilter</filter-name>
    <filter-class>cn.itcast.chapter08.filter.AutoLoginFilter</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>AutoLoginFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
  <listener>
    <listener-class>cn.itcast.chapter08.listener.myListenr</listener-class>
  </listener>
  <listener>
    <listener-class>cn.itcast.chapter08.listener.MyAttributeListener</listener-class>
  </listener>
</web-app>




JDBC技术


在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值