Servlet的代码优化,让代码具有复用性将代码耦合性降低,每添加一个方法方法就要多添加一个servlet这样很浪费空间,所以我们要把所有方法放在一个类里面,用方法名来判断该用那个方法,这样提高了代码
列如:
每一个添加方法
BrandServletAdd
BrandSelectAll
非常的浪费资源
所以我们把每个方法都提取到一个类里面就想Mapper接口一样
public interface BrandMapper { @Select("select * from tb_brand") @ResultMap("brandResultMap") List selectAll(); @Insert("insert into tb_brand values(null,#{brandName},#{companyName},#{ordered},#{description},#{status})") void add(Brand brand); @Select("select * from tb_brand where id = #{id}") @ResultMap("brandResultMap") Brand selectById(int id); @Update("update tb_brand set brand_name = #{brandName},company_name = #{companyName},ordered = #{ordered},description = #{description},status = #{status} where id = #{id}") void Update(Brand brand); @Delete("delete from tb_brand where id = #{id}") void deleteById(int id);}
所以我们可以换一种思路来写创建一个类继承
public class BaseServlet extends HttpServlet{}
把方法名字的路径和方法名字写成一样,方待会反射调用方法列如路径名字是selectAll
我们就可以把他当做方法名传给反射里面的 getMethod 就可获取到该方法
这样就不用创建过多的类了案列如下
public class BaseServlet extends HttpServlet { @Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String s = req.getRequestURI(); int i = s.lastIndexOf("/"); String u = s.substring(i + 1); Class aClass = this.getClass(); try { Method method = aClass.getMethod(u, HttpServletRequest.class, HttpServletResponse.class); method.invoke(this,req,resp); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } }}
以上是获取地址然后拆分获取到路径最后一位,就是方法名字啦
然后在设置一个类比如Brand继承着现在这个类
@WebServlet("/brand/*")public class BrandServlet extends BaseServlet{ private BrandServletImpl bs = new BrandServletImpl(); public void selectAll(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { List brands = bs.selectAll(); String s = JSON.toJSONString(brands); response.setContentType("text/json;charset=utf-8"); response.getWriter().write(s); } public void add(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { BufferedReader reader = request.getReader(); String s = reader.readLine(); System.out.println(s); Brand brand = JSON.parseObject(s, Brand.class); BrandServletImpl brandServlet = new BrandServletImpl(); brandServlet.add(brand); response.getWriter().write("ok"); }}
记住路径一定要 /brand/* 用通配符这样可以接收一切的路径
总结:每添加一个方法方法就要多添加一个servlet这样很浪费空间,所以我们要把所有方法放在一个类里面,用方法名来判断该用那个方法,这样提高了代码的复用性