当前位置: 代码迷 >> Web前端 >> javaEE中应用jquery实现单个页面的CURD
  详细解决方案

javaEE中应用jquery实现单个页面的CURD

热度:225   发布时间:2012-11-23 00:03:43.0
javaEE中使用jquery实现单个页面的CURD
[align=center]工具:eclipse 3  数据库:mysql 5.0

自己写的一个CURD使用了jquery插件jquery-impromptu.2.7.min.js,
一个页面实现一张表的增删改查,无任何跳转,访问很快
项目结构如下:

test数据库,user表
sql:
CREATE TABLE `user` (                   
`id` int(11) NOT NULL auto_increment, 
`username` varchar(12) default NULL,  
`addr` varchar(12) default NULL,      
PRIMARY KEY  (`id`)                   
)

util包代码:
-------------------------------------
UtilTool .java
package com.test.util;

import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.text.DecimalFormat;

/**
*
* @author zhaiyu
* @see 常用方法工具包
*/
public class UtilTool {
/*
* 验证字符串是否为空
*/
public static boolean isNotBlank(String temp) {
if (temp != null && !"".equals(temp)) {
return true;
} else {
return false;
}
}

/*
* 验证数字是否为空
*/
public static boolean isNotBlank(int temp) {
if (!"".equals(temp) && temp > 0) {
return true;
} else {
return false;
}
}

/*
* 验证数字是否有效
*/
public static boolean isNumAvaliable(int temp) {
if (!"".equals(temp) && temp > 0) {
return true;
} else {
return false;
}
}
}

DbConnection.java
package com.test.util;
import java.sql.Connection;
import java.sql.DriverManager;
public class DbConnection {
public static Connection getConnection(){
Connection con=null;
String CLASSFORNAME="com.mysql.jdbc.Driver";
String SERVANDDB="jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=UTF-8";
String USER="root";
String PWD="admin";
try{
Class.forName(CLASSFORNAME);
con=DriverManager.getConnection(SERVANDDB,USER,PWD);

}catch(Exception e){
e.printStackTrace();
}
return con;   
}

public static void main(String args []){
System.out.println(DbConnection.getConnection());
}
}

PaginationNotice.java
package com.test.util;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import com.test.model.User;

public class PaginationNotice {
private int allRows;
private int curPage = 1;
private int rowPerPage = 10;
private int allPages;

public int getRowPerPage() {
return rowPerPage;
}

public int getAllRows() {
return allRows;
}

public void setCurPage(int curPage) {
this.curPage = curPage;
}

public int getCurPage() {
return curPage;
}

public int getAllPages() {
return allPages;
}

public List<User> queryAll() {
List<User> list = new ArrayList<User>();
Statement stmt = null;
ResultSet rst = null;

try {
stmt = DbConnection.getConnection()
.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
rst = stmt.executeQuery("select * from user");
rst.last();
this.allRows = rst.getRow();
if (this.allRows % this.rowPerPage == 0) {
this.allPages = this.allRows / this.rowPerPage;
} else {
this.allPages = this.allRows / this.rowPerPage + 1;
}

if (this.curPage == 1) {
rst.beforeFirst();
} else {
rst.absolute((this.curPage - 1) * this.rowPerPage);
}

int i = 0;
while (rst.next() && i < this.rowPerPage) {
User user = new User();
user.setId(rst.getInt(1));
user.setUsername(rst.getString(2));
user.setAddr(rst.getString(3));

list.add(user);
i++;
}

} catch (SQLException e) {
e.printStackTrace();
}

return list;
}
}

model包代码:
-------------------------------------
User.java
package com.test.model;

public class User {
private int id;
private String username;
private String addr;

public int getId() {
return id;
}

public void setId(int id) {
this.id = id;
}

public String getUsername() {
return username;
}

public void setUsername(String username) {
this.username = username;
}

public String getAddr() {
return addr;
}

public void setAddr(String addr) {
this.addr = addr;
}

}

DAO包代码:
-------------------------------------
UserDAO.java
package com.test.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import com.test.model.User;
import com.test.util.DbConnection;

