2020-11-30
byYoutian
- 开发工具:idea
- Tomcat
- jar包:
- druid-1.1.9
- mysql-connector-java-5.1.7-bin.jar
- junit-4.12.jar
- commons-beanutils-1.8.0.jar
- hamcrest-core-1.3.jar
- 思维导图:
- 百度云链接:
链接:https://pan.baidu.com/s/1fk3tXcqhhZe5tufZLZ61wg
提取码:Yout
复制这段内容后打开百度网盘手机App,操作更方便哦--来自百度网盘超级会员V1的分享
- 百度云链接:
- 流程
代码块:
- POJO层User对象
- 用户名密码等属性
dao层 查询操作
- Userdao接口实现类
- dao接口的实现类
- dao层的Basedao dao层继承这个抽象类,dao层就可看起来简洁干净,专注于sql语句详情看笔记
- service层:
- service接口 判断是否登录或用户名是否存在的业务逻辑
- service接口的实现类
- utils工具类
- jdbcUtils jdbcUtils (阿里数据库池连接数据库) webUtils (beanutilsjar包注入useru对象)
- WebUtils
- web
- BaseServlet 这个抽象类的创建优化了从客户端发过来的数据通过反射去寻找对应子类的方法从而达到代码优化不需要大量的if(具体实现看代码快)
- UserServlet 有了BaseServlet就不需要去继承HttpServlet直接去继承抽象类做他的子类
- 里面有session代码块是以为我做过滤器用的过滤器的代码在最后一个初学者别忘记配置Servlet那个web.xml文件
package ink.youtian.pojo; public class User { private Integer id; private String username ; private String password; private String email ; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } @Override public String toString() { return "User{" + "id=" + id + ", username='" + username + '\'' + ", password='" + password + '\'' + ", email='" + email + '\'' + '}'; } public User() { } public User(Integer id, String username, String password, String email) { this.id = id; this.username = username; this.password = password; this.email = email; } }
package ink.youtian.dao; import ink.youtian.pojo.User; public interface UserDao { /** * 根据用户名查询用户信息 * @param username * @return 如何返回null 没有这个用户 */ public User queryUserByUsername(String username); /** * 根据用户名密码查询用户 * @param username * @param password * @return 如何返回null 说明用户名密码错误 */ public User queryUserByUsernameAndByPassword(String username ,String password); /** * 保持用户信息 * @param user * @return */ public int saveUser(User user); }
package ink.youtian.dao.impl; import ink.youtian.dao.UserDao; import ink.youtian.pojo.User; public class UserDaoImpl extends BaseDao implements UserDao { @Override public User queryUserByUsername(String username) { String sql = "select id,username,password,email from t_user where username = ?"; return queryForOne(User.class,sql,username) ; } @Override public User queryUserByUsernameAndByPassword(String username, String password) { String sql = "select id,username,password,email from t_user where username = ? and password = ? "; return queryForOne(User.class,sql,username,password) ; } @Override public int saveUser(User user) { String sql = "insert into t_user(`username`,`password`,`email`) values(?,?,?);\n"; return update(sql,user.getUsername(),user.getPassword(),user.getEmail()); } }
package ink.youtian.dao.impl;//工程路径 import ink.youtian.qiushao.utils.jdbcUtils; import org.apache.commons.dbutils.QueryRunner; import org.apache.commons.dbutils.handlers.BeanHandler; import org.apache.commons.dbutils.handlers.BeanListHandler; import org.apache.commons.dbutils.handlers.ScalarHandler; import java.sql.Connection; import java.sql.SQLException; import java.util.List; public abstract class BaseDao { //使用DbUtils操作数据库 private QueryRunner queryRunner = new QueryRunner(); /** * update() 方法用来执行:Insert\Update\Delete语句 * * @return 如果返回-1,说明执行失败<br/>返回其他表示影响的行数 */ public int update(String sql, Object... args) { System.out.println(" BaseDao 程序在[" +Thread.currentThread().getName() + "]中"); Connection connection = jdbcUtils.getConnection(); try { return queryRunner.update(connection, sql, args); } catch (SQLException e) { e.printStackTrace(); throw new RuntimeException(e); }finally { jdbcUtils.close(connection); } } /** * 查询返回一个javaBean的sql语句 * * @param type 返回的对象类型 * @param sql 执行的sql语句 * @param args sql对应的参数值 * @param <T> 返回的类型的泛型 * @return */ public <T> T queryForOne(Class<T> type, String sql, Object... args) { Connection con = jdbcUtils.getConnection(); try { return queryRunner.query(con, sql, new BeanHandler<T>(type), args); } catch (SQLException e) { e.printStackTrace(); throw new RuntimeException(e); }finally { jdbcUtils.close(con); } } /** * 查询返回多个javaBean的sql语句 * * @param type 返回的对象类型 * @param sql 执行的sql语句 * @param args sql对应的参数值 * @param <T> 返回的类型的泛型 * @return */ public <T> List<T> queryForList(Class<T> type, String sql, Object... args) { Connection con = jdbcUtils.getConnection(); try { return queryRunner.query(con, sql, new BeanListHandler<T>(type), args); } catch (SQLException e) { e.printStackTrace(); throw new RuntimeException(e); }finally { jdbcUtils.close(con); } } /** * 执行返回一行一列的sql语句 * @param sql 执行的sql语句 * @param args sql对应的参数值 * @return */ public Object queryForSingleValue(String sql, Object... args){ Connection conn =jdbcUtils.getConnection(); try { return queryRunner.query(conn, sql, new ScalarHandler(), args); } catch (SQLException e) { e.printStackTrace(); throw new RuntimeException(e); }finally { jdbcUtils.close(conn); } } }
package ink.youtian.utils; import org.apache.commons.beanutils.BeanUtils; import java.util.Map; public class WebUtils { /** * 把Map中的值注入到对应的JavaBean属性中。 * @param value * @param bean */ public static <T> T copyParamToBean( Map value , T bean ){ try { System.out.println("注入之前:" + bean); /* * * 把所有请求的参数都注入到user对象中 */ BeanUtils.populate(bean, value); System.out.println("注入之后:" + bean); } catch (Exception e) { e.printStackTrace(); } return bean; } /** * 将字符串转换成为int类型的数据 * @param strInt * @param defaultValue * @return */ public static int parseInt(String strInt,int defaultValue) { try { return Integer.parseInt(strInt); } catch (Exception e) { return defaultValue; } } }
package ink.youtian.web; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.lang.reflect.Method; public abstract class BaseServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doPost(req, resp); } protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // 解决post请求中文乱码问题 // 一定要在获取请求参数之前调用才有效 req.setCharacterEncoding("UTF-8"); String action = req.getParameter("action"); try { // 获取action业务鉴别字符串,获取相应的业务 方法反射对象 Method method = this.getClass().getDeclaredMethod(action, HttpServletRequest.class, HttpServletResponse.class); // System.out.println(method); // 调用目标业务 方法 method.invoke(this, req, resp); } catch (Exception e) { e.printStackTrace(); } } }
package ink.youtian.web; import ink.youtian.pojo.User; import ink.youtian.service.UserService; import ink.youtian.service.impl.UserServiceImpl; import ink.youtian.utils.WebUtils; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; public class UserServlet extends BaseServlet { private UserService userService = new UserServiceImpl(); protected void logout(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // 1,销毁session中的用户信息 req.getSession().invalidate(); // 2、重定向到首页 resp.sendRedirect(req.getContextPath()); } protected void login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //1、获取请求参数 String username = req.getParameter("username"); String password = req.getParameter("password"); //2、调用userServlet处理业务 User user = WebUtils.copyParamToBean(req.getParameterMap(), new User()); User login = userService.login(new User(null, username, password, null)); if (login == null){ //吧错误信息和回显信息保存在request域当中 req.setAttribute("error","用户名或密码错误"); req.setAttribute("username",username); req.getRequestDispatcher("/pages/user/login.jsp").forward(req,resp); }else { req.setAttribute("username",username); //保存用户登录到session域中 req.getSession().setAttribute("user",login); req.getRequestDispatcher("/pages/user/login_success.jsp").forward(req,resp); } } protected void regist(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //1.获取请求的参数 System.out.println("经过了"); String username = req.getParameter("username"); String password = req.getParameter("password"); String email = req.getParameter("email"); User user = new User(); if (userService.existsUsername(username)){ req.setAttribute("mgs","用户名已存在"); req.setAttribute("username",username); req.setAttribute("email",email); req.getRequestDispatcher("/pages/user/regist.jsp").forward(req,resp); }else { req.setAttribute("username",username); userService.registUeser(new User(null, username, password, email)); req.getRequestDispatcher("/pages/user/regist_success.jsp").forward(req,resp); } } }
package ink.youtian.web; import javax.servlet.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import java.io.IOException; public class FileServlet implements Filter { @Override public void init(FilterConfig filterConfig) throws ServletException { } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest httpServletRequest = (HttpServletRequest) request; HttpSession session = httpServletRequest.getSession(); Object user = session.getAttribute("user"); if (user==null){ request.getRequestDispatcher("/pages/user/login.jsp").forward(request,response); }else { chain.doFilter(request,response); } } @Override public void destroy() { } }
java开发,框架笔记记录