一个不错的样例值得细细品味:

以下依照包顺序将代码贴出来供大家參考:

IEmpDAO

package org.lzch.dao;

import java.util.List;

import org.lzch.vo.Emp;

public interface IEmpDAO {
public boolean doCreate(Emp emp)throws Exception;
public boolean doUpdate(Emp emp)throws Exception;
public boolean doDelete(int empno)throws Exception;
public List findAll(int currentPage,int lineSize,String keyword)throws Exception;
public int getAllCount(String keyword)throws Exception;
public Emp findEmpById(int empno)throws Exception;
public boolean getAllEname(String ename)throws Exception;
}

EmpDAOImpl

package org.lzch.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List; import org.lzch.dao.IEmpDAO;
import org.lzch.vo.Emp; public class EmpDAOImpl implements IEmpDAO {
private Connection conn=null;
public EmpDAOImpl(Connection conn){
this.conn=conn;
}
//加入用户信息
public boolean doCreate(Emp emp) throws Exception {
// TODO Auto-generated method stub
boolean flag=false;
PreparedStatement pstmt=null;
try{
this.conn.setAutoCommit(false); //手动提交
String sql="INSERT INTO emp1(empno,ename,job,hiredate,sal,comm,photo)VALUES(?,?,?,?,?,? ,?)";
pstmt=this.conn.prepareStatement(sql);
pstmt.setInt(1, emp.getEmpno());
pstmt.setString(2, emp.getEname());
pstmt.setString(3, emp.getJob());
pstmt.setDate(4, new java.sql.Date(emp.getHiredate().getTime()));
pstmt.setFloat(5, emp.getSal());
pstmt.setFloat(6, emp.getComm());
pstmt.setString(7, emp.getPhoto());
int count=pstmt.executeUpdate();
this.conn.commit(); //提交
if(count>0){
flag=true;
}
}catch(Exception e){
this.conn.rollback();
}finally{
try{
pstmt.close();
}catch(Exception e){
throw e;
}
}
return flag;
}
//删除
public boolean doDelete(int empno) throws Exception {
// TODO Auto-generated method stub
boolean flag=false;
PreparedStatement pstmt=null;
try{
String sql="DELETE FROM emp1 WHERE empno=? ";
pstmt=this.conn.prepareStatement(sql);
pstmt.setInt(1, empno);
int count=pstmt.executeUpdate();
if(count>0){
flag=true;
}
}catch(Exception e){
throw e;
}finally{
try{
pstmt.close();
}catch(Exception e){
throw e;
}
}
return flag;
}
//更新
public boolean doUpdate(Emp emp) throws Exception {
// TODO Auto-generated method stub
boolean flag=false;
PreparedStatement pstmt=null;
try{
String sql="UPDATE emp1 SET ename=?,job=? ,hiredate=?,sal=?,comm=?,photo=? WHERE empno=?";
pstmt=this.conn.prepareStatement(sql);
pstmt.setString(1, emp.getEname());
pstmt.setString(2, emp.getJob());
pstmt.setDate(3, new java.sql.Date(emp.getHiredate().getTime()));
pstmt.setFloat(4, emp.getSal());
pstmt.setFloat(5, emp.getComm());
pstmt.setString(6, emp.getPhoto());
pstmt.setInt(7, emp.getEmpno());
int count=pstmt.executeUpdate();
System.out.println("emp_UPDATE_SQL==="+sql);
if(count>0){
flag=true;
}
}catch(Exception e){
throw e;
}finally{
try{
pstmt.close();
}catch(Exception e){
throw e;
}
}
return flag;
}
//查询全部信息
public List findAll(int currentPage, int lineSize, String keyword)
throws Exception {
// TODO Auto-generated method stub
List all=new ArrayList();
PreparedStatement pstmt=null;
String sql=null;
if(keyword==null||"".equals(keyword)){
sql="SELECT TOP "+lineSize+" empno,ename,job,hiredate,sal,comm,photo FROM " +
"(SELECT TOP "+lineSize+" empno,ename,job,hiredate,sal,comm,photo FROM " +
"(SELECT TOP "+currentPage*lineSize+" * FROM emp1 ORDER BY empno ASC)temptlb1 ORDER BY empno DESC)temptlb2 ORDER BY empno asc";
}else{
sql="SELECT empno,ename,job,hiredate,sal,comm,photo FROM emp1 WHERE empno LIKE '%"+keyword+"%' " +
"OR ename LIKE '%"+keyword+"%' OR job LIKE '%"+keyword+"%' OR hiredate LIKE '%"+keyword+"%'" +
" OR sal LIKE '%"+keyword+"%' OR comm LIKE '%"+keyword+"%' ";
}
try{
pstmt=this.conn.prepareStatement(sql);
// pstmt.setString(1, "%"+keyword+"%");
// pstmt.setString(2, "%"+keyword+"%");
// pstmt.setString(3, "%"+keyword+"%");
// pstmt.setString(4, "%"+keyword+"%");
// pstmt.setString(5, "%"+keyword+"%");
// pstmt.setString(6, "%"+keyword+"%");
System.out.println(sql);
ResultSet rs=pstmt.executeQuery();
Emp emp=null;
while(rs.next()){
emp=new Emp();
emp.setEmpno(rs.getInt(1));
emp.setEname(rs.getString(2));
emp.setJob(rs.getString(3));
emp.setHiredate(rs.getDate(4));
emp.setSal(rs.getFloat(5));
emp.setComm(rs.getFloat(6));
emp.setPhoto(rs.getString(7));
all.add(emp);
}
}catch(Exception e){
throw e;
}finally{
try{
pstmt.close();
}catch(Exception e){
throw e;
}
}
return all;
}
//按ID查询
public Emp findEmpById(int empno) throws Exception {
// TODO Auto-generated method stub
Emp emp=null;
PreparedStatement pstmt=null;
try{
String sql="SELECT empno,ename,job,hiredate,sal,comm,photo FROM emp1 WHERE empno=?";
pstmt=this.conn.prepareStatement(sql);
pstmt.setInt(1, empno);
ResultSet rs=pstmt.executeQuery();
if(rs.next()){
emp=new Emp();
emp.setEmpno(rs.getInt(1));
emp.setEname(rs.getString(2));
emp.setJob(rs.getString(3));
emp.setHiredate(rs.getDate(4));
emp.setSal(rs.getFloat(5));
emp.setComm(rs.getFloat(6));
emp.setPhoto(rs.getString(7));
}
}catch(Exception e){
throw e;
}finally{
try{
pstmt.close();
}catch(Exception e){
throw e;
}
}
return emp;
}
//查询数据表里 记录集
public int getAllCount(String keyword) throws Exception {
// TODO Auto-generated method stub
int count=0;
PreparedStatement pstmt=null;
try{
String sql="SELECT COUNT(empno) FROM emp1 WHERE empno LIKE ? OR ename LIKE ? " +
"OR job LIKE ? OR hiredate LIKE ? OR sal LIKE ? OR comm LIKE ? OR photo LIKE ? ";
pstmt=this.conn.prepareStatement(sql);
pstmt.setString(1, "%"+keyword+"%");
pstmt.setString(2, "%"+keyword+"%");
pstmt.setString(3, "%"+keyword+"%");
pstmt.setString(4, "%"+keyword+"%");
pstmt.setString(5, "%"+keyword+"%");
pstmt.setString(6, "%"+keyword+"%");
pstmt.setString(7, "%"+keyword+"%");
ResultSet rs=pstmt.executeQuery();
if(rs.next()){
count=rs.getInt(1); //返回数据表里的全部数据集 geeInt(1):方法。查询表里全部数据集
}
}catch(Exception e){
throw e;
}finally{
try{
pstmt.close();
}catch(Exception e){
throw e;
}
}
return count;
}
//验证username是否存在
public boolean getAllEname(String ename)throws Exception{
boolean flag=false;
PreparedStatement pstmt=null;
try{
String sql="SELECT COUNT(ename) FROM emp1 WHERE ename=? ";
pstmt=this.conn.prepareStatement(sql);
pstmt.setString(1, ename);
ResultSet rs=pstmt.executeQuery();
if(rs.next()){
if(rs.getInt(1)>0){
flag=true;
System.out.println("impl===flag=="+rs.getInt(1));
System.out.println("impl===flag=="+flag);
}else{
flag=false;
}
}
}catch(Exception e){
throw e;
}finally{
try{
pstmt.close();
}catch(Exception e){
throw e;
}
}
return flag;
}
}