public class UserDAO {
private Connection con;

/** 通过id查询 */
public User queryById(String id) throws Exception {
con = DbConnection.getConnection();
PreparedStatement pstmt = null;
User user = null;
ResultSet rst = null;
try {
pstmt = con.prepareStatement("select * from user where id = ?");
pstmt.setString(1, id);
rst = pstmt.executeQuery();
while (rst.next()) {
user = new User();
user.setId(rst.getInt(1));
user.setUsername(rst.getString(2));
user.setAddr(rst.getString(3));
}
} catch (RuntimeException e) {
e.printStackTrace();
} finally {
con.close();
}
return user;
}

/** 增加一条记录 */
public void addRecord(User user) throws Exception {
con = DbConnection.getConnection();
PreparedStatement pstmt = null;
try {
pstmt = con.prepareStatement("insert into user (username,addr) values(?,?)");
pstmt.setString(1, user.getUsername());
pstmt.setString(2, user.getAddr());
pstmt.execute();
} catch (RuntimeException e) {
e.printStackTrace();
} finally {
con.close();
}
}

/** 删除一条记录 */
public void deleteRecord(int id) throws Exception {
con = DbConnection.getConnection();
PreparedStatement pstmt = null;
try {
pstmt = con.prepareStatement("delete from user where id = ?");
pstmt.setInt(1, id);
pstmt.execute();
} catch (RuntimeException e) {
e.printStackTrace();
} finally {
con.close();
}
}

/** 更新一条记录 */
public void update(User user) throws Exception {
con = DbConnection.getConnection();
PreparedStatement pstmt = null;
try {
pstmt = con.prepareStatement("update user set username=?,addr=? where id=?");
pstmt.setString(1, user.getUsername());
pstmt.setString(2, user.getAddr());
pstmt.setInt(3, user.getId());

pstmt.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
throw e;
} finally {
con.close();
}
}
}

service->itf包代码:
-------------------------------------
package com.test.service.itf;

import com.test.model.User;

/**
* @author zhaiyu
* @see 用户公告表的业务逻辑接口
* @version 2009.8.25
*/
public interface IUserService {
/** 查询一条记录 */
public User getoneRecord(String id) throws Exception;

/** 增加一条记录 */
public void addRecord(User user) throws Exception;

/** 删除一条记录 */
public void deleteUserById(int id) throws Exception;

/** 更新一条记录 */
public void update(User user) throws Exception;


}

service->impl包代码:
-------------------------------------
package com.test.service.impl;

import com.test.dao.UserDAO;
import com.test.model.User;
import com.test.service.itf.IUserService;


