社区微信群开通啦,扫一扫抢先加入社区官方微信群
社区微信群
1.1.1 需求:
1.1.2 数据库设计:
1.1.3 网上商城用户模块的代码实现:(前台)1.1.3.1 编写一个通用的Servlet:
传统方式的开发一个请求对应一个Servlet:这样的话会导致一个模块的Servlet过多,导致整个项目的Servlet都会很多.能不能做一个处理?让一个模块致用一个Servlet处理请求.
注册:http://localhost:8080/store_2.0/UserServlet?method=regist
登录:http://localhost:8080/store_2.0/UserServlet?method=login
激活:http://localhost:8080/store_2.0/UserServlet?method=active
商品查询所有:http://localhost:8080/store_2.0/ProductServlet?method=findAll
商品查询某个:http://localhost:8080/store_2.0/ProductServlet?method=findById
传统:
public class UserServlet extends HttpServlet{
public void service(HttpServletRequest req,HttpServletResponse resp){
// 接收参数:
String methodName = request.getParameter(“method”);
if(“regist”.equals(methodName)){
regist(req,resp);
}else if(“login”.equals(methodName)){
login(req,resp);
}
}
public void regist(HttpServletRequest req,HttpServletResponse resp){
}
public void login(HttpServletRequest req,HttpServletResponse resp){
}
}
public class ProductServlet extends HttpServlet{
public void service(HttpServletRequest req,HttpServletResponse resp){
// 接收参数:
String methodName = request.getParameter(“method”);
if(“findAll”.equals(methodName)){
findAll(req,resp);
}else if(“findById”.equals(methodName)){
findById(req,resp);
}
}
public void findAll(HttpServletRequest req,HttpServletResponse resp){
}
public void findById(HttpServletRequest req,HttpServletResponse resp){
}
}
反射:
public class BaseServlet extends HttpServlet{
public void service(HttpServletRequest req,HttpServletResponse resp){
// http://localhost:8080/store_2.0/UserServlet?method=regist
// http://localhost:8080/store_2.0/ProductServlet?method=findAll
String methodName = request.getParameter(“method”);
// 获得Class:
Class clazz = this.getClass();
Method method = clazz.getMethod(methodName,HttpServletRequest.class,HttpSerlvetResponse.class);
String path = (String)method.invoke(this,req,resp);
if(path != null){
req.getRequestDispatcher(path).forward(req,resp);
}
}
}
public class UserServlet extends BaseServlet {
public String regist(HttpServletRequest req,HttpServletResponse resp){
return “/login.jsp”;
}
public String login(HttpServletRequest req,HttpServletResponse resp){
return “/index.jsp”;
}
}
public class ProductServlet extends BaseServlet{
public String findAll(HttpServletRequest req,HttpServletResponse resp){
}
public String findById(HttpServletRequest req,HttpServletResponse resp){
}
}
1.1.3.2 搭建开发环境:
【步骤一】:引入开发jar包
如果觉得我的文章对您有用,请随意打赏。你的支持将鼓励我继续创作!