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

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. 时间js转换方法Date("149...") 转成 2016-7-12 21:23:34 009

     function timeFormatter(value) {     var da = new Date(parseInt(value.replace("/Date(", &q ...

  2. Oracle数据库基础知识2

    字符操作相关_1 1.CONCAT关键字作用:连接字符串语法:CONCAT(字串1, 字串2)例如: CONCAT('hello','world') FROM DUAL; 注意:Oracle的CONC ...

  3. [dpdk] 熟悉SDK与初步使用 (四)(L3 Forwarding源码分析)

    接续前节:[dpdk] 熟悉SDK与初步使用 (三)(IP Fragmentation源码分析) 前文中的最后一个问题,搁置,并没有找到答案.所以继续阅读其他例子的代码,想必定能在其他位置看到答案. ...

  4. android studio 2.0 GPU Debugger使用说明

    GPU Debugger GPU Debugging Tools The GPU debugging tools are an experimental feature intended to hel ...

  5. HTML第二本书学习后记

    1,换行标记<br>,不换行标记<nobr></nobr> 2,添加水平线 <hr> 3,插入特殊符号:   空格 &nbsp    " ...

  6. RestTemplate配置

    什么是RestTemplate? RestTemplate是Spring提供的用于访问Rest服务的客户端,RestTemplate提供了多种便捷访问远程Http服务的方法,能够大大提高客户端的编写效 ...

  7. 水的demo

  8. 基于 debootstrap 和 busybox 构建 mini ubuntu

    基于 debootstrap 和 busybox 构建 mini ubuntu 最近的工作涉及到服务器自动安装和网络部署操作系统,然后使用 ansible 和 saltsatck 进行配置并安装 op ...

  9. Issue 1:sigmod 撞车

    11.6晚22:40,距离论文截止还有5天.在最后的紧要关头,竟然发现学术上撞车了,非常戏剧性的一幕,这么狗血的事情尽然就这么发生了. 自2015年8月份以来,本人一直在研究快速检查点领域.最近一篇t ...

  10. RDIFramework.NET ━ .NET快速信息化系统开发框架 记录所有操作的Sql

    在实际开发或试运行过程中,我们有时需要查看或分析模块执行的所有sql,以便进行相关分析.有时我们可以通过数据库自带的软件抓取,如:SQL Server Profiler.在我们RDIFramework ...