当前位置 : 主页 > 编程语言 > java >

jsp基于注解方式部署过滤器

来源:互联网 收集:自由互联 发布时间:2021-06-25
1.新建一个Dynamic Web Project项目,里面新建一个jsp文件和一个filter文件,整体的框架如下图所示: 2.one.jsp里面的代码如下所示: %@page import="java.util.Date"%%@ page language="java" contentType="text/

1.新建一个Dynamic Web Project项目,里面新建一个jsp文件和一个filter文件,整体的框架如下图所示:


2.one.jsp里面的代码如下所示:

<%@page import="java.util.Date"%>
<%@ 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>example</title>
</head>
<body>
	<h2>Test</h2>
</body>
</html>

3.FirstFiler.java里面的代码如下所示:

package filter;

import java.io.IOException;
import java.io.PrintWriter;

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;

@WebFilter(filterName = "firstFilter", urlPatterns = { "/*" })
public class FirstFilter implements Filter {

	public void destroy() {
	}

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = response.getWriter();
		out.print("首先执行过滤器<br>");
		chain.doFilter(request, response);
	}

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

}

4. 在浏览器里面输入http://localhost:8080/Servlet/one.jsp运行之后得到的结果如下所示:

网友评论