图片内容是所有的包名,文件名。

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包》

MVC简单分层思想(连接数据库)的更多相关文章

  1. 【blade的UI设计】理解前端MVC与分层思想

    前言 最近校招要来了,很多大三的同学一定按捺不住心中的焦躁,其中有期待也有彷徨,或许更多的是些许担忧,最近在开始疯狂的复习了吧 这里小钗有几点建议给各位: ① 不要看得太重,关心则乱,太紧张反而表现不 ...

  2. 初识mvc分层思想

    首先要清楚的是: mvc是一种设计模式,一种分层思想,没有具体的技术与之对应,无论是js还是java或者其他的技术都可以运用. 既然是分层那么这些层都有哪些职责呢? View层(界面层): 为用户展示 ...

  3. JavaWeb开发中的分层思想(一)

    JavaWeb开发分层思想(一) 一.认识DAO.Service.Controller层 DAO(Data Access Object) 1.直接看英文意思就是"数据访问对象",也 ...

  4. PHP中MVC的编程思想浅谈

    我相信这样的文章已经被写烂了,但是我今天还是愿意冒着风险把自己的经验与大家分享一下.纯属原创,我也没什么可保留,希望对新手有帮助,有说的什么不对的地方,欢迎大家伙吐槽. 什么是MVC? 简单的说就是将 ...

  5. 从Microsoft.AspNet.Identity看微软推荐的一种MVC的分层架构

    Microsoft.AspNet.Identity简介 Microsoft.AspNet.Identity是微软在MVC 5.0中新引入的一种membership框架,和之前ASP.NET传统的mem ...

  6. javaWeb中MVC的编程思想示例

    没有学习MVC之前我只写了一个Servlet类(Note_List.java),分层之后,我将这个类分成了5个类(NoteDao.java,,NoteDaoImpl.java,,NoteService ...

  7. 程序设计分层思想和DAO设计模式的开发

    无论是一个应用程序项目还是一个Web项目,我们都可以按照分层思想进行程序设计.对于分层,当下最流行划分方式是:表现层+控制层+业务层+数据层.其中,业务层和数据层被统称为后台业务层,而表现层和控制层属 ...

  8. RebotFrameWork的分层思想

    RebotFrameWork的分层思想 分层思想,就是通过关键字调用的方法,把大杂烩的代码根据脚本特征拆封开来,提高代码的灵活性和清晰度,从而也让一些组件层内容可扩展.可复用.可维护. 解析下目录结构 ...

  9. Robot Framework自动化测试(四)--- 分层思想

    谈到Robot  Framework 分层的思想,就不得不提“关键字驱动”. 关键字驱动: 通过调用的关键字不同,从而引起测试结果的不同. 在上一节的selenium API 中所介绍的方法其实就是关 ...

随机推荐

  1. 关于datagridview里使用combox的总结

    最近写的程序中需要在DataGridView中使用下拉选择的功能,首选方案是列的ColumnType属性 使用EditingControlShowing事件, if (e.Control is Com ...

  2. Spring 000 框架简介 (转载)

    转载自:https://my.oschina.net/myriads/blog/37922 1.使用框架的意义与Spring的主要内容 随着软件结构的日益庞大,软件模块化趋势出现,软件开发也需要多人合 ...

  3. 【Html 学习笔记】第二节——文本格式

    上一节基本已经了解了一些html的基础,这一节主要学习html处理文本相关内容,直接看内容吧. 字体: 预格式文本:<pre> 地址:<address> 缩写:<abbr ...

  4. win7 WindowsImageBackup 无法识别

    控制面板\所有控制面板项\备份和还原

  5. 什么是ValueStack

    转载自:http://www.cnblogs.com/zyw-205520/archive/2012/09/12/2681346.html Strut2的Action类通过属性可以获得所有相关的值,如 ...

  6. tomcat底层原理实现

    1.首先完成一个server类,用来接收客户端的请求:代码都在一个while(true)循环中,模拟tomcat一直在启动,其中绑定一个端口,用来监听一个端口,然后创建一个输入流,获取请求的输入流,然 ...

  7. docker在centos7下的一些坑

    在centos的docker上安装mysql提示chown mod /var/lib/mysql permission denied,通过下面的方法1解决. 在centos上挂载数据卷,在容器内部访问 ...

  8. Netty NIO 框架性能压测-短链接-对比Tomcat

    压测方案 准备多个文件大小分别为 1k 10k 100k 300k 使用ab分别按 [50,2000](按50逐渐叠加)压测服务,每次请求10W次 硬件信息:CPU:Intel(R) Xeon(R) ...

  9. Python--While循环语句

    Python While循环语句 Python 编程中 while 语句用于循环执行程序,即在某条件下,循环执行某段程序,以处理需要重复处理的相同任务.其基本形式为: while 判断条件: 执行语句 ...

  10. mac安装paramiko

    $ brew install openssl $ /usr/local/opt/openssl/bin/c_rehash $ export ARCHFLAGS="-arch x86_64&q ...