MVC简单分层思想(连接数据库)
图片内容是所有的包名,文件名。
1.创建(M)模型
package oa.bean; public class User { private String userName; private String passWord; 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; } @Override public String toString() { return "User [userName=" + userName + ", passWord=" + passWord + "]"; } }
2.创建DAO层
创建Dao层接口 package oa.dao; import oa.bean.User; /** * @author Administrator * */ public interface IUserDao { public boolean login(User user); public boolean insert(User entity); } 2.创建Dao层实现类 package oa.dao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import oa.Util.JDBCuntl; import oa.bean.User; public class UserDaoImpl implements IUserDao { // 封装数据库操作属性 Connection conn = null; PreparedStatement pstm = null; ResultSet rs = null; // 第一步:声明返回值变量 boolean falg = false; // 登录 @Override public boolean login(User user) { // 第二步:获取连接对象 try { conn = JDBCuntl.getConnection(); // 第三步:声明sql语句 String sql = "select * from user"; // 第四步:根据sql语句创建预处理对象 pstm = conn.prepareStatement(sql); // 第五步:执行查询 rs = pstm.executeQuery(); // 第六步:判断 while (rs.next()) { String uname = rs.getString(1); String upwd = rs.getString(2); if (uname.equals(user.getUserName()) && upwd.equals(user.getPassWord())) { return true; } } } catch (Exception e) { e.printStackTrace(); } finally { // 第八步:释放资源 try { JDBCuntl.close(rs, pstm, conn); } catch (SQLException e) { e.printStackTrace(); } } // 判断 /* * if("admin".equals(user.getUserName()) && * "123456".equals(user.getPassWord())){ return true; }else{ return * false; } */ return false; } // 注册 @Override public boolean insert(User entity) { try { // 第二步:获取连接对象 conn = JDBCuntl.getConnection(); // 第三步:声明sql语句(插入) String sql = "insert into user(userName,passWord) values(?,?)"; // 第四步:根据sql语句出创建对象 pstm = conn.prepareStatement(sql); // 第五步:为占位符赋值 int index = 1; pstm.setObject(index++, entity.getUserName()); pstm.setObject(index++, entity.getPassWord()); // 第六步:执行语句 int i = pstm.executeUpdate(); // 第七步:判断执行 if (i > 0) { falg = true; } } catch (Exception e) { e.printStackTrace(); } finally { try { JDBCuntl.close(null, pstm, conn); } catch (SQLException e) { e.printStackTrace(); } } return falg; } }
3.创建Service层
1.创建service层接口 package oa.service; import oa.bean.User; public interface IUserService { public boolean login(User user); public boolean insert(User entity); } 2.创建service的实现类 package oa.service; import oa.bean.User; import oa.dao.IUserDao; import oa.dao.UserDaoImpl; public class UserServiceImpl implements IUserService { // 封装实体操作类 private IUserDao uDao = new UserDaoImpl(); @Override public boolean login(User user) { return uDao.login(user); } @Override public boolean insert(User entity) { return uDao.insert(entity); } }
4.建立一个工具链接数据库
package oa.Util; import java.sql.*; import java.util.Properties; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; /** * 获取数据库连接对象的工具类 * @author Administrator * @version 1.0 */ public class JDBCuntl { private static String driverClass = null; private static String url = null; private static String user = null; private static String password = null; //通过静态块获取jdbc.properties中的数据库驱动信息并初始化静态成员变量 static{ Properties props = new Properties(); InputStream is = JDBCuntl.class.getClassLoader().getResourceAsStream("jdbc.properties"); try { props.load(is); driverClass = props.getProperty("jdbc.driver"); url = props.getProperty("jdbc.url"); user = props.getProperty("jdbc.user"); password = props.getProperty("jdbc.password"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } /*driverClass="com.mysql.jdbc.Driver"; url="jdbc:mysql://localhost:3306/user"; user="root"; password="1";*/ } /** * 根据获取的数据库驱动信息来创建数据库连接对象并返回 * @return 连接对象 * @throws Exception */ public static Connection getConnection() throws Exception{ Connection conn = null; Class.forName(driverClass); conn = DriverManager.getConnection(url, user, password); return conn; } /** * 统一关闭JDBC资源的方法 * @param rs 结果集对象 * @param stmt 语句对象 * @param conn 连接对象 * @throws SQLException */ public static void close(ResultSet rs,Statement stmt,Connection conn) throws SQLException{ if(rs != null){ rs.close(); rs = null; } if(stmt != null){ stmt.close(); stmt = null; } if(conn != null){ conn.close(); conn = null; } } } 其中的文件是方便读取数据库,也方便更改数据库 文件内容是: jdbc.driver=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://127.0.0.1:3306/user jdbc.user=root jdbc.password=1 如果连接数据库有问题,可以测试数据库 测试代码: package oa.Util; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; public class TestUtil { /** * @param args */ public static void main(String[] args) { try { Connection conn=JDBCuntl.getConnection(); PreparedStatement psmt=conn.prepareStatement("select * from user"); ResultSet rs=psmt.executeQuery(); while (rs.next()) { System.out.println(rs.getString(1)+"\t"+rs.getString(2)); } JDBCuntl.close(rs, psmt, conn); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
5.创建Servlet(控制器 C)
package oa.servlet; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class LoginSuccess extends HttpServlet { /** * Constructor of the object. */ public LoginSuccess() { super(); } /** * Destruction of the servlet. <br> */ public void destroy() { super.destroy(); // Just puts "destroy" string in log // Put your code here } /** * The doGet method of the servlet. <br> * * This method is called when a form has its tag value method equals to get. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } /** * The doPost method of the servlet. <br> * * This method is called when a form has its tag value method equals to post. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=utf-8"); PrintWriter out = response.getWriter(); out.println("登录成功!欢迎你:" + request.getParameter("user")); out.flush(); out.close(); } /** * Initialization of the servlet. <br> * * @throws ServletException if an error occurs */ public void init() throws ServletException { // Put your code here } }
6.创建登录页面,注册页面
<!DOCTYPE html> <html> <head> <title>Login.html</title> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="this is my page"> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <!--<link rel="stylesheet" type="text/css" href="./styles.css">--> <script type="text/javascript"> function register() { window.location = "register.html"; } </script> </head> <body> <h1>欢迎使用XXXX点餐系统</h1> <form action="LoginServlet" method="post"> 用户名:<input type="text" name="user"><br> <br> 密码:<input type="password" name="pwd"><br> <br> <input type="submit" value="提交"> <input type="button" value="注册" onclick="register()"> <input type="reset" value="重置"> </form> </body> </html>
7.创建一些跳转页面(成功,失败页面)
成功页面 此处用servlet实现 response.setContentType("text/html;charset=utf-8"); PrintWriter out = response.getWriter(); out.println("登录成功!欢迎你:" + request.getParameter("user")); out.flush(); out.close(); 失败页面 response.setContentType("text/html;charset=utf-8"); PrintWriter out = response.getWriter(); out.print("登录失败!用户名或者密码错误!"); out.flush(); out.close();
8.创建注册页面和注册成功失败页面
package oa.servlet; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import oa.bean.User; import oa.service.IUserService; import oa.service.UserServiceImpl; public class RegisterService extends HttpServlet { /** * Constructor of the object. */ public RegisterService() { super(); } /** * Destruction of the servlet. <br> */ public void destroy() { super.destroy(); // Just puts "destroy" string in log // Put your code here } /** * The doGet method of the servlet. <br> * * This method is called when a form has its tag value method equals to get. * * @param request * the request send by the client to the server * @param response * the response send by the server to the client * @throws ServletException * if an error occurred * @throws IOException * if an error occurred */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } /** * The doPost method of the servlet. <br> * * This method is called when a form has its tag value method equals to * post. * * @param request * the request send by the client to the server * @param response * the response send by the server to the client * @throws ServletException * if an error occurred * @throws IOException * if an error occurred */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=utf-8"); PrintWriter out = response.getWriter(); // 获取用户输入的数据 String userName = request.getParameter("user"); String passWord = request.getParameter("pwd"); request.setCharacterEncoding("UTF-8"); // 创建实体类 User entity = new User(); // 为实体对象赋值 entity.setUserName(userName); entity.setPassWord(passWord); // 调用Service层实现用户登录业务 IUserService uService = new UserServiceImpl(); boolean falg = uService.insert(entity); if (falg==true) { response.sendRedirect("rSuccess.html"); }else{ response.sendRedirect("rFail.html"); } out.flush(); out.close(); } /** * Initialization of the servlet. <br> * * @throws ServletException * if an error occurs */ public void init() throws ServletException { // Put your code here } }
注册页面 <!DOCTYPE html> <html> <head> <title>register.html</title> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="this is my page"> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <!--<link rel="stylesheet" type="text/css" href="./styles.css">--> </head> <body> <form action="RegisterService" method="post"> 用户姓名:<input type="text" name="user"><br/><br/> 密码:<input type="password" name="pwd"><br/><br/> <input type="submit" name="提交" value="提交"><br/> </form> </body> </html> 成功页面 <!DOCTYPE html> <html> <head> <title>rSuccess.html</title> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="this is my page"> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <!--<link rel="stylesheet" type="text/css" href="./styles.css">--> </head> <body> <font color="red" size="6">注册成功</font> </body> </html> 失败页面 <!DOCTYPE html> <html> <head> <title>rFail.html</title> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="this is my page"> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <!--<link rel="stylesheet" type="text/css" href="./styles.css">--> </head> <body> <font color="red" size="6">注册失败</font> </body> </html>
此处一定要在webRoot下的
WEB—INF下的
lib文件内将数据库jar包导入《一定要导入jar包》