testFilter
/test.jsp
testFilter
/index.jsp
REQUEST
FORWARD
package cn.itcast.web.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;
// Filter入门
// 1.创建一个类你,实现Filter接口
// 2.重写方法
// 3.在web.xml文件中配置
public class Demo1Filter implements Filter {
@Override
public void destroy() {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
System.out.println("进行过滤操作......");
// 放行
chain.doFilter(request, response);
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
System.out.println("Demo1Filter初始化创建....");
}
}
配置Demo1Filter的注册与映射 在web.xml中添加如下配置:
demoFilter
cn.itcast.web.filter.Demo1Filter
demoFilter
/index.jsp
package cn.itcast.web.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;
public class FirstFilter implements Filter {
@Override
public void destroy() {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
System.out.println("firstFilter....");
chain.doFilter(request, response);
System.out.println("firstFilter end....");
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
}
SecondFilter
package cn.itcast.web.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;
public class SecondFilter implements Filter {
@Override
public void destroy() {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
System.out.println("secondFilter....");
chain.doFilter(request, response);
System.out.println("secondFilter end....");
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
}
package cn.itcast.web.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class DemoServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("demo servlet");
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
firstFilter
cn.itcast.web.filter.FirstFilter
senondFilter
cn.itcast.web.filter.SecondFilter
firstFilter
/demo
senondFilter
/demo
demoServlet
cn.itcast.web.servlet.DemoServlet
demoServlet
/demo
启动服务器,访问/demo
package cn.itcast.web.filter;
import java.io.IOException;
import java.util.Enumeration;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
// Filter入门
// 1.创建一个类你,实现Filter接口
// 2.重写方法
// 3.在web.xml文件中配置
public class Demo2Filter implements Filter {
@Override
public void destroy() {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
System.out.println("demo2Filter进行过滤操作......");
// 放行
chain.doFilter(request, response);
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
// 1. 获取filter名称
String filterName = filterConfig.getFilterName();
System.out.println(filterName);
// 2.获取初始化参数
String encoding = filterConfig.getInitParameter("encoding");
System.out.println(encoding);
Enumeration names = filterConfig.getInitParameterNames();
while (names.hasMoreElements()) {
System.out.println(names.nextElement());
}
// 3.获取ServletConfig对象
filterConfig.getServletContext();
}
}
demo2Filter
cn.itcast.web.filter.Demo2Filter
encoding
utf-8
username
liuxun
demo2Filter
/index.jsp
package cn.itcast.web.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class DemoServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("demo servlet");
// 请求转发到demo1Servlet
request.getRequestDispatcher("/demo1").forward(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
Demo1Servlet
package cn.itcast.web.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Demo1Servlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("Demo1Servlet ......");
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
在web.xml中添加如下配置:
myFilter
cn.itcast.web.filter.MyFilter
myFilter
/demo1
REQUEST
FORWARD
demoServlet
cn.itcast.web.servlet.DemoServlet
Demo1Servlet
cn.itcast.web.servlet.Demo1Servlet
demoServlet
/demo
Demo1Servlet
/demo1
访问/demo1 后台打印如下:
package cn.itcast.filter.demo1;
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.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class EncodingFilter implements Filter {
private String encode;
@Override
public void destroy() {
}
@Override
public void doFilter(ServletRequest arg0, ServletResponse arg1,
FilterChain arg2) throws IOException, ServletException {
// 1.强制转换
HttpServletRequest request = (HttpServletRequest) arg0;
HttpServletResponse response = (HttpServletResponse) arg1;
// 2.操作
request.setCharacterEncoding(encode);
response.setContentType("text/html;charset=utf-8");
// 3.放行
arg2.doFilter(request, response);
}
@Override
public void init(FilterConfig arg0) throws ServletException {
this.encode = arg0.getInitParameter("encode");
}
}
Demo1Servlet.java
package cn.itcast.servlet.demo1;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Demo1Servlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// request.setCharacterEncoding("utf-8");
// 1.获取页面的请求参数
String username = request.getParameter("username");
String msg = request.getParameter("msg");
// 显示
System.out.println(username);
System.out.println(msg);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
demo1.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
My JSP 'demo1.jsp' starting page
在web.xml中添加如下配置
encodingFilter
cn.itcast.filter.demo1.EncodingFilter
encode
utf-8
encodingFilter
/*
Demo1Servlet
cn.itcast.servlet.demo1.Demo1Servlet
Demo1Servlet
/demo1
package cn.itcast.filter.demo2;
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.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class CacheFilter implements Filter {
@Override
public void destroy() {
}
@Override
public void doFilter(ServletRequest req, ServletResponse resp,
FilterChain chain) throws IOException, ServletException {
// 1.强制转换
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) resp;
// 2.操作
response.setHeader("pragma", "no-cache");
response.setHeader("cache-control", "no-cache");
response.setDateHeader("expires", 0);
// 3.放行
chain.doFilter(request, response);
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
}
cacheFilter
cn.itcast.filter.demo2.CacheFilter
cacheFilter
*.jsp
package cn.itcast.filter.demo3;
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.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ImageCacheFilter implements Filter {
@Override
public void destroy() {
}
@Override
public void doFilter(ServletRequest req, ServletResponse resp,
FilterChain chain) throws IOException, ServletException {
// 1.强制转换
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) resp;
// 2.操作 设置响应的缓存时间为10天
response.setDateHeader("expires", System.currentTimeMillis() + 60 * 60
* 24 * 10*1000);
// 3.放行
chain.doFilter(request, response);
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
}
新建一加载图片的jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
My JSP 'index.jsp' starting page
配置图片过滤器的注册和映射 在web.xml中添加如下配置
imageFilter
cn.itcast.filter.demo3.ImageCacheFilter
imageFilter
*.png
*.jpg
*.bmp
重启服务器 访问 查看如下:
create table user (
id int primary key auto_increment,
username varchar(20),
password varchar(40),
role varchar(10)
);
insert into user values(null,'admin','123','admin');
insert into user values(null,'aaa','123','user');
insert into user values(null,'bbb','123','user');
package cn.itcast.utils;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class Md5Utils {
public static String md5(String plainText) { //明文
byte[] secretBytes = null;
try {
secretBytes = MessageDigest.getInstance("md5").digest(
plainText.getBytes());
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException("没有md5这个算法!");
}
String md5code = new BigInteger(1, secretBytes).toString(16);
for (int i = 0; i < 32 - md5code.length(); i++) {
md5code = "0" + md5code;
}
return md5code;
}
public static void main(String[] args) {
System.out.println(md5("123"));
}
}
com.mysql.jdbc.Driver
jdbc:mysql:///mydb1
root
root
package cn.itcast.utils;
import java.sql.Connection;
import java.sql.SQLException;
import javax.sql.DataSource;
import com.mchange.v2.c3p0.ComboPooledDataSource;
public class DataSourceUtils {
private static ComboPooledDataSource cpds = new ComboPooledDataSource();
public static Connection getConnection() throws SQLException {
return cpds.getConnection();
}
public static DataSource getDataSource() {
return cpds;
}
}
在工具包内新建MD5加密的工具类
package cn.itcast.utils;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class Md5Utils {
public static String md5(String plainText) { //明文
byte[] secretBytes = null;
try {
secretBytes = MessageDigest.getInstance("md5").digest(
plainText.getBytes());
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException("没有md5这个算法!");
}
String md5code = new BigInteger(1, secretBytes).toString(16);
for (int i = 0; i < 32 - md5code.length(); i++) {
md5code = "0" + md5code;
}
return md5code;
}
public static void main(String[] args) {
System.out.println(md5("123"));
}
}
在工具包内新建根据名称从Cookie[] 数组中取出Cookie的工具类
package cn.itcast.utils;
import javax.servlet.http.Cookie;
public class CookieUtils {
public static Cookie findCookieByName(Cookie[] cs, String name) {
if (cs == null || cs.length == 0) {
return null;
}
for (Cookie c : cs) {
if (c.getName().equals(name)) {
return c;
}
}
return null;
}
}
package cn.itcast.domain;
public class User {
private int id;
private String username;
private String password;
private String role;
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;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
}
新建DAO UserDao
package cn.itcast.dao;
import java.sql.SQLException;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import cn.itcast.domain.User;
import cn.itcast.utils.DataSourceUtils;
public class UserDao {
// 根据用户名和密码查找用户
public User findUserByUsernameAndPassword(String username, String password)
throws SQLException {
String sql = "select * from user where username=? and password=?";
QueryRunner runner = new QueryRunner(DataSourceUtils.getDataSource());
return runner.query(sql, new BeanHandler(User.class), username,
password);
}
}
新建业务层类UserService实现登录功能
package cn.itcast.service;
import java.sql.SQLException;
import cn.itcast.dao.UserDao;
import cn.itcast.domain.User;
public class UserService {
public User login(String username, String password) throws SQLException {
return new UserDao().findUserByUsernameAndPassword(username, password);
}
}
package cn.itcast.servlet.demo4;
import java.io.IOException;
import java.net.URLEncoder;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import cn.itcast.domain.User;
import cn.itcast.service.UserService;
import cn.itcast.utils.Md5Utils;
public class LoginServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
// 1.得到请求参数
String username = request.getParameter("username");
String password = request.getParameter("password");
// 2.登录
UserService service = new UserService();
try {
User user = service.login(username, Md5Utils.md5(password));
if (user != null) {
// 登录成功
// 判断是否勾选了自动登录
String autologin = request.getParameter("autologin");
if ("ok".equals(autologin)) {
// 勾选了自动登录
Cookie cookie = new Cookie("autologin", URLEncoder.encode(
username, "utf-8") + "::" + Md5Utils.md5(password));
cookie.setMaxAge(60 * 60 * 24 * 10); // 存储10天
cookie.setPath("/");
response.addCookie(cookie);
}
request.getSession().setAttribute("user", user);
response.sendRedirect(request.getContextPath()
+ "/demo4/success.jsp");
return;
} else {
request.setAttribute("login.message", "用户名或密码错误");
request.getRequestDispatcher("/demo4/login.jsp").forward(
request, response);
return;
}
} catch (SQLException e) {
e.printStackTrace();
request.setAttribute("login.message", "登录失败");
request.getRequestDispatcher("/demo4/login.jsp").forward(request,
response);
return;
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
package cn.itcast.filter.demo4;
import java.io.IOException;
import java.net.URLDecoder;
import java.sql.SQLException;
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;
import javax.servlet.http.HttpServletResponse;
import cn.itcast.domain.User;
import cn.itcast.service.UserService;
import cn.itcast.utils.CookieUtils;
import cn.itcast.utils.Md5Utils;
public class AutoLoginFilter implements Filter {
@Override
public void destroy() {
}
@Override
public void doFilter(ServletRequest req, ServletResponse resp,
FilterChain chain) throws IOException, ServletException {
// 1.强制转换
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) resp;
// 2.操作
// 判断用户访问的是登录操作,不进行自动登录
String uri = request.getRequestURI();
String contextPath = request.getContextPath();
String path = uri.substring(contextPath.length());
// System.out.println(uri);
// System.out.println(contextPath);
// System.out.println(path);
if (!(path.equals("/demo4/login.jsp") || path.equals("/login"))) {
// 判断用户没有登录,才进行自动登录
User u = (User) request.getSession().getAttribute("user");
System.out.println(u);
if (u == null) {
// 2.1得到cookie中的username,password
Cookie cookie = CookieUtils.findCookieByName(
request.getCookies(), "autologin");
if (cookie != null) {
// 找到了则进行自动登录
String username = URLDecoder.decode(cookie.getValue()
.split("::")[0], "utf-8");
String password = cookie.getValue().split("::")[1];
UserService service = new UserService();
User user = null;
try {
user = service.login(username, password);
if (user != null) {
// 查到了用户,则进行自动登录
request.getSession().setAttribute("user", user);
return;
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
// 3.放行
chain.doFilter(request, response);
}
@Override
public void init(FilterConfig arg0) throws ServletException {
}
}
autoLoginFilter
cn.itcast.filter.demo4.AutoLoginFilter
autoLoginFilter
/*
LoginServlet
cn.itcast.servlet.demo4.LoginServlet
LoginServlet
/login
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
My JSP 'login.jsp' starting page
${ requestScope["login.message"] }
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
My JSP 'login.jsp' starting page
当前用户:${user.username }
运行结果如下:
package cn.itcast.servlet.demo5;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class BookAddServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("book add ......");
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
BookDeleteServlet url:/book_delete
package cn.itcast.servlet.demo5;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class BookDeleteServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("book delete ......");
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
BookSearchServlet url: /book_search
package cn.itcast.servlet.demo5;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class BookSearchServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("book search ......");
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
BookUpdateServlet url: /book_update
package cn.itcast.servlet.demo5;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class BookUpdateServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("book update ......");
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
新建自定义权限异常类PrivilegeException 继承自RuntimeException
package cn.itcast.exception;
import java.io.PrintStream;
import java.io.PrintWriter;
public class PrivilegeException extends RuntimeException {
@Override
public String getMessage() {
// TODO Auto-generated method stub
return super.getMessage();
}
@Override
public String getLocalizedMessage() {
// TODO Auto-generated method stub
return super.getLocalizedMessage();
}
@Override
public synchronized Throwable getCause() {
// TODO Auto-generated method stub
return super.getCause();
}
@Override
public synchronized Throwable initCause(Throwable cause) {
// TODO Auto-generated method stub
return super.initCause(cause);
}
@Override
public String toString() {
// TODO Auto-generated method stub
return super.toString();
}
@Override
public void printStackTrace() {
// TODO Auto-generated method stub
super.printStackTrace();
}
@Override
public void printStackTrace(PrintStream s) {
// TODO Auto-generated method stub
super.printStackTrace(s);
}
@Override
public void printStackTrace(PrintWriter s) {
// TODO Auto-generated method stub
super.printStackTrace(s);
}
@Override
public synchronized Throwable fillInStackTrace() {
// TODO Auto-generated method stub
return super.fillInStackTrace();
}
@Override
public StackTraceElement[] getStackTrace() {
// TODO Auto-generated method stub
return super.getStackTrace();
}
@Override
public void setStackTrace(StackTraceElement[] stackTrace) {
// TODO Auto-generated method stub
super.setStackTrace(stackTrace);
}
@Override
public int hashCode() {
// TODO Auto-generated method stub
return super.hashCode();
}
@Override
public boolean equals(Object obj) {
// TODO Auto-generated method stub
return super.equals(obj);
}
@Override
protected Object clone() throws CloneNotSupportedException {
// TODO Auto-generated method stub
return super.clone();
}
@Override
protected void finalize() throws Throwable {
// TODO Auto-generated method stub
super.finalize();
}
}
新建自定义权限异常抛出后跳转的页面
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
My JSP 'privilege.jsp' starting page
权限不足
最后自定义URL权限访问过滤器package cn.itcast.filter.demo5;
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.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import cn.itcast.domain.User;
import cn.itcast.exception.PrivilegeException;
//权限过滤器--垃圾版本
public class PrivilegeFilter implements Filter {
public void destroy() {
}
public void doFilter(ServletRequest req, ServletResponse resp,
FilterChain chain) throws IOException, ServletException {
// 1.强制转换
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) resp;
// 2.操作
// 判断当前资源是否需要权限控制.
String uri = request.getRequestURI();
String contextPath = request.getContextPath();
String path = uri.substring(contextPath.length());
if (path.equals("/book_add") || path.equals("/book_update")
|| path.equals("/book_delete") || path.equals("/book_search")) {
// 判断用户是否登录了.
User user = (User) request.getSession().getAttribute("user");
if (user == null) {
throw new PrivilegeException();
}
// 判断用户的角色,是否可以访问当前资源路径。
if ("admin".equals(user.getRole())) {
// 这是admin角色
if (!(path.equals("/book_add") || path.equals("/book_update") || path
.equals("/book_delete"))) {
throw new PrivilegeException();
}
} else {
// 这是user角色
if (!(path.equals("/book_search"))) {
throw new PrivilegeException();
}
}
}
// 3.放行
chain.doFilter(request, response);
}
public void init(FilterConfig filterConfig) throws ServletException {
}
}
注意:以上的这个权限过滤器虽然可以使用 但代码过于臃肿,另外访问路径和filter的耦合性很强不便于维护
url=/book_add,/book_delete,/book_update
url=/book_search
(2)修改权限过滤器如下所示:
package cn.itcast.filter.demo5;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;
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.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import cn.itcast.domain.User;
import cn.itcast.exception.PrivilegeException;
//权限过滤器
public class PrivilegeFilter implements Filter {
private List admins;
private List users;
public void destroy() {
}
public void doFilter(ServletRequest req, ServletResponse resp,
FilterChain chain) throws IOException, ServletException {
// 1.强制转换
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) resp;
// 2.操作
// 判断当前资源是否需要权限控制.
String uri = request.getRequestURI();
String contextPath = request.getContextPath();
String path = uri.substring(contextPath.length());
if (admins.contains(path) || users.contains(path)) {
// 判断用户是否登录了.
User user = (User) request.getSession().getAttribute("user");
if (user == null) {
throw new PrivilegeException();
}
// 判断用户的角色,是否可以访问当前资源路径。
if ("admin".equals(user.getRole())) {
// 这是admin角色
if (!(admins.contains(path))) {
throw new PrivilegeException();
}
} else {
// 这是user角色
if (!(users.contains(path))) {
throw new PrivilegeException();
}
}
}
// 3.放行
chain.doFilter(request, response);
}
public void init(FilterConfig filterConfig) throws ServletException {
this.admins = new ArrayList();
this.users = new ArrayList();
fillPath("user", users);
fillPath("admin", admins);
}
private void fillPath(String baseName, List list) {
ResourceBundle bundle = ResourceBundle.getBundle(baseName);
String path = bundle.getString("url");
String[] paths = path.split(",");
for (String p : paths) {
list.add(p);
}
}
}
修改示例4中的success.jsp 如下:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
My JSP 'index.jsp' starting page
当前用户:${user.username}
book add
book update
book delete
book search
最后进行web.xml的配置(添加异常类配置和权限过滤器配置)
privilegeFilter
cn.itcast.filter.demo5.PrivilegeFilter
privilegeFilter
/book_delete
/book_add
/book_update
/book_search
LoginServlet
cn.itcast.servlet.demo4.LoginServlet
BookAddServlet
cn.itcast.servlet.demo5.BookAddServlet
BookDeleteServlet
cn.itcast.servlet.demo5.BookDeleteServlet
BookUpdateServlet
cn.itcast.servlet.demo5.BookUpdateServlet
BookSearchServlet
cn.itcast.servlet.demo5.BookSearchServlet
Demo1Servlet
/demo1
LoginServlet
/login
BookAddServlet
/book_add
BookDeleteServlet
/book_delete
BookUpdateServlet
/book_update
BookSearchServlet
/book_search
index.jsp
cn.itcast.exception.PrivilegeException
/error/privilege.jsp
getParameter
getParameterValues
getParameterMap
在覆盖的时候可以考虑只遍历getParameterMap中的键值对 使用new String(name.getBytes("iso-8859-1"),"utf-8")方法对参数值进行重新编码,这样做必须注意一条,因为第一次调用就已经将所有参数的值进行重新编码,如果再次调用就会将编码后正常的参数值又进行一次编码 造成除了第一次获取后的参数都是乱码,其解决方案就是 加flag限制符保证一次请求只调用获取参数方法时只遍历一次getParameterMap方法。
编写过滤器如下:
package cn.itcast.filter.demo6;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.Principal;
import java.util.Enumeration;
import java.util.Locale;
import java.util.Map;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class EncodingFilter implements Filter {
public void destroy() {
}
public void doFilter(ServletRequest req, ServletResponse resp,
FilterChain chain) throws IOException, ServletException {
// 1.强制转换
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) resp;
// 2.操作
HttpServletRequest myrequest = new MyRequest(request); // 增强后的request,解决了编码问题
response.setContentType("text/html;charset=utf-8");
// 3.放行
chain.doFilter(myrequest, response);
}
public void init(FilterConfig filterConfig) throws ServletException {
}
}
// 装饰类
class MyRequest extends HttpServletRequestWrapper {
private HttpServletRequest request;
public MyRequest(HttpServletRequest request) {
super(request);
this.request = request;
}
// 重写关于获取请求参数的方法.
@Override
public String getParameter(String name) {
Map map = getParameterMap();
if (name == null) {
return null;
}
String[] st = map.get(name);
if (st == null || st.length == 0) {
return null;
}
return st[0];
}
@Override
public String[] getParameterValues(String name) {
Map map = getParameterMap();
if (name == null) {
return null;
}
String[] st = map.get(name);
return st;
}
private boolean flag = true;
@Override
public Map getParameterMap() {
// 1.得到所有请求参数的Map集合
Map map = request.getParameterMap(); // 有编码问题.
// 2.解决编码问题.
if (flag) {
for (String key : map.keySet()) {
String[] values = map.get(key);
for (int i = 0; i < values.length; i++) {
try {
values[i] = new String(values[i].getBytes("iso8859-1"),
"utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
}
flag = false;
}
return map;
}
}
编写Servlet处理表单的示例 进行测试
Demo6Servlet
package cn.itcast.servlet.demo6;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Demo6Servlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println(request.getParameter("msg1"));
System.out.println(request.getParameter("msg2"));
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
demo6.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
My JSP 'demo6.jsp' starting page
EncodingFilter
cn.itcast.filter.demo6.EncodingFilter
EncodingFilter
/*