MVC 实现的小实例
2015-07-15 15:45
501 查看
MVC 实现的小实例
在上一篇博文中我们搭建了一下开发环境。在这个基础上这一篇文章我们来讲一下mvc的实现,在Java web中开始采用的形式是model (JavaBean+jsp),但是后来发现这样写的话前后台的耦合度会增加,不利于系统的维护,为了避免牵一发而动全身,所以后来慢慢的诞生了model2(jsp+servlet+javaBean)这样就把前后台的耦合度给降低了,这样的实现是所谓的mvc下面我们来做一个demo;
step1:在elipse中建立一个java web动态工程,工程名称是mvcDemo,由于时间问题这里做的很简单主要是阐述一下思想:
step2:建立一个mysql数据库 mvcdb,里边有一张表table1:
step3:下载mysql-jdbc驱动包
下载
下载之后把这个jar复制到WEB-INF/lib中或者添加到external jar中都可以。
在工程下新建一个数据库操作类:dbUtils代码如下:
package com.soft.grand.Utils;
import java.util.*;
import java.sql.*;
import com.mysql.jdbc.Connection;
public class dbUtils {
public static String name = "root";
public static String pwd = "root";
public static String driver = "com.mysql.jdbc.Driver";
public static String connUrl = "jdbc:mysql://localhost:3306/mvcdb";
public static Connection conn;
public static Statement statement;
public static ResultSet rs;
public static int isRegist = 0; // 数据库驱动只可以注册一次,这是注册次数
/*
* 构造函数
*/
public dbUtils() {
}
private synchronized static Connection getConnection() {
try {
if (isRegist == 0) {
Class.forName(driver).newInstance();
isRegist = 1;
}
if (conn == null)
conn = (Connection) DriverManager.getConnection(connUrl, name,
pwd);
} catch (Exception e) {
e.printStackTrace();
}
return conn;
}
/*
* 执行修改,删除,插入等操作
*/
public synchronized static int updateOrInsert(String sql) {
int count = 0;
getConnection();
try {
statement = conn.createStatement();
count = statement.executeUpdate(sql);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (statement != null) {
statement.close();
statement = null;
}
if (conn != null) {
conn.close();
conn = null;
}
} catch (Exception e) {
e.printStackTrace();
}
}
return count;
}
/*
* 查询 返回List<map>
*/
public static synchronized List<Map> query(String sql) {
List<Map> list = null;
getConnection();
try {
statement = conn.createStatement();
rs = statement.executeQuery(sql);
if (rs != null) {
ResultSetMetaData data = rs.getMetaData();
int count = data.getColumnCount();
Map map = null;
list = new ArrayList<Map>();
while (rs.next()) {
map = new HashMap();
for (int i = 1; i <= count; i++) {
map.put(data.getColumnName(i), rs.getObject(i));
}
}
list.add(map);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (statement != null) {
statement.close();
statement = null;
}
if (conn != null) {
conn.close();
conn = null;
}
} catch (Exception e) {
e.printStackTrace();
}
}
return list;
}
/*
* 执行一条语句返回一个object对象
*/
public synchronized static Map getObject(String sql) {
getConnection();
Map map = null;
try {
statement = conn.createStatement();
rs = statement.executeQuery(sql);
while (rs.next()) {
map = new HashMap();
ResultSetMetaData data = rs.getMetaData();
int count = data.getColumnCount();
for (int i = 1; i <= count; i++) {
map.put(data.getColumnName(i), rs.getObject(i));
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (statement != null) {
statement.close();
statement = null;
}
if (conn != null) {
conn.close();
conn = null;
}
} catch (Exception e) {
e.printStackTrace();
}
}
return map;
}
}
tep4:在工程下创建两个jsp(show.jsp,index.jsp)与一个servlet,一个person类:queryInfo代码如下:
package com.soft.grand.Utils;
import java.io.IOException;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;
/**
* Servlet implementation class queryInfo
*/
@WebServlet("/queryInfo")
public class queryInfo extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public queryInfo() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see Servlet#init(ServletConfig)
*/
public void init(ServletConfig config) throws ServletException {
// TODO Auto-generated method stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doPost(request, response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
dbUtils utils = new dbUtils();
String sql = "select * from table1 where id=1";
// String sql="select * from table1";
Map map = null;
map = utils.getObject(sql);
// list=utils.query(sql);
person p = new person();
/*
* Iterator i=list.iterator(); while(i.hasNext()){ Map map=(Map)
* i.next(); System.out.print(map.get("name").toString()); }
*/
p.setName(map.get("name").toString());
p.setSex(map.get("sex").toString());
p.setPhone(map.get("phone").toString());
List list = new ArrayList();
list.add(p);
request.setAttribute("list", list);
request.getRequestDispatcher("/show.jsp").forward(request, response);
}
}
index.jsp:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="queryInfo" method=post">
<input type="submit"/>
</form>
</body>
</html>
show.jsp:
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<div>
<c:forEach var="list" items="${list}">
${list.name}
</c:forEach>
</div>
</body>
</html>
person:
package com.soft.grand.Utils;
public class person {
private int id;
private String name;
private String sex;
private String phone;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
}
这几个文件主要逻辑是这样的:首先发布工程index.jsp显示,这个页面会出现一个按钮,点击触发表单进去servlet 然后servlet中与数据库中对接操作,把数据存储在model person中然后在跳转去show.jsp中显示数据,在这里我用到了JSTL 标签,在show.jsp文件的头部可以看到有如下代码:
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%/>
换需要导入两个jar包:
点击下载
下载之后点击工程右键->properties->java build path->libary->add external jar 然后选中你的这来那个包,或者可以直接把这两个包复制到web-inf/lib下就ok
这就是一个简单的mvc 由于时间关系数据库 jsp页面都比较简单 主要是这个思路。
在上一篇博文中我们搭建了一下开发环境。在这个基础上这一篇文章我们来讲一下mvc的实现,在Java web中开始采用的形式是model (JavaBean+jsp),但是后来发现这样写的话前后台的耦合度会增加,不利于系统的维护,为了避免牵一发而动全身,所以后来慢慢的诞生了model2(jsp+servlet+javaBean)这样就把前后台的耦合度给降低了,这样的实现是所谓的mvc下面我们来做一个demo;
step1:在elipse中建立一个java web动态工程,工程名称是mvcDemo,由于时间问题这里做的很简单主要是阐述一下思想:
step2:建立一个mysql数据库 mvcdb,里边有一张表table1:
step3:下载mysql-jdbc驱动包
下载
下载之后把这个jar复制到WEB-INF/lib中或者添加到external jar中都可以。
在工程下新建一个数据库操作类:dbUtils代码如下:
package com.soft.grand.Utils;
import java.util.*;
import java.sql.*;
import com.mysql.jdbc.Connection;
public class dbUtils {
public static String name = "root";
public static String pwd = "root";
public static String driver = "com.mysql.jdbc.Driver";
public static String connUrl = "jdbc:mysql://localhost:3306/mvcdb";
public static Connection conn;
public static Statement statement;
public static ResultSet rs;
public static int isRegist = 0; // 数据库驱动只可以注册一次,这是注册次数
/*
* 构造函数
*/
public dbUtils() {
}
private synchronized static Connection getConnection() {
try {
if (isRegist == 0) {
Class.forName(driver).newInstance();
isRegist = 1;
}
if (conn == null)
conn = (Connection) DriverManager.getConnection(connUrl, name,
pwd);
} catch (Exception e) {
e.printStackTrace();
}
return conn;
}
/*
* 执行修改,删除,插入等操作
*/
public synchronized static int updateOrInsert(String sql) {
int count = 0;
getConnection();
try {
statement = conn.createStatement();
count = statement.executeUpdate(sql);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (statement != null) {
statement.close();
statement = null;
}
if (conn != null) {
conn.close();
conn = null;
}
} catch (Exception e) {
e.printStackTrace();
}
}
return count;
}
/*
* 查询 返回List<map>
*/
public static synchronized List<Map> query(String sql) {
List<Map> list = null;
getConnection();
try {
statement = conn.createStatement();
rs = statement.executeQuery(sql);
if (rs != null) {
ResultSetMetaData data = rs.getMetaData();
int count = data.getColumnCount();
Map map = null;
list = new ArrayList<Map>();
while (rs.next()) {
map = new HashMap();
for (int i = 1; i <= count; i++) {
map.put(data.getColumnName(i), rs.getObject(i));
}
}
list.add(map);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (statement != null) {
statement.close();
statement = null;
}
if (conn != null) {
conn.close();
conn = null;
}
} catch (Exception e) {
e.printStackTrace();
}
}
return list;
}
/*
* 执行一条语句返回一个object对象
*/
public synchronized static Map getObject(String sql) {
getConnection();
Map map = null;
try {
statement = conn.createStatement();
rs = statement.executeQuery(sql);
while (rs.next()) {
map = new HashMap();
ResultSetMetaData data = rs.getMetaData();
int count = data.getColumnCount();
for (int i = 1; i <= count; i++) {
map.put(data.getColumnName(i), rs.getObject(i));
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (statement != null) {
statement.close();
statement = null;
}
if (conn != null) {
conn.close();
conn = null;
}
} catch (Exception e) {
e.printStackTrace();
}
}
return map;
}
}
tep4:在工程下创建两个jsp(show.jsp,index.jsp)与一个servlet,一个person类:queryInfo代码如下:
package com.soft.grand.Utils;
import java.io.IOException;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;
/**
* Servlet implementation class queryInfo
*/
@WebServlet("/queryInfo")
public class queryInfo extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public queryInfo() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see Servlet#init(ServletConfig)
*/
public void init(ServletConfig config) throws ServletException {
// TODO Auto-generated method stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doPost(request, response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
dbUtils utils = new dbUtils();
String sql = "select * from table1 where id=1";
// String sql="select * from table1";
Map map = null;
map = utils.getObject(sql);
// list=utils.query(sql);
person p = new person();
/*
* Iterator i=list.iterator(); while(i.hasNext()){ Map map=(Map)
* i.next(); System.out.print(map.get("name").toString()); }
*/
p.setName(map.get("name").toString());
p.setSex(map.get("sex").toString());
p.setPhone(map.get("phone").toString());
List list = new ArrayList();
list.add(p);
request.setAttribute("list", list);
request.getRequestDispatcher("/show.jsp").forward(request, response);
}
}
index.jsp:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="queryInfo" method=post">
<input type="submit"/>
</form>
</body>
</html>
show.jsp:
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<div>
<c:forEach var="list" items="${list}">
${list.name}
</c:forEach>
</div>
</body>
</html>
person:
package com.soft.grand.Utils;
public class person {
private int id;
private String name;
private String sex;
private String phone;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
}
这几个文件主要逻辑是这样的:首先发布工程index.jsp显示,这个页面会出现一个按钮,点击触发表单进去servlet 然后servlet中与数据库中对接操作,把数据存储在model person中然后在跳转去show.jsp中显示数据,在这里我用到了JSTL 标签,在show.jsp文件的头部可以看到有如下代码:
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%/>
换需要导入两个jar包:
点击下载
下载之后点击工程右键->properties->java build path->libary->add external jar 然后选中你的这来那个包,或者可以直接把这两个包复制到web-inf/lib下就ok
这就是一个简单的mvc 由于时间关系数据库 jsp页面都比较简单 主要是这个思路。
相关文章推荐
- MySQL中的integer 数据类型
- java对世界各个时区(TimeZone)的通用转换处理方法(转载)
- java-注解annotation
- java-模拟tomcat服务器
- java-用HttpURLConnection发送Http请求.
- java-WEB中的监听器Lisener
- MySQL存储过程
- 分享微信开发Html5轻游戏中的几个坑
- Android IPC进程间通讯机制
- Android Native 绘图方法
- Android java 与 javascript互访(相互调用)的方法例子
- 介绍一款信息管理系统的开源框架---jeecg
- 聚类算法之kmeans算法java版本
- java实现 PageRank算法
- mysql中int、bigint、smallint 和 tinyint的区别与长度
- mysql load data 导出、导入 csv
- source命令执行SQL脚本文件
- PropertyChangeListener简单理解