大概有一段时间没有进入blog写些东西了。今天我将利用DOM动态更新列表-(最终版源码Ajax+JSP+Servlet+Spring+SQL Server),奉献给大家。当然,还是那个宗旨喜欢就看看吧。
1、首先给出这个程序设计的流程
表现层:JSP+JavaScript+Ajax
控制层:Servlet
业务逻辑层:Spring的IOC容器
数据持久层:Spring中的JDBC
数据库层:由SQL Server提供支持
上面给出了程序设计的流程,那么我在程序设计的时候就是通过上述流程来实现的。
2、实现步骤如下
整个程序设计的步骤由数据持久层向表现层实现
第一:数据持久层
DAO接口实现代码:
package com.gxa.edu.spring.dao;
/**
*@author 国信安百杰
*/
import java.util.List;
import com.gxa.edu.spring.bean.Shopping;
public interface ShoppingDao {
int insertShopping(Shopping shopping);
int deleteShopping(Shopping shopping);
List queryShopping();
int queryMaxShoppingId();
}
实现DAO接口的类代码:
package com.gxa.edu.spring.dao.impl;
/**
*@author 国信安百杰
*/
import java.util.List;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
import com.gxa.edu.spring.bean.Shopping;
import com.gxa.edu.spring.dao.ShoppingDao;
import com.gxa.edu.spring.rowmapper.ShoppingRowMapper;
public class ShoppingDaoImpl extends JdbcDaoSupport implements ShoppingDao{
public int deleteShopping(Shopping shopping) {
// TODO Auto-generated method stub
String sql = "delete from shopping where shoppingName = ?";
Object[] obj = {shopping.getShoppingName()};
return getJdbcTemplate().update(sql, obj);
}
public int insertShopping(Shopping shopping) {
// TODO Auto-generated method stub
String sql = "insert into shopping values(?,?)";
Object[] obj = {shopping.getShoppingId(), shopping.getShoppingName()};
return getJdbcTemplate().update(sql, obj);
}
public List queryShopping() {
// TODO Auto-generated method stub
String sql = "select * from shopping";
return getJdbcTemplate().query(sql, new ShoppingRowMapper());
}
public int queryMaxShoppingId() {
// TODO Auto-generated method stub
String sql = "select max(shoppingId) from shopping";
return getJdbcTemplate().queryForInt(sql);
}
}
编写完上面的接口和类,那么就需要在Spring的配置文件中配置相应的信息
<bean id="shoppingDao" class="com.gxa.edu.spring.dao.impl.ShoppingDaoImpl">
<property name="dataSource">
<ref local="dataSource"/>
</property>
</bean>
实现Spring的RowMapper接口的类:
package com.gxa.edu.spring.rowmapper;
/**
*RowMapper接口主要是通过Spring对JDBC的封装将数据封装给一个JavaBean
*@author 国信安百杰
*/
import java.sql.ResultSet;
import java.sql.SQLException;
import org.springframework.jdbc.core.RowMapper;
import com.gxa.edu.spring.bean.Shopping;
public class ShoppingRowMapper implements RowMapper{
public Object mapRow(ResultSet arg0, int arg1) throws SQLException {
// TODO Auto-generated method stub
Shopping shopping = new Shopping();
shopping.setShoppingId(arg0.getInt("shoppingId"));
shopping.setShoppingName(arg0.getString("shoppingName"));
return shopping;
}
}
实现Shopping JavaBean的代码:
package com.gxa.edu.spring.bean;
/**
*@author 国信安百杰
*/
public class Shopping {
private int shoppingId;
private String shoppingName;
public int getShoppingId() {
return shoppingId;
}
public void setShoppingId(int shoppingId) {
this.shoppingId = shoppingId;
}
public String getShoppingName() {
return shoppingName;
}
public void setShoppingName(String shoppingName) {
this.shoppingName = shoppingName;
}
}
第二:业务逻辑层
package com.gxa.edu.spring.logic;
/**
*@author 国信安百杰
*/
import java.util.List;
import com.gxa.edu.spring.bean.Shopping;
import com.gxa.edu.spring.dao.ShoppingDao;
public class ShoppingLogic {
private ShoppingDao dao;
public void setDao(ShoppingDao dao) {
this.dao = dao;
}
public List queryShopping() {
return dao.queryShopping();
}
public int deleteShopping (Shopping shopping) {
return dao.deleteShopping(shopping);
}
public int insertShopping(Shopping shopping) {
return dao.insertShopping(shopping);
}
public int queryMaxShoppingId() {
return dao.queryMaxShoppingId();
}
}
业务逻辑类在Spring中配置信息
<bean id="shoppingLogic" class="com.gxa.edu.spring.logic.ShoppingLogic">
<property name="dao">
<ref local="shoppingDao"/>
</property>
</bean>
第三:控制层的实现
package com.gxa.edu.servlet;
/**
*@author 国信安百杰
*/
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 org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import com.gxa.edu.spring.bean.Shopping;
import com.gxa.edu.spring.logic.ShoppingLogic;
public class ShoppingServlet extends HttpServlet {
/**
* Constructor of the object.
*/
public ShoppingServlet() {
super();
}
/**
* Destruction of the servlet. <br>
*/
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
response.setContentType("text/xml; charset=UTF-8");
String name = request.getParameter("name");
String action = request.getParameter("action");
System.out.println("name===" + name);
System.out.println("action===" + action);
PrintWriter out = response.getWriter();
WebApplicationContext wc = WebApplicationContextUtils.getRequiredWebApplicationContext(this.getServletContext());
ShoppingLogic logic = (ShoppingLogic) wc.getBean("shoppingLogic");
if ("add".equals(action)) {
int i = logic.queryMaxShoppingId();
System.out.println(i);
Shopping shopping = new Shopping();
shopping.setShoppingId(i + 1);
shopping.setShoppingName(name);
if (logic.insertShopping(shopping) > 0) {
out.println("添加商品成功");
} else {
out.println("添加商品失败");
}
}
if ("del".equals(action)) {
Shopping shopping = new Shopping();
shopping.setShoppingName(name);
if (logic.deleteShopping(shopping) > 0) {
out.println("删除商品成功");
} else {
out.println("删除商品失败");
}
}
out.close();
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
/**
* Initialization of the servlet. <br>
*
* @throws ServletException if an error occure
*/
public void init() throws ServletException {
// Put your code here
}
}
第四:表现层的实现
表现层中创建一个dynamicShopping.jsp页面,在该页面里面编写了Ajax代码
<%@ page language="java" import = "java.util.*" pageEncoding="gb2312"%>
<%@ page import = "org.springframework.web.context.WebApplicationContext" %>
<%@ page import = "org.springframework.web.context.support.WebApplicationContextUtils" %>
<%@ page import = "com.gxa.edu.spring.logic.*" %>
<%@ page import = "com.gxa.edu.spring.bean.*" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>实现Web页面局部动态更新品牌信息</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
<link rel="stylesheet" type="text/css" href="images/css.css">
<script type="text/javascript">
var XMLHttpReq = false;
//创建XMLHttpRequest对象
function createXMLHttpRequest() {
if(window.XMLHttpRequest) { //Mozilla 浏览器
XMLHttpReq = new XMLHttpRequest();
}
else if (window.ActiveXObject) { // IE浏览器
try {
XMLHttpReq = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
XMLHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {}
}
}
}
//添加商品的相应函数
function addSortProcessResponse() {
if (XMLHttpReq.readyState == 4) {//和服务器端交互完毕
if (XMLHttpReq.status == 200) {//返回成功信息
addSortList();
}
}
}
//确认按钮出发事件函数
function addSort() {
var name = document.getElementById("name").value;
if (name == "") {
return;
}
var url = "ShoppingServlet?action=add" + "&name=" + name;
createXMLHttpRequest();
XMLHttpReq.open("GET", url, true);//建立服务器端连接
XMLHttpReq.onreadystatechange = addSortProcessResponse;//指定添加商品的相应函数
XMLHttpReq.send(null);
}
//一旦添加商品信息进入后台数据库,就执行此函数将信息打印到页面
function addSortList() {
var name = document.getElementById("name").value;
if (name == "") {
return;
}
var row = document.createElement("tr");
row.setAttribute("id", name);
var cell = document.createElement("td");
cell.appendChild(document.createTextNode(name));
row.appendChild(cell);
//添加删除按钮
var deleteButton = document.createElement("input");
deleteButton.setAttribute("type", "button");
deleteButton.setAttribute("value", "删除");
deleteButton.onclick = function () {deleteSort(name)};
cell = document.createElement("td");
cell.appendChild(deleteButton);
row.appendChild(cell);
//将设置好的元素动态添加到tbody里面
document.getElementById("sortList").appendChild(row);
//添加完品牌后就清空输入框
document.getElementById("name").value="";
}
//删除品牌信息相应函数
function deleteSortProcessResponse() {
if (XMLHttpReq.readyState == 4) {//和服务器端交互完毕
if (XMLHttpReq.status == 200) {//返回成功信息
window.alert("删除成功");
}
}
}
//删除品牌信息
function deleteSort(id) {
if (id != null) {
//var row = document.getElementById(id);
//var sorlist = document.getElementById("sortlist");
//sorlist.removeChild(row);
var url = "ShoppingServlet?action=del" + "&name=" + id;
createXMLHttpRequest();
XMLHttpReq.open("GET", url, true);//建立服务器端连接
XMLHttpReq.onreadystatechange = deleteSortProcessResponse;//指定添加商品的相应函数
XMLHttpReq.send(null);
clearSort(id);//清空表格中信息
}
}
//清空表格中信息
function clearSort(id) {
if (id != null) {
var row = document.getElementById(id);
var sorlist = document.getElementById("sortlist");
sorlist.removeChild(row);
}
}
</script>
</head>
<%
WebApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(getServletContext());
ShoppingLogic logic = (ShoppingLogic) ctx.getBean("shoppingLogic");
List list = logic.queryShopping();
%>
<body>
<table style="BORDER-COLLAPSE: collapse" bordercolor="#111111" cellspacing="0" cellpadding="2" width="400" bgcolor="#f5efe7" border="0">
<tr>
<td align="middle" height="4" colspan="3">
<img height="4" src="images/promo_list_top.gif" width="100%" border="0" alt="">
</td>
</tr>
<tr>
<td align="middle" bgcolor="#dbc2b0" height="19" colspan="3">
<b>品牌信息管理</b>
</td>
</tr>
<tr>
<td height="20">
增加新品牌:
</td>
<td height="20">
<input id="name" type="text" size="15">
</td>
<td height="20">
<img src="images/ok.gif" alt="">
</td>
</tr>
<tr>
<td height="20">
品牌信息管理:
</td>
</tr>
<table border="1" width="400">
<tr>
<td height="20" valign="top" align="center">
品牌名称:
</td>
<td id="pos_1" height="20">
操作
</td>
</tr>
<tbody id="sortList">
<%
for (int i = 0; i < list.size(); i++) {
Shopping shopping = (Shopping) list.get(i);%>
<tr id="<%=shopping.getShoppingName() %>">
<td><%=shopping.getShoppingName() %></td>
<td><input type="button" value="删除" ></input></td>
</tr>
<%}%>
</tbody>
</table>
</table>
</body>
</html>
最后,给出整个Spring的配置文件applicationContext.xml的代码
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
<!-- 配置SQL Server数据源 -->
<bean id="dataSource"
class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName">
<value>com.microsoft.jdbc.sqlserver.SQLServerDriver</value>
</property>
<property name="url">
<value>jdbc:microsoft:sqlserver://127.0.0.1:1433;DatabaseName=stu</value>
</property>
<property name="username">
<value>sa</value>
</property>
<property name="password">
<value>123456</value>
</property>
</bean>
<!-- =====DataSourceTransactionManager来对数据源进行事务管理===== -->
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource">
<ref local="dataSource" />
</property>
</bean>
<!-- =====TransactionProxyFactoryBean一个事务管理代理工厂bean,它是我们Spring中一个拦截器====== -->
<bean id="basicTransactionProxy"
class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean"
abstract="true">
<property name="transactionManager">
<ref local="transactionManager" />
</property>
<property name="transactionAttributes">
<props>
<prop key="get*">PROPAGATION_REQUIRED,readOnly</prop>
<prop key="insert*">PROPAGATION_REQUIRED</prop>
<prop key="update*">PROPAGATION_REQUIRED</prop>
</props>
</property>
<!-- <property name="proxyTargetClass" value="true"></property> -->
</bean>
<!-- ====配置ShoppingDao===== -->
<bean id="shoppingLogic" class="com.gxa.edu.spring.logic.ShoppingLogic">
<property name="dao">
<ref local="shoppingDao"/>
</property>
</bean>
<bean id="shoppingDao" class="com.gxa.edu.spring.dao.impl.ShoppingDaoImpl">
<property name="dataSource">
<ref local="dataSource"/>
</property>
</bean>
</beans>
3、总结
上面的代码其实在我们开发和运用肯定是微乎其微,但是在我们平时刚开始学习的时候,这段代码确实我们进步的基础。
要给大家说一下的是Spring框架的版本是1.2的。在applicationContext.xml文件加入了1.2版本的事务管理。Spring1.2版本的事务管理和高版本的有比较大的区别。当然,大家对Spring比较了解的可以使用高一些的版本,如Spring2.0或是Spring2.5.
运维网声明
1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网 享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com