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包》
MVC简单分层思想(连接数据库)的更多相关文章
- 【blade的UI设计】理解前端MVC与分层思想
前言 最近校招要来了,很多大三的同学一定按捺不住心中的焦躁,其中有期待也有彷徨,或许更多的是些许担忧,最近在开始疯狂的复习了吧 这里小钗有几点建议给各位: ① 不要看得太重,关心则乱,太紧张反而表现不 ...
- 初识mvc分层思想
首先要清楚的是: mvc是一种设计模式,一种分层思想,没有具体的技术与之对应,无论是js还是java或者其他的技术都可以运用. 既然是分层那么这些层都有哪些职责呢? View层(界面层): 为用户展示 ...
- JavaWeb开发中的分层思想(一)
JavaWeb开发分层思想(一) 一.认识DAO.Service.Controller层 DAO(Data Access Object) 1.直接看英文意思就是"数据访问对象",也 ...
- PHP中MVC的编程思想浅谈
我相信这样的文章已经被写烂了,但是我今天还是愿意冒着风险把自己的经验与大家分享一下.纯属原创,我也没什么可保留,希望对新手有帮助,有说的什么不对的地方,欢迎大家伙吐槽. 什么是MVC? 简单的说就是将 ...
- 从Microsoft.AspNet.Identity看微软推荐的一种MVC的分层架构
Microsoft.AspNet.Identity简介 Microsoft.AspNet.Identity是微软在MVC 5.0中新引入的一种membership框架,和之前ASP.NET传统的mem ...
- javaWeb中MVC的编程思想示例
没有学习MVC之前我只写了一个Servlet类(Note_List.java),分层之后,我将这个类分成了5个类(NoteDao.java,,NoteDaoImpl.java,,NoteService ...
- 程序设计分层思想和DAO设计模式的开发
无论是一个应用程序项目还是一个Web项目,我们都可以按照分层思想进行程序设计.对于分层,当下最流行划分方式是:表现层+控制层+业务层+数据层.其中,业务层和数据层被统称为后台业务层,而表现层和控制层属 ...
- RebotFrameWork的分层思想
RebotFrameWork的分层思想 分层思想,就是通过关键字调用的方法,把大杂烩的代码根据脚本特征拆封开来,提高代码的灵活性和清晰度,从而也让一些组件层内容可扩展.可复用.可维护. 解析下目录结构 ...
- Robot Framework自动化测试(四)--- 分层思想
谈到Robot Framework 分层的思想,就不得不提“关键字驱动”. 关键字驱动: 通过调用的关键字不同,从而引起测试结果的不同. 在上一节的selenium API 中所介绍的方法其实就是关 ...
随机推荐
- partnerv2.1
2.1.实时获取产品价格(action=queryprice) 请求 { "useDate": "2016-04-05T19:56", //开始用车时间(当地时 ...
- 掌握Thinkphp3.2.0----SQL查询
首先,先谈一下对查询的理解:查询的对象是数据库中的数据表,一个或多个:查询的限制就是各种条件或要求:查询的结果=表对象+限制(条件). 对数据表的操作(CRUD)查询是最复杂也是最关键的一步!'SEL ...
- C# 构造post参数一种看起来直观点的方法[转]
因为本人经常爱用C#做一些爬虫类的小东西,每次构造post参数的时候,都是直接字符串拼接的方式的,有时候改起来不太方便. 场景: 需要post一个地址 参数列表 : username:管理员 pass ...
- GridView 实现LinkButton下载文件/附件
<asp:TemplateField > <ItemTemplate> <asp:LinkButton ID="lbtnDownFile" runat ...
- Qt程序打包(使用Enigma Virtual Box和BoxedApp Packer封包)
一.使用单文件封包工具 单文件封包工具,顾名思义就是将可执行文件及其相关依赖打包成单个可执行文件的工具. 这里推荐两个单文件封包工具:Enigma Virtual Box和BoxedApp Packe ...
- CentOS 6安装PostgreSQL
https://zh.wikipedia.org/wiki/PostgreSQL PostgreSQL是自由的对象-关系型数据库服务器(数据库管理系统),在灵活的BSD-风格许可证下发行.它在其他开放 ...
- django-- Models
数据库配置 django默认支持sqlite,MySQL,Oracle,postgresql数据库 如何将数据库设置为MySQL 将setting中的database修改: DATABASES = { ...
- java 给指定时间加上天数or给当前日期加天数
给指定日期加上天数: /** * 指定日期加上天数后的日期 * @param num 为增加的天数 * @param newDate 创建时间 * @return * @throws ParseExc ...
- blowfish ECB decode
blowfish ECB Decode package main import ( "crypto/cipher" "encoding/hex" " ...
- HTML初级入门内容
常用属性: Width=宽度 Height=高度 Size=大小 Color=颜色 Align=布局方向,值包括(top,bottom,left,right,center)上,下,左,右,中. Bor ...