注册功能-Servlet代码实现、Dao代码实现
Servlet代码实现
RegistUserServlet:
@WebServlet("/registUserServlet") public class RegistUserServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 1、获取数据 Map<String, String[]> map = request.getParameterMap(); // 2、封装对象 User user = new User(); try { BeanUtils.populate(user,map); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } // 3、调用service完成注册 UserService service = new UserServiceImpl(); boolean flag = service.regist(user); // 4、响应结果 ResultInfo info = new ResultInfo(); if (flag){ // 注册成功 info.setFlag(true); }else { // 注册失败 info.setFlag(false); info.setErrorMsg("注册失败"); } // 将info对象序列化为json ObjectMapper mapper = new ObjectMapper(); String string = mapper.writeValueAsString(info); // 将json数据写回客户端 // 设置content-type response.setContentType("application/json;charset=utf-8"); response.getWriter().write(string); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } }
Dao代码实现
UserDao接口:
public interface UserDao { /** * 根据用户名查询用户信息 * @param username * @return */ public User findByUsername(String username); /** * 用户保存 * @param user */ public void save(User user); }
UserDaoImpl实现类:
public class UserDaoImpl implements UserDao { private JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource()); @Override public User findByUsername(String username) { User user = null; try { // 定义sql String sql = "select * from tab_user where username = ?"; // 执行sql user = template.queryForObject(sql, new BeanPropertyRowMapper<>(User.class), username); } catch (Exception e) { } return user; } @Override public void save(User user) { // 1、定义sql String sql = "insert into tab_user(username,password,name,birthday,sex,telephone,email) values(?,?,?,?,?,?,?)"; // 2、执行sql template.update(sql,user.getUsername(),user.getPassword(),user.getName(),user.getBirthday() ,user.getSex(),user.getTelephone(),user.getEmail()); } }