EmpDAOProxy

package org.lzch.dao.proxy;

import java.util.List;

import org.lzch.dao.IEmpDAO;
import org.lzch.dao.impl.EmpDAOImpl;
import org.lzch.dbc.DatabaseConnection;
import org.lzch.vo.Emp; public class EmpDAOProxy implements IEmpDAO {
private DatabaseConnection dbc=null;
private IEmpDAO dao=null;
int count=0;
public EmpDAOProxy(){
try{
this.dbc=new DatabaseConnection();
}catch(Exception e){
e.printStackTrace();
}
this.dao=new EmpDAOImpl(this.dbc.getConnection());
} public boolean doCreate(Emp emp) throws Exception {
// TODO Auto-generated method stub
boolean flag=false;
try{
if(this.dao.findEmpById(emp.getEmpno())==null){
flag=this.dao.doCreate(emp); //调用真实主题类
}
}catch(Exception e){
throw e;
}finally{
try{
this.dbc.closeConnection();
}catch(Exception e){
throw e;
}
}
return flag;
} public boolean doDelete(int empno) throws Exception {
// TODO Auto-generated method stub
boolean flag=false;
try{
flag=this.dao.doDelete(empno); //调用真实主题类
}catch(Exception e){
throw e;
}finally{
try{
this.dbc.closeConnection();
}catch(Exception e){
throw e;
}
}
return flag;
} public boolean doUpdate(Emp emp) throws Exception {
// TODO Auto-generated method stub
boolean flag=false;
try{
flag=this.dao.doUpdate(emp); //调用真实主题类
}catch(Exception e){
throw e;
}finally{
try{
this.dbc.closeConnection();
}catch(Exception e){
throw e;
}
}
return flag;
} public List findAll(int currentPage, int lineSize, String keyword)
throws Exception {
// TODO Auto-generated method stub
List all=null;
try{
all=this.dao.findAll(currentPage, lineSize, keyword); //调用真实主题类
count=this.dao.getAllCount(keyword); //取得最大记录数 //调用真实主题类
}catch(Exception e){
throw e;
}finally{
try{
this.dbc.closeConnection();
}catch(Exception e){
throw e;
}
}
return all;
} public Emp findEmpById(int empno) throws Exception {
// TODO Auto-generated method stub
Emp emp=null;
try{
emp=this.dao.findEmpById(empno); //调用真实主题类
}catch(Exception e){
throw e;
}finally{
try{
this.dbc.closeConnection();
}catch(Exception e){
throw e;
}
}
return emp;
} public int getAllCount(String keyword) throws Exception {
// TODO Auto-generated method stub
return this.count;
} public boolean getAllEname(String ename)throws Exception{
boolean flag=false;
try{
flag=this.dao.getAllEname(ename);
}catch(Exception e){
throw e;
}finally{
try{
this.dbc.closeConnection();
}catch(Exception e){
throw e;
}
}
return flag;
}
}

DatabaseConnection

package org.lzch.dbc;

