Filter入门示例
- 需求分析
- 程序设计
- MyFilter
- index.jsp
- product_input.jsp
- < table >
- product_details.jsp
- 效果测试
一:需求分析
二:程序设计
1> MyFilter
package xyz.xx.filter;
import org.apache.commons.beanutils.BeanUtils;
import xyz.xx.pojo.Product;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
@WebFilter("/*")
public class MyFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) servletRequest;
String servletPath = req.getServletPath();
String path = null;
if("/product-input.action".equals(servletPath)){
path = "/WEB-INF/pages/product_input.jsp";
}else if("/product-save.action".equals(servletPath)){
path = "/WEB-INF/pages/product_details.jsp";
Product p1 = new Product();
try {
BeanUtils.populate(p1,req.getParameterMap());
} catch (IllegalAccessException | InvocationTargetException e) {
e.printStackTrace();
}
p1.setProductId(10012);
servletRequest.setAttribute("product",p1);
}
if(path!=null) {
servletRequest.getRequestDispatcher(path).forward(servletRequest, servletResponse);
}
filterChain.doFilter(servletRequest,servletResponse);
}
@Override
public void destroy() {
}
}
index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>$Title$</title>
</head>
<body>
<a href="product-input.action">商品录入</a>
</body>
</html>
product_input.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<form action="product-save.action" method="post">
<table>
<tr>
<td>ProductName:</td>
<td><input type="text" name="productName"></td>
</tr>
<tr>
<td>ProductDesc:</td>
<td><input type="text" name="productDesc"></td>
</tr>
<tr>
<td>ProductPrice:</td>
<td><input type="text" name="productPrice"></td>
</tr>
<tr>
<td colspan="2"><input style="width:100%;height:30px" type="submit" value="Submit"></td>
</tr>
</table>
</form>
</body>
</html>
product_details.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
<style type="text/css">
table{
width: 600px;
text-align: center;
border: red 1px solid;
border-collapse: collapse;
}
tr,th,td{
border: red 3px solid;
border-collapse: collapse;
}
</style>
</head>
<body>
<table align="center">
<tr>
<th>ProductId</th>
<th>ProductName</th>
<th>ProductDesc</th>
<th>ProductPrice</th>
</tr>
<tr>
<td>${requestScope.product.productId}</td>
<td>${requestScope.product.productName}</td>
<td>${requestScope.product.productDesc}</td>
<td>${requestScope.product.productPrice}</td>
</tr>
</table>
</body>
</html>
三:效果测试