跟随小破站学习java web第十三天

本文详细解析了Java Web中会话管理和过滤器的实现方式,包括UUID生成、Session使用、过滤器设计及执行流程,展示了如何在Servlet中进行会话验证和请求过滤。

//获取UUID 转换为String类型 替换'-'

public static void main(String[] args) {
		
		String uuid = UUID.randomUUID().toString().replace("-","");
		
		System.out.println(uuid);
	}
<%@page import="java.util.UUID"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>登录页面</title>
</head>
<body>
	<%
		String uuid = UUID.randomUUID().toString().replace("-", "");
		session.setAttribute("uuid", uuid);
	%>
	<form action="ReSubServlet" method="post">
		<input type="hidden" value="<%=uuid %>" name="uuid2">
		<label>用户名称:</label>
		<input class="itxt" type="text" placeholder="请输入用户名" autocomplete="off" tabindex="1" name="username" />
		<br />
		<br />
		<label>用户密码:</label>
		<input class="itxt" type="password" placeholder="请输入密码" autocomplete="off" tabindex="1" name="password" />
		<br />
		<br />
		<input type="submit" value="登录" id="sub_btn" />
	</form>
</body>
</html>
public class ReSubServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession();
		//分别取session域和隐藏域中的uuid值
		String uuid2 = request.getParameter("uuid2");
		Object uuid = session.getAttribute("uuid");
		//判断是否相等
		if(uuid != null && uuid.toString().equals(uuid2)){
			//相等,提交,移除session域中的Token
			System.out.println("提交了!");
			session.removeAttribute("uuid");
		}
		
		System.out.println("end!");
	}

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

}

注意:在servlet中之所有不立即将uuid转换为String类型,是为了避免出现空值报错的情况!

1.导入jar包

2.设置web.xml

<servlet>
  	<servlet-name>KaptchaServlet</servlet-name>
  	<servlet-class>com.google.code.kaptcha.servlet.KaptchaServlet</servlet-class>
  </servlet>
  <servlet-mapping>
  	<servlet-name>KaptchaServlet</servlet-name>
  	<url-pattern>/code.jpg</url-pattern>
  </servlet-mapping>

3.页面修改

<label>验证码:</label>
<input class="itxt" type="text" style="width: 150px;" id="code"/>
<!-- 									sessionKey:KAPTCHA_SESSION_KEY -->
<img alt="" src="code.jpg" style="float: right; margin-right: 40px;width:80px;height:40px; ">

public class HelloWorldFilter implements Filter{

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		System.out.println("doFilter()!");
		//放行
		chain.doFilter(request, response);
	}

	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		
	}

}
<?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">
  <filter>
    <filter-name>HelloWorldFilter</filter-name>
    <filter-class>com.atguigu.filter.HelloWorldFilter</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>HelloWorldFilter</filter-name>
    <url-pattern>/HelloWorldFilter</url-pattern>
  </filter-mapping>
</web-app>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!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>Insert title here</title>
</head>
<body>
	<a href="HelloWorldFilter">HelloWorldFilter</a>
	<a href="UserServlet">userServlet</a>
</body>
</html>
public class UserServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		System.out.println("处理用户请求,做出响应!");
	}

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

}

修改WEB-INF 显示过滤功能 通过放行的方式可以使Servlet重新调用!

<?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">
  <filter>
    <filter-name>HelloWorldFilter</filter-name>
    <filter-class>com.atguigu.filter.HelloWorldFilter</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>HelloWorldFilter</filter-name>
    <url-pattern>/UserServlet</url-pattern>
  </filter-mapping>
  <servlet>
    <description></description>
    <display-name>UserServlet</display-name>
    <servlet-name>UserServlet</servlet-name>
    <servlet-class>com.atguigu.servlet.UserServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>UserServlet</servlet-name>
    <url-pattern>/UserServlet</url-pattern>
  </servlet-mapping>
</web-app>

即请求后先执行doFilter()放行前的代码,然后执行请求代码,再执行doFilter()放行后的代码,最后才是作出响应!

注意:当web.xml中,调整<Filter-mapping>的顺序,哪个url先被执行,就先调用哪个过滤器!

<?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">
  <filter>
    <filter-name>HelloWorldFilter</filter-name>
    <filter-class>com.atguigu.filter.HelloWorldFilter</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>HelloWorldFilter</filter-name>
    <url-pattern>/UserServlet</url-pattern>
  </filter-mapping>
  <servlet>
    <description></description>
    <display-name>UserServlet</display-name>
    <servlet-name>UserServlet</servlet-name>
    <servlet-class>com.atguigu.servlet.UserServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>UserServlet</servlet-name>
    <url-pattern>/UserServlet</url-pattern>
  </servlet-mapping>
  <filter>
    <display-name>UserServletFilter</display-name>
    <filter-name>UserServletFilter</filter-name>
    <filter-class>com.atguigu.filter.UserServletFilter</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>UserServletFilter</filter-name>
    <url-pattern>/UserServlet</url-pattern>
<!--     <url-pattern>/pages/user/*</url-pattern> -->
<!--     <url-pattern>*.jsp</url-pattern> -->
<!-- 	<servlet-name>UserServlet</servlet-name> -->
  </filter-mapping>
</web-app>

设计HttpFilter

public abstract class HttpFilter implements Filter {

	private FilterConfig filterConfig;
	
    public HttpFilter() {
        // TODO Auto-generated constructor stub
    }

	public void destroy() {
		// TODO Auto-generated method stub
	}

	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest)request;
		HttpServletResponse res = (HttpServletResponse)response;
		doFilter(req, res, chain);
	}
	
	public abstract void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException;
	
	public void init(FilterConfig fConfig) throws ServletException {
		this.filterConfig = fConfig;
	}

	/**
	 * 获取FilterConfig对象
	 * @return
	 */
	public FilterConfig getFilterConfig() {
		return filterConfig;
	}

}
public class HttpFilterTestFilter extends HttpFilter {

	@Override
	public void doFilter(HttpServletRequest request,HttpServletResponse response, FilterChain chain)throws IOException, ServletException {
		FilterConfig filterConfig2 = this.getFilterConfig();
		System.out.println("filterConfig2:"+filterConfig2);
		//放行
		chain.doFilter(request, response);
	}

}

注意:此时会出现404 原因是HttpFiler.java为abstract抽象类型,无需去web.xml中进行注册!

解决办法:去web.xml中删除关于HttpFilter的注册

注意:此时会出现第二个404 原因是没有书写Servlet,服务器无法对请求进行响应操作!

 解决办法:书写Servlet

public class HttpFilterTestFilter extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		System.out.println("处理请求");
	}

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

}

public class ApplicationListenerDemo implements ServletContextListener{

	@Override
	public void contextInitialized(ServletContextEvent sce) {
		System.out.println("application创建了!");
	}

	@Override
	public void contextDestroyed(ServletContextEvent sce) {
		System.out.println("application销毁了!");
	}

}
<?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">
  
  <listener>
  	<listener-class>com.atguigu.listener.ApplicationListenerDemo</listener-class>
  </listener>

</web-app>

 注意:Listener执行优先级>Filter>Servlet!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值