public class UserServiceImpl implements IUserService {
private UserDAO dao = new UserDAO();

/** 增加一条记录 */
public void addRecord(User user) throws Exception {
dao.addRecord(user);
}

/** 查询一条记录 */
public User getoneRecord(String id) throws Exception {
return dao.queryById(id);
}

/** 删除一条记录 */
public void deleteUserById(int id) throws Exception {
dao.deleteRecord(id);
}
/** 更新一条记录 */
public void update(User user) throws Exception {
dao.update(user);

}


controller包代码:
-------------------------------------
UserServlet.java
package com.test.controller;

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 com.test.model.User;
import com.test.service.impl.UserServiceImpl;
import com.test.service.itf.IUserService;
import com.test.util.UtilTool;


public class UserServlet extends HttpServlet {

private static final long serialVersionUID = -2446220534127375106L;
private IUserService userv = new UserServiceImpl();

public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String action = request.getParameter("action"); 


if ("del".equals(action)) {
String id = request.getParameter("id");
if (UtilTool.isNotBlank(id)) {
try {
userv.deleteUserById(Integer.parseInt(id));
PrintWriter out = response.getWriter();
out.println("删除成功!");
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}

if ("add".equals(action)) {
String username = request.getParameter("username");
String addr = request.getParameter("addr");
if (UtilTool.isNotBlank(username)&&UtilTool.isNotBlank(addr)) {
try {
User user = new User();
user.setUsername(username);
user.setAddr(addr);
userv.addRecord(user);
PrintWriter out = response.getWriter();
out.println("添加成功!");
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}

if ("update".equals(action)) {
String id = request.getParameter("id");
String username = request.getParameter("username");
if (UtilTool.isNotBlank(username) && UtilTool.isNotBlank(id)) {
try {
User user = new User();
int uid = Integer.parseInt(id);
user.setId(uid);
user.setUsername(username);

userv.update(user);
PrintWriter out = response.getWriter();
out.println("公告修改成功!");
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}

if ("query".equals(action)) {
String id = request.getParameter("id");
if (UtilTool.isNotBlank(id)) {
try {
User user = userv.getoneRecord(id);
if (user != null) {
PrintWriter out = response.getWriter();
out
.println("username:"
+ user.getUsername()
+ "<br>"
+ "address:"+user.getAddr());
out.flush();
out.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}

}

public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}

WEB-INF下web.xml
-------------------------------------
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<servlet>
<servlet-name>UserServlet</servlet-name>
<servlet-class>
com.test.controller.UserServlet
</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>UserServlet</servlet-name>
<url-pattern>/UserServlet.do</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>login.jsp</welcome-file>
</welcome-file-list>
</web-app>

WebRoot下useredit.jsp代码如下:
-------------------------------------
<%@ page language="java" pageEncoding="UTF-8"%>
<%@ page import="java.util.*" %>
<%@ page import="com.test.model.*" %>  
<%@ page import="com.test.util.*" %>  
<%@ page import="com.test.service.impl.*"%>
<%@ page import="com.test.service.itf.*"%> 
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>公告管理</title> 
<style>
* { margin:0; padding:0; font-size:12px;}
body{ background-color:#fff;}
#wrapper{ margin-left:auto; margin-right:auto; margin:30px;}
#wrapper h3{ font-size:18px;}
a{ text-decoration:none; color:#000;}
a:hover{ text-decoration:underline;}
table{border-collapse:collapse; cellpadding:10px;}
td,th {    border: 1px solid #000;    padding: 3px 5px 2px 5px;}

#pagination a{display:black;line-height:22px; text-align:center; width:45px; height:22px;border:1px #000 solid; background-color:#FFFFFF;}
#quit{display:black;line-height:22px; text-align:center; width:55px; height:22px;border:1px #000 solid; background-color:#FFFFFF;}
/*-------------impromptu---------- */
.jqifade{ position: absolute; background-color: #aaaaaa; }
div.jqi{ width: 400px; font-family: Verdana, Geneva, Arial, Helvetica, sans-serif; position: absolute; background-color: #ffffff; font-size: 11px; text-align: left; border: solid 1px #eeeeee; -moz-border-radius: 10px; -webkit-border-radius: 10px; padding: 7px; }
div.jqi .jqicontainer{ font-weight: bold; }
div.jqi .jqiclose{ position: absolute; top: 4px; right: -2px; width: 18px; cursor: default; color: #bbbbbb; font-weight: bold; }
div.jqi .jqimessage{ padding: 10px; line-height: 20px; color: #444444; }
div.jqi .jqibuttons{ text-align: right; padding: 5px 0 5px 0; border: solid 1px #eeeeee; background-color: #f4f4f4; }
div.jqi button{ padding: 3px 10px; margin: 0 10px; background-color: #2F6073; border: solid 1px #f4f4f4; color: #ffffff; font-weight: bold; font-size: 12px; }
div.jqi button:hover{ background-color: #728A8C; }
div.jqi button.jqidefaultbutton{ background-color: #BF5E26; }
.jqiwarning .jqi .jqibuttons{ background-color: #BF5E26; }
/*-------------------------------- */
</style>
<script language="javascript" src="js/jquery.min.js"></script>
<script type="text/javascript" src="js/jquery-impromptu.2.7.min.js"></script>
<script type="text/javascript">
//增加记录
function addNews(){
var txt = '用户名:<input id="username" name="username" /><br>地址:<input id="addr" name="addr" />';

function mysubmitfunc(v,m,f){
an = m.children('#content');
if(f.content == ""){
an.css("border","solid #ff0000 1px");
return false;
}

$.ajax({      
type:"POST",
url:"http://127.0.0.1:8080/webs/UserServlet.do?action=add",                      
data:"username="+f.username+"&addr="+f.addr,
success:function(msg){ 
$("#tips").css("color", "red");
$("#tips").html(msg);
window.location.reload(); 
}   
});
return true;  
}

//在对话框添加公告
$.prompt(txt,{ 
submit: mysubmitfunc,
buttons:{'确定':true}
});
}

//修改记录
function updateNews(){
var newsids = $("input:checked");

if(newsids.length == 0){
$("#tips").css("color", "red");
$("#tips").html("请选择你要进行操作的记录,对其进行操作!");
}
for(var i=0;i<newsids.length;i++){ 
if(newsids[i].checked){
var old = "";
//通过ajax获取原来的记录内容
$.ajax({      
type:"POST",
url:"http://127.0.0.1:8080/webs/UserServlet.do?action=query",
data:"id="+newsids[i].value,
async :false,
success:function(msg){  
old = msg;
}   
});

var txt = old+'<br><input type="hidden" id="id" name="id" value='+newsids[i].value+'>用户名:<input id="username" name="username" />';

function mysubmitfunc(v,m,f){
an = m.children('#username');
if(f.content == ""){
an.css("border","solid #ff0000 1px");
return false;
}
//ajax进行异步修改
$.ajax({      
type:"POST",
url:"http://127.0.0.1:8080/webs/UserServlet.do?action=update",                      
data:"id="+f.id+"&username="+f.username,
success:function(msg){ 
$("#tips").css("color", "red");
$("#tips").html(msg);
window.location.reload(); 
}   
});
return true;  
}

//在对话框修改公告
$.prompt(txt,{ 
submit: mysubmitfunc,
buttons:{'确定':true}
});
}
}
}

//删除记录
function deleteNews(){ 
var newsids = $("input:checked");

if(newsids.length == 0){
$("#tips").css("color", "red");
$("#tips").html("请选择你要进行操作的记录,对其进行操作!");
return;
}
for(var i=0;i<newsids.length;i++){ 
if(newsids[i].checked){

$.ajax({      
type:"POST",
url:"http://127.0.0.1:8080/webs/UserServlet.do?action=del",                      
data:"id="+newsids[i].value,
success:function(msg){ 
$("#tips").css("color", "red");
$("#tips").html(msg);
window.location.reload();
}   
});
}
}                
}

//查询 
$(function(){
$("td > a").click(function(){
var id = $(this).attr("name");

var old = "";
//通过ajax获取原来的记录内容
$.ajax({      
type:"POST",
url:"http://127.0.0.1:8080/webs/UserServlet.do?action=query",
data:"id="+id,
async :false,
success:function(msg){  
old = msg;
}   
});

var txt = old;

//在对话框添加公告
$.prompt(txt,{  
buttons:{'确定':true}
});

});
});
</script>
</head>
<body>
<div id="wrapper">
<h3>系统用户管理</h3>
<form action="" name="myform" method="post">
<table>
<tr>
<td>编号</td>          
<td>用户</td>
<td>地址</td>
</tr>
<%String str_curPage = request.getParameter("curPage");
PaginationNotice noticep = new PaginationNotice();
if(str_curPage!=null){
noticep.setCurPage(Integer.parseInt(str_curPage));
}
List<User> list = noticep.queryAll();
int allRows = noticep.getAllRows();
int allPages = noticep.getAllPages();
int curPage = noticep.getCurPage();
int rowPerPage = noticep.getRowPerPage();

for(int i=0;i<list.size();i++){
User user = list.get(i);
%>      
<tr>
<td><input type="checkbox" name="newsid" class="newsid" value="<%=user.getId()%>" /><%=(curPage-1)*rowPerPage+i+1%></td>          
<td><a href="#" name="<%=user.getId()%>"><%=user.getUsername()%></a></td>
<td><%=user.getAddr()%></td>
</tr>
<%}%>
</table>
<br>
<div id="pagination">
<a href="noticelist.jsp?curPage=1">首页</a>
<% if(curPage!=1){ %>
<a href="noticelist.jsp?curPage=<%=curPage-1 %>">上一页</a>
<%}if(allPages>=3){%>
<a href="noticelist.jsp?curPage=2">2</a>
<a href="noticelist.jsp?curPage=3">3</a>
<%}if(curPage!=allPages){ %>
<a href="noticelist.jsp?curPage=<%=curPage+1 %>">下一页</a>
<%} %>
<a href="noticelist.jsp?curPage=<%=allPages %>">末页</a>
</div> 
<br>
<input type="button" name="operate" value="增加"    onclick="addNews();"/>
<input type="button" name="operate" value="修改"    onclick="updateNews();"/>
<input type="button" name="operate" value="删除"    onclick="deleteNews();"/>
<br><br>
<p id="tips"></p>    
</form>
</div>
</body>
</html>

效果如下:
[/align]
  相关解决方案