GenericServlet抽象类
提供了Servlet与ServletConfig接口默认的实现方法
GenericServlet常用方法
HttpServlet继承于GenericServlet
用来处理HTTP协议的请求和响应
HttpServlet的方法
Servlet初始化参数配置
配置Servlet上下文
HttpServletRequest类常用方法
HttpServletResponset类常用方法
RequestDispatcher类
作用:实现请求转发
使用步骤如下:
什么是过滤器
过滤器运行在服务器端
过滤器必须实现Servlet API中的Filter接口
Filter通常可用于以下几种情况:
1.认证
2.记录访问日至
3.加密解密
4.字符编码转换
5.数据压缩
过滤器示意图:
字符编码过滤器小例子:
package com.zgq.filter;
import java.io.IOException;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
/**
* 编码过滤器
* @author Administrator
*
*/
//@WebFilter(value="/*",initParams={@WebInitParam(name="encoding",value="utf-8")})
public class CharacterFilter implements Filter {
private String encoding;
/**
* 初始化
*/
@Override
public void init(FilterConfig filterConfig) throws ServletException {
// TODO Auto-generated method stub
System.out.println("字符编码过滤器启动...");
encoding=filterConfig.getInitParameter("encoding");
}
/**
* 过滤功能
*/
@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
// TODO Auto-generated method stub
//设置请求编码格式
request.setCharacterEncoding(encoding);
//设置响应编码格式
response.setContentType("text/html;charset="+encoding);
response.setCharacterEncoding(encoding);
chain.doFilter(request, response);
}
/**
* 销毁
*/
@Override
public void destroy() {
// TODO Auto-generated method stub
System.out.println("字符编码过滤器结束...");
}
}
import java.io.IOException;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
/**
* 编码过滤器
* @author Administrator
*
*/
//@WebFilter(value="/*",initParams={@WebInitParam(name="encoding",value="utf-8")})
public class CharacterFilter implements Filter {
private String encoding;
/**
* 初始化
*/
@Override
public void init(FilterConfig filterConfig) throws ServletException {
// TODO Auto-generated method stub
System.out.println("字符编码过滤器启动...");
encoding=filterConfig.getInitParameter("encoding");
}
/**
* 过滤功能
*/
@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
// TODO Auto-generated method stub
//设置请求编码格式
request.setCharacterEncoding(encoding);
//设置响应编码格式
response.setContentType("text/html;charset="+encoding);
response.setCharacterEncoding(encoding);
chain.doFilter(request, response);
}
/**
* 销毁
*/
@Override
public void destroy() {
// TODO Auto-generated method stub
System.out.println("字符编码过滤器结束...");
}
}