后端心得

后端心得

传统servlet

@WebServlet("/exitServlet")
public class ExitServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.getSession().invalidate();

        response.sendRedirect(request.getContextPath()+"/login.html");
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
  1. 注解 @WebServlet("/activeUserServlet")里面对应url,就是访问该方法的网址。html页面请求的也是该方法

  2. doGet方法没什么用,只用post

    对Servlet抽取,来实现解耦

    public class BaseServlet extends HttpServlet {
        //不需要被访问到,其他的Servlet来继承
     @Override
        protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    //         当子类Servlet被访问,就运行这个方法(方法继承)
    //         获取请求路径,方法名称,方法对象,执行方法(反射)
    //         这里运行方法是通过网址来获取的
            String uri = req.getRequestURI();
            // /user/add
            String methodName = uri.substring(uri.lastIndexOf('/') + 1);
            //在这里this对象就是UserServlet 谁调用,就是谁
            try {
                //getDeclaredMethod,忽略修饰符
                Method method = this.getClass()
                        .getDeclaredMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
                method.setAccessible(true);
                // 暴力反射
                method.invoke(this, req, resp);
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
        }
        public void writeJsonBack(Object object, HttpServletResponse response) throws IOException {
            ObjectMapper mapper = new ObjectMapper();
            response.setContentType("application/json;charset=utf-8");
            mapper.writeValue(response.getOutputStream(), object);
        }
    
        public String writeValueAsString(Object obj) throws JsonProcessingException {
            ObjectMapper mapper = new ObjectMapper();
            return mapper.writeValueAsString(obj);
        }
    }
    
    

    这里多出的两个方法用于回写数据,数据写进流中,只有流能在网络中传输

    @WebServlet("/category/*")
    public class CategoryServlet extends BaseServlet {
        private CategoryService service = new CategoryServiceImpl();
    
        protected void findAll(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            List<Category> cs = service.findAll();			 writeJsonBack(cs,response); }}
    

    另一种方法,将方法直接写在一个Servlet中,改写注解

    @WebServlet("/user/*")
    public class UserServlet extends BaseServlet {
        //复用代码的抽取
        private UserService userService = new UserServiceImpl();
    
        public void regist(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            .......
        }
    
        public void findOneUser(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            User user = (User) request.getSession().getAttribute("user");
            writeJsonBack(user, response);
        }
    
        public void exit(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            request.getSession().invalidate();
            response.sendRedirect(request.getContextPath() + "/login.html");
        }}
    
    

    Service

    servlet只用于前台和后台Service之间的交互桥梁,而Service用于Dao的连接,将查询到的数据给Servlet,再通过servlet回写给前台

    public class UserServiceImpl implements UserService {
        private UserDao userDao = new UserDaoImpl();
     @Override
        public User login(User user) {
    
            return userDao.findByUsernameAndPassword(user.getUsername(), user.getPassword());
        }	}
    

    Dao

    private JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());
    
        @Override
        public List<Category> findAll() {
            String sql = "select * from tab_category ";
            return template.query(sql, new BeanPropertyRowMapper<Category>(Category.class));
            //BeanPropertyRowMapper(Category.class) 按照Category.class,把数据写成类
        }
        
        public int findCountByRid(int rid) {
            String sql = "select count(*) from tab_favorite where rid = ?";
    
            return template.queryForObject(sql, Integer.class, rid);
        }
    	
    @Override
        public void add(int rid, int uid) {
            String sql = "insert into tab_favorite values(?,?,?)";
            template.update(sql, rid, new Date(), uid);
        }
    

    使用jdbc来连接数据库,按照返回类型的不同,使用不同的方法。

你可能感兴趣的:(项目实战)