import java.sql.Connection;
import java.sql.DriverManager; public class DatabaseConnection {
private static final String DBDRIVER="com.microsoft.sqlserver.jdbc.SQLServerDriver";
private static final String DBURL="jdbc:sqlserver://localhost:1433;DatabaseName=login";
private static final String DBUSER="sa";
private static final String DBPASSWORD="000000";
private Connection conn=null;
public DatabaseConnection(){
try{
Class.forName(DBDRIVER);
this.conn=DriverManager.getConnection(DBURL,DBUSER,DBPASSWORD);
}catch(Exception e){
e.printStackTrace();
}
}
public Connection getConnection(){
return this.conn;
}
public void closeConnection(){
if(this.conn!=null){
try{
this.conn.close();
}catch(Exception e){
e.printStackTrace();
}
}
}
}

DAOFactory

package org.lzch.factory;

import org.lzch.dao.IEmpDAO;
import org.lzch.dao.proxy.EmpDAOProxy; public class DAOFactory {
public static IEmpDAO getIEmpDAOInstance(){
return new EmpDAOProxy();
}
}

EmpEncodingFilter

package org.lzch.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse; public class EmpEncodingFilter implements Filter {
private String charset=null;
public void destroy() {
// TODO Auto-generated method stub } public void doFilter(ServletRequest req, ServletResponse resp,
FilterChain chain) throws IOException, ServletException {
// TODO Auto-generated method stub
req.setCharacterEncoding(this.charset);
chain.doFilter(req, resp);
} public void init(FilterConfig config) throws ServletException {
// TODO Auto-generated method stub
this.charset=config.getInitParameter("charset");
} }

EmpServlet

package org.lzch.servlet;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List; import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import org.lzch.factory.DAOFactory;
import org.lzch.util.IPTimeStamp;
import org.lzch.vo.Emp; import com.jspsmart.upload.SmartUpload; public class EmpServlet extends HttpServlet {
public void service(HttpServletRequest req,HttpServletResponse resp)throws ServletException,IOException{
String p=req.getParameter("p");
if(p.equals("emp_insert")){
this.doCreate(req, resp);
}
if(p.equals("doUpdatePage")){
this.doUpdatePage(req, resp);
}
if(p.equals("doUpdate")){
this.doUpdate(req, resp);
}
if(p.equals("doDelete")){
this.doDelete(req, resp);
}
if(p.equals("getAllEname")){
this.getAllEname(req, resp);
}
}
public void doCreate(HttpServletRequest req,HttpServletResponse resp)throws ServletException,IOException{
List all=new ArrayList();
SmartUpload smart=new SmartUpload();
Emp emp=new Emp();
int empno=0;
String ename=null;
String job=null;
Date hiredate=null;
float sal=0.0f;
float comm=0.0f;
String photo="nophoto.jpg";
try{
smart.initialize(this.getServletConfig(),req,resp); //初始化上传
smart.upload(); //准备上传 empno=Integer.parseInt(smart.getRequest().getParameter("empno"));
ename=smart.getRequest().getParameter("ename");
job=smart.getRequest().getParameter("job");
hiredate=new SimpleDateFormat("yyyy-mm-dd").parse(smart.getRequest().getParameter("hiredate"));
sal=Float.parseFloat(smart.getRequest().getParameter("sal"));
comm=Float.parseFloat(smart.getRequest().getParameter("comm"));
if(smart.getFiles().getFile(0).getSize()>0){ //推断是否有上传文件
IPTimeStamp its=new IPTimeStamp(req.getRemoteAddr());
//拼凑上传文件名
photo=its.getIPTimeStampRand()+"."+smart.getFiles().getFile(0).getFileExt();
}
emp.setEmpno(empno);
emp.setEname(ename);
emp.setJob(job);
emp.setHiredate(hiredate);
emp.setSal(sal);
emp.setComm(comm);
emp.setPhoto(photo);
if(DAOFactory.getIEmpDAOInstance().doCreate(emp)){
if(smart.getFiles().getFile(0).getSize()>0){
//加入成功,保存上传文件
smart.getFiles().getFile(0).saveAs(getServletContext().getRealPath("/")+"jsp/upload/"+photo);
}
all.add("职员信息加入成功! ");
}else{
all.add("职员信息加入失败!");
}
}catch(Exception e){
e.printStackTrace();
}
req.setAttribute("infoInsert", all);
req.getRequestDispatcher("jsp/admin/emp/emp_insert_do.jsp").forward(req, resp);
}
public void doUpdatePage(HttpServletRequest req,HttpServletResponse resp)throws ServletException,IOException{
int empno=0;
Emp emp=null;
try{
empno=Integer.parseInt(req.getParameter("empno"));
emp=DAOFactory.getIEmpDAOInstance().findEmpById(empno);
}catch(Exception e){
e.printStackTrace();
}
req.setAttribute("infoUpdatePage", emp);
req.getRequestDispatcher("jsp/admin/emp/emp_update.jsp").forward(req, resp);
}
public void doUpdate(HttpServletRequest req,HttpServletResponse resp)throws ServletException,IOException{
List all=new ArrayList();
SmartUpload smart=new SmartUpload();
Emp emp=new Emp(); int empno=0;
String ename=null;
String job=null;
Date hiredate=null;
float sal=0.0f;
float comm=0.0f;
String photo=smart.getRequest().getParameter("pic"); try{
smart.initialize(getServletConfig(),req,resp); //初始化上传
smart.upload(); //准备上传 empno=Integer.parseInt(smart.getRequest().getParameter("empno"));
ename=smart.getRequest().getParameter("ename");
job=smart.getRequest().getParameter("job");
hiredate=new SimpleDateFormat("yyyy-mm-dd").parse(smart.getRequest().getParameter("hiredate"));
sal=Float.parseFloat(smart.getRequest().getParameter("sal"));
comm=Float.parseFloat(smart.getRequest().getParameter("comm"));
if(smart.getFiles().getFile(0).getSize()>0){
IPTimeStamp its=new IPTimeStamp(req.getRemoteAddr());
photo=its.getIPTimeStampRand()+"."+smart.getFiles().getFile(0).getFileExt(); //拼凑上传文件名
}
emp.setEmpno(empno);
emp.setEname(ename);
emp.setJob(job);
emp.setHiredate(hiredate);
emp.setSal(sal);
emp.setComm(comm);
emp.setPhoto(photo);
if(DAOFactory.getIEmpDAOInstance().doUpdate(emp)){
if(smart.getFiles().getFile(0).getSize()>0){
//保存上传文件
smart.getFiles().getFile(0).saveAs(getServletContext().getRealPath("/")+"jsp/upload/"+photo);
}
all.add("员工信息改动成功。");
}else{
all.add("员工信息改动失败。");
}
}catch(Exception e){
e.printStackTrace();
}
req.setAttribute("infoUpdate", all);
req.getRequestDispatcher("jsp/admin/emp/emp_update_do.jsp").forward(req, resp);
}
public void doDelete(HttpServletRequest req,HttpServletResponse resp)throws ServletException,IOException{
int empno=0;
String photo=null;
List all=new ArrayList();
try{
empno=Integer.parseInt(req.getParameter("empno"));
photo=req.getParameter("photo");
System.out.println("photo=="+photo);
if(DAOFactory.getIEmpDAOInstance().doDelete(empno)){
if(!(photo.equals("nophoto.jpg"))){
File f=new File(this.getServletContext().getRealPath("/")+"jsp/upload/"+photo); //找到当前文件
System.out.println("当前文件是否存在=="+f.exists());
if(f.exists()){ //推断当前文件或者文件文件夹是否存在,则
f.delete(); //则进行删除
}
}
all.add("文件删除成功!");
}else{
all.add("文件删除失败! ");
}
}catch(Exception e){
e.printStackTrace();
}
req.setAttribute("infoDelete", all);
req.getRequestDispatcher("jsp/admin/emp/emp_delete_do.jsp").forward(req, resp);
}
public void getAllEname(HttpServletRequest req,HttpServletResponse resp)throws ServletException,IOException{
req.setCharacterEncoding("gb2312");
resp.setContentType("text/html;charset=gb2312");
String ename=null;
PrintWriter out=resp.getWriter();
try{
System.out.println("++++++后台取javascript传递參数++++++++"+req.getParameter("ename"));
//1.String name = URLDecoder.decode("client传输过来的中文字符","UTF-8");
ename=URLDecoder.decode(req.getParameter("ename"),"gb2312");
System.out.println("********servlet********"+ename);
if(DAOFactory.getIEmpDAOInstance().getAllEname(ename)){
out.print("true");
}else{
out.print("false");
}
}catch(Exception e){
e.printStackTrace();
}
}
}

