步骤 1 : 一个路径对应一个Servlet的弊端 步骤 2 : 对设计进行改进 步骤 3 : 原理流程图 步骤 4 : 代码讲解 - BackServletFilter 步骤 5 : 代码讲解 - CategoryServlet和BaseBackServlet 步骤 6 : 一个Servlet类就能满足CRUD一系列业务要求
通过观察
http://127.0.0.1:8080/tmall/admin_category_list 可以发现,分类管理需要:增加,删除,编辑,修改,查询5个服务端功能。 那么按照传统的在web.xml中配置Servlet的方式,一个路径对应一个Servlet的思路,就需要设计5个Servlet类,并且在web.xml中配置5个路径 AddCategoryServlet DeleteCategoryServlet EditCategoryServlet UpdateCategoryServlet ListCategoryServlet 而后台需要做分类,产品,属性,产品图片,用户,订单这么6种管理,那么就一共需要30个Servlet,以及在web.xml中对应的配置,那么配置文件就会变得臃肿,并且容易出错
但是观察已经实现了分类管理的可运行项目下载包里的代码,却发现Servlet只有一个即CategoryServlet,web.xml里,也只有一个CategoryServlet的映射,并没有5个映射。
如图是对于最后完工了的项目的servlet包里类的截图,可以发现,每种实体类,对应了一个Servlet,而不是对应了5个,这样首先从Servlet数量上来讲,就大大的减少了
增值内容,请先登录
完整的J2EE模仿天猫项目,使用J2SE、前端技术(包含所有前端jsp文件)、J2EE一整套技术栈, 从无到有涵盖全部147个知识点,475个开发步骤, 充实J2EE项目经验,为简历加上一个有吸引力的砝码.
增值内容,点击购买
使用爬虫已经被系统记录,请勿使用爬虫,增大封号风险。 如果是误封 ,请联系站长,谢谢
增值内容,请先登录
完整的J2EE模仿天猫项目,使用J2SE、前端技术(包含所有前端jsp文件)、J2EE一整套技术栈, 从无到有涵盖全部147个知识点,475个开发步骤, 充实J2EE项目经验,为简历加上一个有吸引力的砝码.
增值内容,点击购买
使用爬虫已经被系统记录,请勿使用爬虫,增大封号风险。 如果是误封 ,请联系站长,谢谢
package tmall.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;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.StringUtils;
public class BackServletFilter implements Filter {
public void destroy() {
}
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
String contextPath=request.getServletContext().getContextPath();
String uri = request.getRequestURI();
uri =StringUtils.remove(uri, contextPath);
if(uri.startsWith("/admin_")){
String servletPath = StringUtils.substringBetween(uri,"_", "_") + "Servlet";
String method = StringUtils.substringAfterLast(uri,"_" );
request.setAttribute("method", method);
req.getRequestDispatcher("/" + servletPath).forward(request, response);
return;
}
chain.doFilter(request, response);
}
public void init(FilterConfig arg0) throws ServletException {
}
}
<filter>
<filter-name>BackServletFilter</filter-name>
<filter-class>tmall.filter.BackServletFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>BackServletFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
增值内容,请先登录
完整的J2EE模仿天猫项目,使用J2SE、前端技术(包含所有前端jsp文件)、J2EE一整套技术栈, 从无到有涵盖全部147个知识点,475个开发步骤, 充实J2EE项目经验,为简历加上一个有吸引力的砝码.
增值内容,点击购买
使用爬虫已经被系统记录,请勿使用爬虫,增大封号风险。 如果是误封 ,请联系站长,谢谢
package tmall.servlet;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import tmall.bean.Category;
import tmall.util.ImageUtil;
import tmall.util.Page;
public class CategoryServlet extends BaseBackServlet {
public String add(HttpServletRequest request, HttpServletResponse response, Page page) {
Map<String,String> params = new HashMap<>();
InputStream is = super.parseUpload(request, params);
String name= params.get("name");
Category c = new Category();
c.setName(name);
categoryDAO.add(c);
File imageFolder= new File(request.getSession().getServletContext().getRealPath("img/category"));
File file = new File(imageFolder,c.getId()+".jpg");
try {
if(null!=is && 0!=is.available()){
try(FileOutputStream fos = new FileOutputStream(file)){
byte b[] = new byte[1024 * 1024];
int length = 0;
while (-1 != (length = is.read(b))) {
fos.write(b, 0, length);
}
fos.flush();
//通过如下代码,把文件保存为jpg格式
BufferedImage img = ImageUtil.change2jpg(file);
ImageIO.write(img, "jpg", file);
}
catch(Exception e){
e.printStackTrace();
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "@admin_category_list";
}
public String delete(HttpServletRequest request, HttpServletResponse response, Page page) {
int id = Integer.parseInt(request.getParameter("id"));
categoryDAO.delete(id);
return "@admin_category_list";
}
public String edit(HttpServletRequest request, HttpServletResponse response, Page page) {
int id = Integer.parseInt(request.getParameter("id"));
Category c = categoryDAO.get(id);
request.setAttribute("c", c);
return "admin/editCategory.jsp";
}
public String update(HttpServletRequest request, HttpServletResponse response, Page page) {
Map<String,String> params = new HashMap<>();
InputStream is = super.parseUpload(request, params);
System.out.println(params);
String name= params.get("name");
int id = Integer.parseInt(params.get("id"));
Category c = new Category();
c.setId(id);
c.setName(name);
categoryDAO.update(c);
File imageFolder= new File(request.getSession().getServletContext().getRealPath("img/category"));
File file = new File(imageFolder,c.getId()+".jpg");
file.getParentFile().mkdirs();
try {
if(null!=is && 0!=is.available()){
try(FileOutputStream fos = new FileOutputStream(file)){
byte b[] = new byte[1024 * 1024];
int length = 0;
while (-1 != (length = is.read(b))) {
fos.write(b, 0, length);
}
fos.flush();
//通过如下代码,把文件保存为jpg格式
BufferedImage img = ImageUtil.change2jpg(file);
ImageIO.write(img, "jpg", file);
}
catch(Exception e){
e.printStackTrace();
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "@admin_category_list";
}
public String list(HttpServletRequest request, HttpServletResponse response, Page page) {
List<Category> cs = categoryDAO.list(page.getStart(),page.getCount());
int total = categoryDAO.getTotal();
page.setTotal(total);
request.setAttribute("thecs", cs);
request.setAttribute("page", page);
return "admin/listCategory.jsp";
}
}
package tmall.servlet;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import tmall.dao.CategoryDAO;
import tmall.dao.OrderDAO;
import tmall.dao.OrderItemDAO;
import tmall.dao.ProductDAO;
import tmall.dao.ProductImageDAO;
import tmall.dao.PropertyDAO;
import tmall.dao.PropertyValueDAO;
import tmall.dao.ReviewDAO;
import tmall.dao.UserDAO;
import tmall.util.Page;
public abstract class BaseBackServlet extends HttpServlet {
public abstract String add(HttpServletRequest request, HttpServletResponse response, Page page) ;
public abstract String delete(HttpServletRequest request, HttpServletResponse response, Page page) ;
public abstract String edit(HttpServletRequest request, HttpServletResponse response, Page page) ;
public abstract String update(HttpServletRequest request, HttpServletResponse response, Page page) ;
public abstract String list(HttpServletRequest request, HttpServletResponse response, Page page) ;
protected CategoryDAO categoryDAO = new CategoryDAO();
protected OrderDAO orderDAO = new OrderDAO();
protected OrderItemDAO orderItemDAO = new OrderItemDAO();
protected ProductDAO productDAO = new ProductDAO();
protected ProductImageDAO productImageDAO = new ProductImageDAO();
protected PropertyDAO propertyDAO = new PropertyDAO();
protected PropertyValueDAO propertyValueDAO = new PropertyValueDAO();
protected ReviewDAO reviewDAO = new ReviewDAO();
protected UserDAO userDAO = new UserDAO();
public void service(HttpServletRequest request, HttpServletResponse response) {
try {
/*获取分页信息*/
int start= 0;
int count = 5;
try {
start = Integer.parseInt(request.getParameter("page.start"));
} catch (Exception e) {
}
try {
count = Integer.parseInt(request.getParameter("page.count"));
} catch (Exception e) {
}
Page page = new Page(start,count);
/*借助反射,调用对应的方法*/
String method = (String) request.getAttribute("method");
Method m = this.getClass().getMethod(method, javax.servlet.http.HttpServletRequest.class,
javax.servlet.http.HttpServletResponse.class,Page.class);
String redirect = m.invoke(this,request, response,page).toString();
/*根据方法的返回值,进行相应的客户端跳转,服务端跳转,或者仅仅是输出字符串*/
if(redirect.startsWith("@"))
response.sendRedirect(redirect.substring(1));
else if(redirect.startsWith("%"))
response.getWriter().print(redirect.substring(1));
else
request.getRequestDispatcher(redirect).forward(request, response);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
throw new RuntimeException(e);
}
}
public InputStream parseUpload(HttpServletRequest request, Map<String, String> params) {
InputStream is =null;
try {
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
// 设置上传文件的大小限制为10M
factory.setSizeThreshold(1024 * 10240);
List items = upload.parseRequest(request);
Iterator iter = items.iterator();
while (iter.hasNext()) {
FileItem item = (FileItem) iter.next();
if (!item.isFormField()) {
// item.getInputStream() 获取上传文件的输入流
is = item.getInputStream();
} else {
String paramName = item.getFieldName();
String paramValue = item.getString();
paramValue = new String(paramValue.getBytes("ISO-8859-1"), "UTF-8");
params.put(paramName, paramValue);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return is;
}
}
<servlet>
<servlet-name>CategoryServlet</servlet-name>
<servlet-class>tmall.servlet.CategoryServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>CategoryServlet</servlet-name>
<url-pattern>/categoryServlet</url-pattern>
</servlet-mapping>
通过这样一种模式,一个Servlet类就能满足CRUD一系列业务要求
如果访问的路径是admin_category_list,就会调用categoryServlet.list()方法 如果访问的路径是admin_category_add,就会调用categoryServlet.add()方法 如果访问的路径是admin_category_delete,就会调用categoryServlet.delete()方法 如果访问的路径是admin_category_edit,就会调用categoryServlet.edit()方法 如果访问的路径是admin_category_update,就会调用categoryServlet.update()方法
HOW2J公众号,关注后实时获知最新的教程和优惠活动,谢谢。
问答区域
2022-05-09
request.getRequestDispatcher(redirect).forward(request, response)服务端跳转不会经过过滤器filter吗
回答已经提交成功,正在审核。 请于 我的回答 处查看回答记录,谢谢
2022-04-04
import org.apache.commons.lang.StringUtils没有怎么处理
1 个答案
how2j 跳转到问题位置 答案时间:2022-05-02 你没有导入这里的jars吗?
https://how2j.cn/k/tmall-j2ee/tmall-j2ee-1007/1007.html#step4002
回答已经提交成功,正在审核。 请于 我的回答 处查看回答记录,谢谢
2021-12-02
web.xml 中相同的 url-pattern ,执行顺序是怎么样的?
2021-10-12
站长好帅
2021-05-16
这个实现方法也太可怕了吧,明明有更方便的方法
提问太多,页面渲染太慢,为了加快渲染速度,本页最多只显示几条提问。还有 96 条以前的提问,请 点击查看
提问之前请登陆
提问已经提交成功,正在审核。 请于 我的提问 处查看提问记录,谢谢
|