Test

package org.lzch.test;

import java.util.Date;

import org.lzch.vo.Emp;
import org.lzch.factory.DAOFactory; public class Test { /**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Emp emp=new Emp();
emp.setEmpno(79);
emp.setEname("lzch");
emp.setJob("project师");
emp.setHiredate(new Date());
emp.setSal(5555.5f);
emp.setComm(350.9f);
emp.setPhoto("nophoto.jpg");
try{
if(DAOFactory.getIEmpDAOInstance().doCreate(emp)){
System.out.println("插入成功! ");
}else{
System.out.println("插入失败! ");
} }catch(Exception e){
e.printStackTrace();
}
} }

IPTimeStamp

package org.lzch.util;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random; public class IPTimeStamp {
private String ip=null;
public IPTimeStamp(String ip){
this.ip=ip;
}
//上传文件命名:IP+时间戳+3位随机数
public String getIPTimeStampRand(){
StringBuffer buf=new StringBuffer();
//加入当前IP地址
if(this.ip!=null){
String str[]=this.ip.split("\\."); //进行拆分IP地址
for(int i=0;i<str.length;i++){
buf.append(this.addZero(str[i], 3)); //位数不够3位的。进行补0操作
}
}
//加入时间戳
buf.append(this.getTimeStamp());
//加入3为随机数
Random ran=new Random();
for(int i=0;i<3;i++){ //循环3次
buf.append(ran.nextInt(10)); //取得一位0到10之间的随机整数
}
return buf.toString();
}
//补0操作
public String addZero(String str,int len){
StringBuffer buf=new StringBuffer();
buf.append(str);
while(buf.length()<len){
buf.insert(0, "0"); //进行加入0操作
}
return buf.toString();
}
//时间戳
public String getTimeStamp(){
SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMddHHmmssSSS"); //取得当前时间
return sdf.format(new Date());
}
}

Emp

package org.lzch.vo;

import java.util.Date;

public class Emp {
private int empno;
private String ename;
private String job;
private Date hiredate;
private float sal;
private float comm;
private String photo;
public float getComm() {
return comm;
}
public void setComm(float comm) {
this.comm = comm;
}
public int getEmpno() {
return empno;
}
public void setEmpno(int empno) {
this.empno = empno;
}
public String getEname() {
return ename;
}
public void setEname(String ename) {
this.ename = ename;
}
public Date getHiredate() {
return hiredate;
}
public void setHiredate(Date hiredate) {
this.hiredate = hiredate;
}
public String getJob() {
return job;
}
public void setJob(String job) {
this.job = job;
}
public String getPhoto() {
return photo;
}
public void setPhoto(String photo) {
this.photo = photo;
}
public float getSal() {
return sal;
}
public void setSal(float sal) {
this.sal = sal;
} }

emp_delete_do.jsp

<%@page pageEncoding="GBK" contentType="text/html; charset=GBK" %>
<%@page import="java.util.List,java.util.Iterator" %>
<html>
<head>
<title>删除</title>
</head>
<script type="text/javascript">
opener.window.location.reload() ; //又一次读取,刷新
function closeWin(){
window.close();
}
</script>
<body>
<center>
<h2>职员管理程序</h2>
<hr>
<%
List all=(List)request.getAttribute("infoDelete");
Iterator iter=all.iterator();
while(iter.hasNext()){
%>
<h2><%=iter.next() %></h2>
<%
}
%>
<h2><a href="#" onclick="closeWin()">关闭窗体</a></h2>
</center>
</body>
</html>

emp_insert_do.jsp

<%@page pageEncoding="GBK" contentType="text/html; charset=GBK" %>
<%@page import="java.util.List,java.util.Iterator" %>
<html>
<head>
<title>注冊页面</title>
</head>
<script type="text/javascript">
opener.window.location.reload() ; //又一次读取,刷新
function closeWin(){
window.close();
}
</script>
<body>
<center>
<h2>职员管理程序</h2>
<hr>
<%
List all=(List)request.getAttribute("infoInsert");
Iterator iter=all.iterator();
while(iter.hasNext()){
%>
<h2><%=iter.next() %></h2>
<%
}
%>
<h2><a href="#" onclick="closeWin()">关闭窗体</a></h2>
<center>
</body>
</html>

emp_insert.jsp

<%@page pageEncoding="GBK" contentType="text/html; charset=GBK" %>
<html>
<head>
<title>职员注冊页面</title>
</head>
<script type="text/javascript" src="../../../js/data.js"></script>
<script type="text/javascript">
var xmlHttp;
var flag;
function createXMLHttp(){
if(window.XMLHttpRequest){
xmlHttp=new XMLHttpRequest();
}else{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
}
function checkEname(ename){
createXMLHttp();
encodeURI(encodeURI(ename));//解决中文乱码问题两次编码 xmlHttp.open("POST","<%=request.getContextPath() %>/EmpServlet?p=getAllEname&ename="+ename); //设置一个请求。
alert("ename="+ename);
xmlHttp.onreadystatechange=checkEnameCallback; //设置请求完毕之后处理的回调函数
xmlHttp.send(null); //发送请求。不传递不论什么參数
document.getElementById("msg").innerHTML="正在验证....."; }
function checkEnameCallback(){
if(xmlHttp.readyState==4){
alert("status==="+xmlHttp.status);
if(xmlHttp.status==200){
alert("responseText=="+xmlHttp.responseText);
// var text=xmlHttp.responseText; //接受返回的内容
var text=xmlHttp.responseText;
if(text=="true"){
flag=false;
document.getElementById("msg").innerHTML="反复的username。请更换username!";
}else{
flag=true;
document.getElementById("msg").innerHTML="此username能够注冊!";
}
}
}
}
function checkForm(){
return flag;
}
//关闭窗体
function closeWin(){
window.close();
}
</script>
<body>
<%
request.setCharacterEncoding("gb2312");
%>
<script type="text/javascript">
var xmlHttp;
var flag;
function createXMLHttp(){
if(window.XMLHttpRequest){
xmlHttp=new XMLHttpRequest();
}else{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
}
function checkEname(ename){
createXMLHttp();
alert("ename="+ename);
xmlHttp.open("POST","<%=request.getContextPath() %>/EmpServlet? p=getAllEname&ename="+ename); //设置一个请求,
xmlHttp.onreadystatechange=checkEnameCallback; //设置请求完毕之后处理的回调函数
xmlHttp.send(null); //发送请求。不传递不论什么參数
document.getElementById("msg").innerHTML="正在验证....."; }
function checkEnameCallback(){
if(xmlHttp.readyState==4){
alert("status==="+xmlHttp.status);
if(xmlHttp.status==200){
alert("responseText=="+xmlHttp.responseText);
var text=xmlHttp.responseText; //接受返回的内容
if(text=="true"){
flag=false;
document.getElementById("msg").innerHTML="反复的username,请更换username!";
}else{
flag=true;
document.getElementById("msg").innerHTML="此username能够注冊。";
}
}
}
}
function checkForm(){
return flag;
}
//关闭窗体
function closeWin(){
window.close();
}
</script>
<center>
<form action="<%=request.getContextPath() %>/EmpServlet?p=emp_insert" method="post" enctype="multipart/form-data" onsubmit="return checkForm()">
<table border="1" width="80%">
<tr>
<td colspan="2" align="center"><h2>加入职员</h2></td>
</tr>
<tr>
<td>职员编号</td>
<td><input type="text" name="empno"></td>
</tr>
<tr>
<td>职员姓名</td>
<td><input type="text" name="ename" onblur="checkEname(this.value)"><span id="msg"></span></td>
</tr>
<tr>
<td>职员职位</td>
<td><input type="text" name="job"></td>
</tr>
<tr>
<td>入职日期</td>
<td>
<input type="text" name="hiredate" size="15" maxlength="15"
onclick='popUpCalendar(this,this,"yyyy-mm-dd")' readonly="true">
</td>
</tr>
<tr>
<td>职员工资</td>
<td><input type="text" name="sal"></td>
</tr>
<tr>
<td>职员奖金</td>
<td><input type="text" name="comm"></td>
</tr>
<tr>
<td>职员照片</td>
<td>
<input type="file" name="pic"><br>
<font color="red" size="2">假设不想上传,能够不选! </font>
</td> </tr>
<tr>
<td colspan="2" align="center">
<input type="submit" value="提交">
<input type="reset" value="重置">
</td>
</tr>
</table>
</form>
<a href="#" onclick="closeWin()">关闭窗体</a>
</center>
</body>
</html>

emp_list.jsp

<%@page pageEncoding="GBK" contentType="text/html; charset=GBK" %>
<%@page import="java.util.List,java.util.Iterator" %>
<%@page import="org.lzch.vo.Emp" %>
<%@page import="org.lzch.dao.proxy.EmpDAOProxy,org.lzch.dao.IEmpDAO" %>
<html>
<head>
<title>职员查询程序</title>
</head>
<style>
body,td{
font-size:13px;
}
</style>
<script type="text/javascript" src="../../../js/data.js"></script>
<script type="text/javascript">
function changeColor(obj,color){
obj.bgColor=color;
}
function goInsert(thisurl){
window.open(thisurl,"雇员管理","width=600,height=420,scrollbars=yes,resizable=yes");
}
function goUpdate(thisurl){
window.open(thisurl,"雇员管理","width=600,height=420,scrollbars=yes,resizable=yes");
}
function goDelete(thisurl){
window.open(thisurl,"雇员管理","width=600,height=420,scrollbars=yes,resizable=yes");
}
</script>
<body>
<center>
<%
int lineSize=5; //每页显示5条记录
int currentPage=1; //当前第一页
int allRecorders=0; //显示数据表里总记录数,须要计算
List all=null;
try{
// 改动页数
currentPage = Integer.parseInt(request.getParameter("cp")) ;
}catch(Exception e){}
try{
// 改动行数
lineSize = Integer.parseInt(request.getParameter("ls")) ;
}catch(Exception e){}
%>
<h2>职员管理程序</h2>
<hr>
<%
String keyword=request.getParameter("keyword");
if(keyword==null){
keyword="";
}
%>
<h2><a href="#" onClick="goInsert('emp_insert.jsp')">加入职员</a></h2>
<%
try{
IEmpDAO dao=new EmpDAOProxy();
all=dao.findAll(currentPage,lineSize,keyword); //查询所有
allRecorders=dao.getAllCount(keyword); //所有记录数
%>
<jsp:include page="../split_page.jsp">
<jsp:param name="currentPage" value="<%=currentPage%>"/>
<jsp:param name="lineSize" value="<%=lineSize%>"/>
<jsp:param name="allRecorders" value="<%=allRecorders%>"/>
<jsp:param name="keyword" value="<%=keyword%>"/>
<jsp:param name="searchFlag" value="TRUE"/>
<jsp:param name="lineSizeFlag" value="TRUE"/>
</jsp:include>
<table border="1" width="80%" cellpadding="5" cellspacing="0" bgcolor="F2F2F2">
<tr>
<td>职员编号</td>
<td>职员姓名</td>
<td>职员职位</td>
<td>入职日期</td>
<td>职员工资</td>
<td>职员奖金</td>
<td>职员照片</td>
<td>操作</td>
</tr>
<%
Iterator iter=all.iterator();
while(iter.hasNext()){
Emp emp=(Emp)iter.next();
%>
<tr onMouseOver="changeColor(this,'white')" onMouseOut="changeColor(this,'F2F2F2')">
<td><%=emp.getEmpno() %></td>
<td><%=emp.getEname() %></td>
<td><%=emp.getJob() %></td>
<td><%=emp.getHiredate() %></td>
<td><%=emp.getSal() %></td>
<td><%=emp.getComm() %></td>
<td><img src="../../upload/<%=emp.getPhoto() %>" width="50" height="40"></td>
<td>
<a href="#" onclick="goUpdate('<%=request.getContextPath() %>/EmpServlet?p=doUpdatePage&empno=<%=emp.getEmpno() %>')">改动</a>
<a href="#" onclick="goDelete('<%=request.getContextPath() %>/EmpServlet? p=doDelete&empno=<%=emp.getEmpno() %>&photo=<%=emp.getPhoto() %>')">删除</a>
</td>
</tr>
<%
}
%>
<%
}catch(Exception e){
e.printStackTrace();
}
%>
</table>
</center>
</body>
</html>

emp_update_do.jsp

<%@page pageEncoding="GBK" contentType="text/html; charset=GBK" %>
<%@page import="java.util.List,java.util.Iterator" %>
<html>
<head>
<title>改动</title>
</head>
<script type="text/javascript">
opener.window.location.reload() ; //又一次读取,刷新
function closeWin(){
window.close();
}
</script>
<body>
<center>
<h2>职员管理程序</h2>
<hr>
<%
List all=(List)request.getAttribute("infoUpdate");
Iterator iter=all.iterator();
while(iter.hasNext()){
%>
<h2><%=iter.next() %></h2>
<%
}
%>
<h2><a href="#" onclick="closeWin()">关闭窗体</a></h2>
</center>
</body>
</html>

emp_update.jsp

<%@page pageEncoding="GBK" contentType="text/html; charset=GBK" %>
<%@page import="org.lzch.vo.Emp" %>
<html>
<head>
<title>更新页面</title>
</head>
<script type="text/javascript" src="../../../js/data.js"></script>
<script type="text/javascript">
function closeWin(){
window.close();
}
</script>
<body>
<center>
<%
Emp emp=(Emp)request.getAttribute("infoUpdatePage");
if(emp!=null){
%> <form action="<%=request.getContextPath() %>/EmpServlet?p=doUpdate" method="post" enctype="multipart/form-data">
<table border="1" width="80%">
<tr>
<td colspan="2" align="center"><h2>改动职员</h2></td>
</tr>
<tr>
<td>职员编号</td>
<td><%=emp.getEmpno() %></td>
</tr>
<tr>
<td>职员姓名</td>
<td><input type="text" name="ename" value="<%=emp.getEname() %>"></td>
<td rowspan="6"><img src="../../upload/<%=emp.getPhoto() %>" width="100" height="155"></td>
</tr>
<tr>
<td>职员职位</td>
<td><input type="text" name="job" value="<%=emp.getJob() %>"></td>
</tr>
<tr>
<td>入职日期</td>
<td>
<input type="text" name="hiredate" size="15" maxlength="15"
onclick='popUpCalendar(this,this,"yyyy-mm-dd")' readonly="true" value="<%=emp.getHiredate() %>">
</td>
</tr>
<tr>
<td>职员工资</td>
<td><input type="text" name="sal" value="<%=emp.getSal() %>"></td>
</tr>
<tr>
<td>职员奖金</td>
<td><input type="text" name="comm" value="<%=emp.getComm() %>"></td>
</tr>
<tr>
<td>职员照片</td>
<td>
<input type="file" name="pic"><br>
<font color="red" size="2">假设不想上传。能够不选! </font>
</td> </tr>
<tr>
<td colspan="2" align="center">
<input type="hidden" name="empno" value="<%=emp.getEmpno() %>">
<input type="hidden" name="pic" value="<%=emp.getPhoto() %>">
<input type="submit" value="提交">
<input type="reset" value="重置">
</td>
</tr>
</table>
</form>
<%
}
%>
<a href="#" onclick="closeWin()">关闭窗体</a>
</center>
</body>
</html>

split_page.jsp

<%@ page contentType="text/html;charset=GBK"%>
<%@ page import="java.util.*"%>
<%--
仅仅须要在须要分页的地方导入此页面就可以
<jsp:include page="split_page.jsp">
<jsp:param name="currentPage" value="<%=currentPage%>"/>
<jsp:param name="lineSize" value="<%=lineSize%>"/>
<jsp:param name="allRecorders" value="<%=allRecorders%>"/>
<jsp:param name="keyWord" value="<%=keyWord%>"/>
<jsp:param name="searchFlag" value="TRUE"/>
<jsp:param name="lineSizeFlag" value="TRUE"/>
</jsp:include>
--%>
<html>
<head>
<title>JSP + Oracle应用</title>
<style type="text/css">
body,td{
font-size:13px ;
}
</style>
<script language="javascript">
function changeColor(obj,color){
obj.bgColor = color ;
}
function goInsert(thisurl){
window.open(thisurl,"雇员管理","width=600,height=420,scrollbars=yes,resizable=yes");
}
function goUpdate(thisurl){
window.open(thisurl,"雇员管理","width=600,height=420,scrollbars=yes,resizable=yes");
}
function goDelete(thisurl){
window.open(thisurl,"雇员管理","width=360,height=200,scrollbars=yes,resizable=yes");
}
</script>
</head>
<body>
<%
// 解决提交时的中文乱码问题
request.setCharacterEncoding("GBK") ;
%>
<%
int currentPage = 1 ; // 当前所在是第一页
int lineSize = 5 ; // 每页显示5条记录
int allRecorders = 0 ; // 总记录数。须要计算
int pageSize = 0 ; // 总页数,须要计算
int line[] = {5,10,15,20,25,30,45,50,100} ;
// 分页要跳转的路径
String SPURL = "" ;
// 接收查询内容
String keyWord = request.getParameter("keyWord") ;
String searchFlag = "FALSE" ;
String lineSizeFlag = "FALSE" ;
%>
<%
try{
searchFlag = request.getParameter("searchFlag").toUpperCase() ;
}catch(Exception e){}
try{
lineSizeFlag = request.getParameter("lineSizeFlag").toUpperCase() ;
}catch(Exception e){}
if(keyWord==null){
keyWord = "" ;
}
%>
<%
try{
// 改动页数
currentPage = Integer.parseInt(request.getParameter("currentPage")) ;
}catch(Exception e){}
try{
// 改动行数
lineSize = Integer.parseInt(request.getParameter("lineSize")) ;
}catch(Exception e){}
try{
// 记录数
allRecorders = Integer.parseInt(request.getParameter("allRecorders")) ;
}catch(Exception e){}
%>
<%
pageSize = (allRecorders + lineSize - 1) / lineSize ;
if(pageSize==1){
currentPage = 1 ;
}
if(pageSize==0){
pageSize = 1 ;
}
%>
<script language="javaScript">
function go(c){
document.getElementById("cp").value = c ;
<%
if("TRUE".equals(lineSizeFlag)){
%>
document.getElementById("ls").value = document.getElementById("lssel").value ;
<%
}
%>
document.spform.submit() ; // 提交表单
}
function goLs(ls){
document.getElementById("ls").value = ls ;
document.getElementById("cp").value = document.getElementById("cpsel").value ;
document.spform.submit() ; // 提交表单
}
function goS(){
document.getElementById("cp").value = document.getElementById("cpsel").value ;
<%
if("TRUE".equals(lineSizeFlag)){
%>
document.getElementById("ls").value = document.getElementById("lssel").value ;
<%
}
%>
}
</script>
<form action="<%=SPURL%>" name="spform" method="post" onsubmit="goS()">
<%
if("TRUE".equals(searchFlag)){
%>
输入查询关键字:<input type="text" name="keyword" value="<%=keyWord%>">
<input type="submit" value="查询"><br>
<%
}
%>
<input type="button" value="首页" onClick="go(1)" <%=currentPage==1? "disabled":""%>>
<input type="button" value="上一页" onClick="go(<%=currentPage-1%>)" <%=currentPage==1?"disabled":""%>>
<input type="button" value="下一页" onClick="go(<%=currentPage+1%>)" <%=currentPage==pageSize?"disabled":""%>>
<input type="button" value="尾页" onClick="go(<%=pageSize%>)" <%=currentPage==pageSize? "disabled":""%>>
跳转到第
<SELECT name="cpsel" onchange="go(this.value)">
<%
for(int i=1;i<=pageSize;i++){
%>
<OPTION value="<%=i%>" <%=currentPage==i?"SELECTED":""%>><%=i%></OPTION>
<%
}
%>
</SELECT>

<%
if("TRUE".equals(lineSizeFlag)){
%>
每页显示
<SELECT name="lssel" onChange="goLs(this.value)">
<%
for(int i=0;i<line.length;i++){
%>
<OPTION value="<%=line[i]%>" <%=lineSize==line[i]? "SELECTED":""%>><%=line[i]%></OPTION>
<%
}
%>
</SELECT>

<%
}
%>
<input type="hidden" name="cp" value="">
<%
if("TRUE".equals(lineSizeFlag)){
%>
<input type="hidden" name="ls" value="">
<%
}
%>
</form>

web.xml

<?

xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>
TestJava2</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list> <filter>
<filter-name>empEncoding</filter-name>
<filter-class>org.lzch.filter.EmpEncodingFilter</filter-class>
<init-param>
<param-name>charset</param-name>
<param-value>gb2312</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>empEncoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping> <servlet>
<servlet-name>empServlet</servlet-name>
<servlet-class>org.lzch.servlet.EmpServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>empServlet</servlet-name>
<url-pattern>/EmpServlet</url-pattern>
</servlet-mapping>
</web-app>

emp.sql

CREATE TABLE emp1(
empno int not null PRIMARY KEY,
ename varchar(20),
job varchar(10),
hiredate datetime,
sal float,
comm float,
photo varchar(20)
)

资源链接:http://download.csdn.net/detail/qilixiang012/7387063

javaEE mvc样例具体解释的更多相关文章

  1. CI框架入门中的简单MVC样例

    最简单的CI模型: 注意:模型须要用到数据库 配置文件在appcation/config.php 这里我们要用到数据库,须要将databases.php中的 相关參数填写一下,详细不再赘述. 直接进入 ...

  2. Java中foreach用法,增强型的for循环的样例和解释

    JDK1.5加入的增强for和循环. 这段时间又回顾了一下JAVA基础 foreach语句使用总结 增强for(part1:part2){part3}; part2中是一个数组对象,或者是带有泛性的集 ...

  3. MVC整个样例的源代码

    以下就是整MVC样例的源代码: #windows应用程序 #开发者:蔡军生(QQ:9073204) 深圳 2014-9-24 #使用类来描写叙述 from ctypes import * from c ...

  4. Spring MVC使用样例

    Spring MVC使用样例 步骤1:添加Spring的相关依赖 1 <dependency> 2 3 <groupId>com.alibaba.external</gr ...

  5. RPM安装包-Spec文件參数具体解释与演示样例分析

    spec文件是整个RPM包建立过程的中心,它的作用就如同编译程序时的Makefile文件. 1.Spec文件參数 spec文件包括建立一个RPM包必需的信息,包括哪些文件是包的一部分以及它们安装在哪个 ...

  6. obj-c编程15[Cocoa实例03]:MVC以及归档化演示样例

    前面的博文里介绍了归档和解档,这里我们把它实际应用到一个简单的代码中去,将它作为一个多文档应用程序的打开和保存的背后支持.另外这里介绍一下MVC思想,这个在不论什么语言里都会有,它是一种设计思想,主要 ...

  7. 10分钟理解Android数据库的创建与使用(附具体解释和演示样例代码)

    1.Android数据库简单介绍. Android系统的framework层集成了Sqlite3数据库.我们知道Sqlite3是一种轻量级的高效存储的数据库. Sqlite数据库具有以下长处: (1) ...

  8. Android中MVP模式与MVC模式比較(含演示样例)

    原文链接 http://sparkyuan.me/ 转载请注明出处 MVP 介绍 MVP模式(Model-View-Presenter)是MVC模式的一个衍生. 主要目的是为了解耦,使项目易于维护. ...

  9. Java 序列化Serializable具体解释(附具体样例)

    Java 序列化Serializable具体解释(附具体样例) 1.什么是序列化和反序列化 Serialization(序列化)是一种将对象以一连串的字节描写叙述的过程:反序列化deserializa ...

随机推荐

  1. 自己写的一个操作Mysql的简单的实例

    #include <WinSock.h> #include <stdio.h> #include <iostream> #include <windows.h ...

  2. Common Probability Distributions

    Common Probability Distributions Probability Distribution A probability distribution describes the p ...

  3. 32个最热CPLD-FPGA论坛

    1. OPENCORES.ORG这里提供非常多,非常好的PLD了内核,8051内核就可以在里面找到.进入后,选择project或者由http//www.opencores.org/browse.cgi ...

  4. centos7重启网卡

    systemctl restart network

  5. 解决python2.7 UnicodeDecodeError和UnicodeEncodeError问题

    最近在项目中,读取上传的csv文件,并写入时,会报编码问题, with open(origin_file_path, mode='wb')as f: for chunk in file_obj: f. ...

  6. 深入理解Eureka - Eureka配置列表

    Eureka包含四个部分的配置 instance:当前Eureka Instance实例信息配置 client:Eureka Client客户端特性配置 server:Eureka Server注册中 ...

  7. 百度地图 JSAPI使用 定位当前地址 与路径规划

    http://lbsyun.baidu.com/index.php?title=jspopular  api  http://developer.baidu.com/map/jsdemo.htm#a1 ...

  8. timeout的作用

    废话: 刚才刚才看视屏有一点没看懂,timeout的作用. 得出的结果: setTimeout(‘test()’,1000); 第一个参数要调用的函数名,第二个参数是延时的时间.时间到达以后调用tes ...

  9. 【Unity笔记】UGUI的自动布局功能

    一些RectTransform的物体(UGUI元素)已经实现了ILayoutElement接口,如Image. 如果一个RectTransform的物体(UGUI元素)的其中一个组件实现了ILayou ...

  10. 【C#/WPF】Button按钮动态设置Background背景颜色

    学习笔记: 在XAML中给Button设置颜色大家都懂的,本篇只是记录用C#代码动态生成的按钮设置Background背景颜色. new一个Button,设置Background时可看到该属性类型是S ...