源码获取:俺的博客首页 "资源" 里下载!
项目介绍
本项目分为前后台,有普通用户与管理员两种角色,普通用户登录前台,管理员登录后台;
用户角色包含以下功能:
查看首页,客户注册,查看服务项目,查看服务项目详情,查看服务人员,查看家政新闻,在线留言等功能。
管理员角色包含以下功能:
管理员登录,管理员管理,客户信息管理,修改密码,员工信息管理,服务类别管理,服务项目管理,预约信息查询,留言管理,家政新闻管理,系统管理,友情链接添加,友情链接查询,系统公告设置等功能。
环境需要
1.运行环境:最好是java jdk 1.8,我们在这个平台上运行的。其他版本理论上也可以。
2.IDE环境:IDEA,Eclipse,Myeclipse都可以。推荐IDEA;
3.tomcat环境:Tomcat 7.x,8.x,9.x版本均可
4.硬件环境:windows 7/8/10 1G内存以上;或者 Mac OS;
5.数据库:MySql 5.7版本;
6.是否Maven项目:否;
技术栈
JSP+CSS+JavaScript+jquery+Servlet+mysql
使用说明
1. 使用Navicat或者其它工具,在mysql中创建对应名称的数据库,并导入项目的sql文件;
2. 使用IDEA/Eclipse/MyEclipse导入项目,Eclipse/MyEclipse导入时,若为maven项目请选择maven;
若为maven项目,导入成功后请执行maven clean;maven install命令,然后运行;
3. 将项目中dao/CommDAO.java配置文件中的数据库配置改为自己的配置;
4. 运行项目,输入localhost:8080/jsp_jzfw_site 登录
登录管理注册管理控制层:
public class MainCtrl extends HttpServlet {
public MainCtrl() {
super();
}
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 {
this.doPost(request, response);
}
public void go(String url,HttpServletRequest request, HttpServletResponse response)
{
try {
request.getRequestDispatcher(url).forward(request, response);
} catch (ServletException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public void gor(String url,HttpServletRequest request, HttpServletResponse response)
{
try {
response.sendRedirect(url);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String ac = request.getParameter("ac");
if(ac==null)ac="";
CommDAO dao = new CommDAO();
String date = Info.getDateStr();
String today = date.substring(0,10);
String tomonth = date.substring(0,7);
if(ac.equals("login"))
{
String username = request.getParameter("username");
String password = request.getParameter("pwd1");
String utype = request.getParameter("cx");
String pagerandom = request.getParameter("pagerandom")==null?"":request.getParameter("pagerandom");
String random = (String)request.getSession().getAttribute("random");
if(!pagerandom.equals(random)&&request.getParameter("a")!=null)
{
request.setAttribute("random", "");
go("/index.jsp", request, response);
}
else{
String sql1="";
if (utype.equals("注册用户"))
{
sql1 = "select * from yonghuzhuce where yonghuming='"+username+"' and mima='"+password+"' and issh='是'";
}
else
{
sql1 = "select * from yuangongxinxi where gonghao='"+username+"' and mima='"+password+"'";
}
List<HashMap> userlist1 = dao.select(sql1);
if(userlist1.size()==1)
{
if (utype.equals("注册用户"))
{
request.getSession(). setAttribute("username", userlist1.get(0).get("yonghuming"));
}
else
{
request.getSession(). setAttribute("username", userlist1.get(0).get("gonghao"));
}
request.getSession(). setAttribute("cx", utype);
gor("index.jsp", request, response);
}else{
request.setAttribute("error", "");
go("/index.jsp", request, response);
}
}
}
if(ac.equals("adminlogin"))
{
String username = request.getParameter("username");
String password = request.getParameter("pwd");
String utype = request.getParameter("cx");
String pagerandom = request.getParameter("pagerandom")==null?"":request.getParameter("pagerandom");
String random = (String)request.getSession().getAttribute("random");
if(!pagerandom.equals(random)&&request.getParameter("a")!=null)
{
request.setAttribute("random", "");
go("/login.jsp", request, response);
}
else{
String sql1 = "select * from allusers where username='"+username+"' and pwd='"+password+"' ";
List<HashMap> userlist1 = dao.select(sql1);
if(userlist1.size()==1)
{
request.getSession(). setAttribute("username", userlist1.get(0).get("username"));
request.getSession(). setAttribute("cx", userlist1.get(0).get("cx"));
gor("main.jsp", request, response);
}else{
request.setAttribute("error", "");
go("/login.jsp", request, response);
}
}
}
//修改密码
if(ac.equals("uppass"))
{
String olduserpass = request.getParameter("ymm");
String userpass = request.getParameter("xmm1");
String copyuserpass = request.getParameter("xmm2");
HashMap m = dao.getmaps("yonghuming",(String)request.getSession().getAttribute("username"), "yonghuzhuce");
if(!(((String)m.get("mima")).equals(olduserpass)))
{
request.setAttribute("error", "");
go("mod2.jsp", request, response);
}else{
//String id = (String)user.get("id");
String sql = "update yonghuzhuce set mima='"+userpass+"' where yonghuming='"+(String)request.getSession().getAttribute("username")+"'";
dao.commOper(sql);
request.setAttribute("suc", "");
go("mod2.jsp", request, response);
}
}
//修改密码
if(ac.equals("adminuppass"))
{
String olduserpass = request.getParameter("ymm");
String userpass = request.getParameter("xmm1");
String copyuserpass = request.getParameter("xmm2");
//println(Info.getUser(request).get("id").toString());
HashMap m = dao.getmaps("username",(String)request.getSession().getAttribute("username"), "allusers");
if(!(((String)m.get("pwd")).equals(olduserpass)))
{
request.setAttribute("error", "");
go("mod.jsp", request, response);
}else{
//String id = (String)user.get("id");
String sql = "update allusers set pwd='"+userpass+"' where username='"+(String)request.getSession().getAttribute("username")+"'";
dao.commOper(sql);
request.setAttribute("suc", "");
go("mod.jsp", request, response);
}
}
if(ac.equals("uploaddoc"))
{
try {
String filename="";
request.setCharacterEncoding("UTF-8");
RequestContext requestContext = new ServletRequestContext(request);
if(FileUpload.isMultipartContent(requestContext)){
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setRepository(new File(request.getRealPath("/upfile/")+"/"));
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setSizeMax(100*1024*1024);
List items = new ArrayList();
items = upload.parseRequest(request);
FileItem fileItem = (FileItem) items.get(0);
if(fileItem.getName()!=null && fileItem.getSize()!=0)
{
if(fileItem.getName()!=null && fileItem.getSize()!=0){
File fullFile = new File(fileItem.getName());
filename = Info.generalFileName(fullFile.getName());
File newFile = new File(request.getRealPath("/upfile/")+"/" + filename);
try {
fileItem.write(newFile);
} catch (Exception e) {
e.printStackTrace();
}
}else{
}
}
}
go("/js/uploaddoc.jsp?docname="+filename, request, response);
} catch (Exception e1) {
e1.printStackTrace();
}
}
if(ac.equals("uploaddoc2"))
{
try {
String filename="";
request.setCharacterEncoding("UTF-8");
RequestContext requestContext = new ServletRequestContext(request);
if(FileUpload.isMultipartContent(requestContext)){
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setRepository(new File(request.getRealPath("/upfile/")+"/"));
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setSizeMax(100*1024*1024);
List items = new ArrayList();
items = upload.parseRequest(request);
FileItem fileItem = (FileItem) items.get(0);
if(fileItem.getName()!=null && fileItem.getSize()!=0)
{
if(fileItem.getName()!=null && fileItem.getSize()!=0){
File fullFile = new File(fileItem.getName());
filename = Info.generalFileName(fullFile.getName());
File newFile = new File(request.getRealPath("/upfile/")+"/" + filename);
try {
fileItem.write(newFile);
} catch (Exception e) {
e.printStackTrace();
}
}else{
}
}
}
go("/js/uploaddoc2.jsp?docname="+filename, request, response);
} catch (Exception e1) {
e1.printStackTrace();
}
}
if(ac.equals("uploaddoc3"))
{
try {
String filename="";
request.setCharacterEncoding("UTF-8");
RequestContext requestContext = new ServletRequestContext(request);
if(FileUpload.isMultipartContent(requestContext)){
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setRepository(new File(request.getRealPath("/upfile/")+"/"));
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setSizeMax(100*1024*1024);
List items = new ArrayList();
items = upload.parseRequest(request);
FileItem fileItem = (FileItem) items.get(0);
if(fileItem.getName()!=null && fileItem.getSize()!=0)
{
if(fileItem.getName()!=null && fileItem.getSize()!=0){
File fullFile = new File(fileItem.getName());
filename = Info.generalFileName(fullFile.getName());
File newFile = new File(request.getRealPath("/upfile/")+"/" + filename);
try {
fileItem.write(newFile);
} catch (Exception e) {
e.printStackTrace();
}
}else{
}
}
}
go("/js/uploaddoc3.jsp?docname="+filename, request, response);
} catch (Exception e1) {
e1.printStackTrace();
}
}
//导excel
if(ac.equals("importexcel"))
{
String page = request.getParameter("page");
String whzdstr = request.getParameter("whzdstr");
String tablename = request.getParameter("tablename");
try {
String filename="";
request.setCharacterEncoding("UTF-8");
RequestContext requestContext = new ServletRequestContext(request);
if(FileUpload.isMultipartContent(requestContext)){
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setRepository(new File(request.getRealPath("/upfile/")+"/"));
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setSizeMax(100*1024*1024);
List items = new ArrayList();
items = upload.parseRequest(request);
FileItem fileItem = (FileItem) items.get(0);
if(fileItem.getName()!=null && fileItem.getSize()!=0)
{
if(fileItem.getName()!=null && fileItem.getSize()!=0){
File fullFile = new File(fileItem.getName());
filename = Info.generalFileName(fullFile.getName());
File newFile = new File(request.getRealPath("/upfile/")+"/" + filename);
try {
fileItem.write(newFile);
} catch (Exception e) {
e.printStackTrace();
}
}else{
}
}
if(filename.indexOf(".xls")>-1)
{
Workbook workbook;
try {
workbook = Workbook.getWorkbook(new File(request.getRealPath("/upfile/")+"/"+filename));
//通过Workbook的getSheet方法选择第一个工作簿(从0开始)
Sheet sheet = workbook.getSheet(0);
//通过Sheet方法的getCell方法选择位置为C2的单元格(两个参数都从0开始)
//int empty = 0;
for(int i=1;i<1000;i++)
{
Cell cell = null;
try{
String isql = "insert into "+tablename+"(";
for(String str:whzdstr.split("-"))
{
isql+=str+",";
}
isql = isql.substring(0,isql.length()-1);
isql+=")values(";
int j=0;
int empty = 1;
for(String str:whzdstr.split("-"))
{
cell = sheet.getCell(j,i);
isql+="'"+cell.getContents()+"',";
String content = cell.getContents()==null?"":cell.getContents();
if(!"".equals(content.trim()))
{
empty = 0;
}
j++;
}
if(empty==1)continue;
isql = isql.substring(0,isql.length()-1);
isql+=")";
dao.commOper(isql);
}catch (Exception e) {
continue;
}
}
workbook.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
go("/admin/"+page+"?docname="+filename, request, response);
} catch (Exception e1) {
e1.printStackTrace();
}
}
if(ac.equals("uploadimg"))
{
try {
String filename="";
request.setCharacterEncoding("UTF-8");
RequestContext requestContext = new ServletRequestContext(request);
if(FileUpload.isMultipartContent(requestContext)){
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setRepository(new File(request.getRealPath("/upfile/")+"/"));
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setSizeMax(100*1024*1024);
List items = new ArrayList();
items = upload.parseRequest(request);
FileItem fileItem = (FileItem) items.get(0);
if(fileItem.getName()!=null && fileItem.getSize()!=0)
{
if(fileItem.getName()!=null && fileItem.getSize()!=0){
File fullFile = new File(fileItem.getName());
filename = Info.generalFileName(fullFile.getName());
File newFile = new File(request.getRealPath("/upfile/")+"/" + filename);
try {
fileItem.write(newFile);
} catch (Exception e) {
e.printStackTrace();
}
}else{
}
}
}
go("/js/uploadimg.jsp?filename="+filename, request, response);
} catch (Exception e1) {
e1.printStackTrace();
}
}
if(ac.equals("uploadimg2"))
{
try {
String filename="";
request.setCharacterEncoding("UTF-8");
RequestContext requestContext = new ServletRequestContext(request);
if(FileUpload.isMultipartContent(requestContext)){
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setRepository(new File(request.getRealPath("/upfile/")+"/"));
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setSizeMax(100*1024*1024);
List items = new ArrayList();
items = upload.parseRequest(request);
FileItem fileItem = (FileItem) items.get(0);
if(fileItem.getName()!=null && fileItem.getSize()!=0)
{
if(fileItem.getName()!=null && fileItem.getSize()!=0){
File fullFile = new File(fileItem.getName());
filename = Info.generalFileName(fullFile.getName());
File newFile = new File(request.getRealPath("/upfile/")+"/" + filename);
try {
fileItem.write(newFile);
} catch (Exception e) {
e.printStackTrace();
}
}else{
}
}
}
go("/js/uploadimg2.jsp?filename="+filename, request, response);
} catch (Exception e1) {
e1.printStackTrace();
}
}
if(ac.equals("uploadimg3"))
{
try {
String filename="";
request.setCharacterEncoding("UTF-8");
RequestContext requestContext = new ServletRequestContext(request);
if(FileUpload.isMultipartContent(requestContext)){
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setRepository(new File(request.getRealPath("/upfile/")+"/"));
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setSizeMax(100*1024*1024);
List items = new ArrayList();
items = upload.parseRequest(request);
FileItem fileItem = (FileItem) items.get(0);
if(fileItem.getName()!=null && fileItem.getSize()!=0)
{
if(fileItem.getName()!=null && fileItem.getSize()!=0){
File fullFile = new File(fileItem.getName());
filename = Info.generalFileName(fullFile.getName());
File newFile = new File(request.getRealPath("/upfile/")+"/" + filename);
try {
fileItem.write(newFile);
} catch (Exception e) {
e.printStackTrace();
}
}else{
}
}
}
go("/js/uploadimg3.jsp?filename="+filename, request, response);
} catch (Exception e1) {
e1.printStackTrace();
}
}
if(ac.equals("uploadimg4"))
{
try {
String filename="";
request.setCharacterEncoding("UTF-8");
RequestContext requestContext = new ServletRequestContext(request);
if(FileUpload.isMultipartContent(requestContext)){
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setRepository(new File(request.getRealPath("/upfile/")+"/"));
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setSizeMax(100*1024*1024);
List items = new ArrayList();
items = upload.parseRequest(request);
FileItem fileItem = (FileItem) items.get(0);
if(fileItem.getName()!=null && fileItem.getSize()!=0)
{
if(fileItem.getName()!=null && fileItem.getSize()!=0){
File fullFile = new File(fileItem.getName());
filename = Info.generalFileName(fullFile.getName());
File newFile = new File(request.getRealPath("/upfile/")+"/" + filename);
try {
fileItem.write(newFile);
} catch (Exception e) {
e.printStackTrace();
}
}else{
}
}
}
go("/js/uploadimg4.jsp?filename="+filename, request, response);
} catch (Exception e1) {
e1.printStackTrace();
}
}
if(ac.equals("uploadimg5"))
{
try {
String filename="";
request.setCharacterEncoding("UTF-8");
RequestContext requestContext = new ServletRequestContext(request);
if(FileUpload.isMultipartContent(requestContext)){
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setRepository(new File(request.getRealPath("/upfile/")+"/"));
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setSizeMax(100*1024*1024);
List items = new ArrayList();
items = upload.parseRequest(request);
FileItem fileItem = (FileItem) items.get(0);
if(fileItem.getName()!=null && fileItem.getSize()!=0)
{
if(fileItem.getName()!=null && fileItem.getSize()!=0){
File fullFile = new File(fileItem.getName());
filename = Info.generalFileName(fullFile.getName());
File newFile = new File(request.getRealPath("/upfile/")+"/" + filename);
try {
fileItem.write(newFile);
} catch (Exception e) {
e.printStackTrace();
}
}else{
}
}
}
go("/js/uploadimg5.jsp?filename="+filename, request, response);
} catch (Exception e1) {
e1.printStackTrace();
}
}
dao.close();
out.flush();
out.close();
}
public void init() throws ServletException {
// Put your code here
}
}
上传管理控制层:
public class Upload extends HttpServlet {
/**
* Constructor of the object.
*/
public Upload() {
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 {
this.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 {
StringBuffer sb = new StringBuffer(50);
response.setContentType("application/x-msdownload;charset=UTF-8");
try {
response.setHeader("Content-Disposition", new String(sb.toString()
.getBytes(), "ISO8859-1"));
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
String filename = request.getParameter("filename");
if (request.getHeader("User-Agent").toLowerCase().indexOf("firefox") > 0){
try {
filename = new String(filename.getBytes("UTF-8"), "ISO8859-1");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else
if (request.getHeader("User-Agent").toUpperCase().indexOf("MSIE") > 0){
try {
filename = URLEncoder.encode(filename, "UTF-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
}
}
response.setContentType("text/plain");
response.setHeader("Location",filename);
response.reset();
response.setHeader("Cache-Control", "max-age=0" );
response.setHeader("Content-Disposition", "attachment; filename=" + filename);
try {
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
OutputStream fos = null;
// File f = new File(request.getRealPath("/upfile/")+"/"+filename);
//System.out.println(f);
bis = new BufferedInputStream((InputStream)new FileInputStream(request.getRealPath("/upfile/")+"/"+filename));
fos = response.getOutputStream();
bos = new BufferedOutputStream(fos);
int bytesRead = 0;
byte[] buffer = new byte[5 * 1024];
while ((bytesRead = bis.read(buffer)) != -1) {
bos.write(buffer, 0, bytesRead);
}
bos.close();
bis.close();
fos.close();
new Info().delPic(request.getRealPath("/upfile/")+"/", filename);
} catch (Exception e) {
}finally{
}
}
/**
* Initialization of the servlet. <br>
*
* @throws ServletException if an error occurs
*/
public void init() throws ServletException {
// Put your code here
}
}
业务处理DAO层:
public class CommDAO
{
public static String dbname = "";
public static String dbtype = "";
public static Connection conn = null;
public CommDAO()
{
conn = this.getConn();
}
//给字段做加减法
public void jiajian(String tablename,String colname,String id,String num)
{
HashMap map = this.getmap(id, tablename);
String value = map.get(colname).toString();
if(value.equals(""))value="0";
int i = Integer.parseInt(value);
int j = Integer.parseInt(num);
commOper("update "+tablename+" set "+colname+" = "+(i+j)+" where id="+id);
}
// 该方法返回一个table 用于流动图片
public String DynamicImage(String categoryid,int cut,int width,int height){
StringBuffer imgStr = new StringBuffer();
StringBuffer thePics1 = new StringBuffer();
StringBuffer theLinks1 = new StringBuffer();
StringBuffer theTexts1 = new StringBuffer();
imgStr.append("<div id=picViwer1 style='background-color: #ffffff' align=center></div><SCRIPT src='js/dynamicImage.js' type=text/javascript></SCRIPT>\n<script language=JavaScript>\n");
thePics1.append("var thePics1=\n'");
theLinks1.append("var theLinks1='");
theTexts1.append("var theTexts1='");
List<HashMap> co = this.select("select * from xinwentongzhi where shouyetupian<>'' and shouyetupian<>'null' and shouyetupian like '%.jpg' order by id desc",1,6);
int i = co.size();
int j = 0;
for(HashMap b:co)
{
j++;
int id = Integer.parseInt(b.get("id").toString()) ;
String title = Info.subStr(b.get("biaoti").toString(), 21) ;
String url = ""+b.get("shouyetupian");
String purl = "gg_detail.jsp?id="+b.get("id");
if(j!=i){
thePics1.append(url.replaceAll("\n", "")+"|");
theLinks1.append(purl+"|");
theTexts1.append(title+"|");
}
if(j==i)
{
thePics1.append(url.replaceAll("\n", ""));
theLinks1.append("gg_detail.jsp?id="+b.get("id"));
theTexts1.append(title);
}
}
thePics1.append("';");
theLinks1.append("';");
theTexts1.append("';");
imgStr.append(thePics1+"\n");
imgStr.append(theLinks1+"\n");
imgStr.append(theTexts1+"\n");
imgStr.append("\n setPic(thePics1,theLinks1,theTexts1,"+width+","+height+",'picViwer1');</script>");
return imgStr.toString();
}
public HashMap getmap(String id,String table)
{
List<HashMap> list = new ArrayList();
try {
Statement st = conn.createStatement();
//System.out.println("select * from "+table+" where id="+id);
ResultSet rs = st.executeQuery("select * from "+table+" where id="+id);
ResultSetMetaData rsmd = rs.getMetaData();
while(rs.next())
{
HashMap map = new HashMap();
int i = rsmd.getColumnCount();
for(int j=1;j<=i;j++)
{
if(!rsmd.getColumnName(j).equals("ID"))
{
String str = rs.getString(j)==null?"": rs.getString(j);
if(str.equals("null"))str = "";
map.put(rsmd.getColumnName(j), str);
}
else
map.put("id", rs.getString(j));
}
list.add(map);
}
rs.close();
st.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return list.get(0);
}
public HashMap getmaps(String nzd,String zdz,String table)
{
List<HashMap> list = new ArrayList();
try {
Statement st = conn.createStatement();
//System.out.println("select * from "+table+" where "+nzd+"='"+zdz+"'");
ResultSet rs = st.executeQuery("select * from "+table+" where "+nzd+"='"+zdz+"'");
ResultSetMetaData rsmd = rs.getMetaData();
while(rs.next())
{
HashMap map = new HashMap();
int i = rsmd.getColumnCount();
for(int j=1;j<=i;j++)
{
if(!rsmd.getColumnName(j).equals("ID"))
{
String str = rs.getString(j)==null?"": rs.getString(j);
if(str.equals("null"))str = "";
map.put(rsmd.getColumnName(j), str);
}
else
map.put("id", rs.getString(j));
}
list.add(map);
}
rs.close();
st.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return list.get(0);
}
public String insert(HttpServletRequest request,HttpServletResponse response, String tablename,HashMap extmap,boolean alert,boolean reflush,String tzurl)
{
extmap.put("addtime", Info.getDateStr());
if(request.getParameter("f")!=null){
HashMap typemap = new HashMap();
ArrayList<String> collist = new ArrayList();
String sql = "insert into "+tablename+"(";
Connection conn = this.getConn();
try {
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery("select * from "+tablename);
ResultSetMetaData rsmd = rs.getMetaData();
int i = rsmd.getColumnCount();
for(int j=1;j<=i;j++)
{
if(rsmd.getColumnName(j).equals("id"))continue;
if(rsmd.getColumnName(j).equals("ID"))continue;
if(rsmd.getColumnName(j).equals("iD"))continue;
if(rsmd.getColumnName(j).equals("Id"))continue;
typemap.put(rsmd.getColumnName(j)+"---", rsmd.getColumnTypeName(j));
collist.add(rsmd.getColumnName(j));
sql+=rsmd.getColumnName(j)+",";
}
sql = sql.substring(0,sql.length()-1);
sql+=") values(";
rs.close();
st.close();
} catch (SQLException e) {
e.printStackTrace();
}
Enumeration enumeration = request.getParameterNames();
String names = ",";
while(enumeration.hasMoreElements())
{
names += enumeration.nextElement().toString()+",";
}
try {
Statement st = conn.createStatement();
for(String str:collist)
{
if(names.indexOf(","+str+",")>-1)
{
String[] values = request.getParameterValues(str);
String value="";
for(String vstr:values)
{
if(vstr==null)vstr="";
if(vstr.equals("null"))vstr="";
if(vstr.trim().equals(""))continue;
if(request.getParameter(vstr)!=null&&!"".equals(request.getParameter(vstr))&&request.getParameter("dk-"+str+"-value")!=null)
{
String dkv = request.getParameter(vstr);
String dknamevalue = request.getParameter("dk-"+str+"-value");
vstr+=" - "+dknamevalue+":"+dkv;
}
value+=vstr+" ~ ";
}
if(value==null)value="";
if(value.equals("null"))value="";
if(value.length()>0)value=value.substring(0,value.length()-3);
if(typemap.get(str+"---").equals("int"))
{
sql+=(value.equals("")?-10:value)+",";
}else{
sql+="'"+(value.equals("null")?"":value)+"',";
}
}else{
if(typemap.get(str+"---").equals("int"))
{
sql+=(extmap.get(str)==null?"":extmap.get(str))+",";
}else{
sql+="'"+(extmap.get(str)==null?"":extmap.get(str))+"',";
}
}
}
sql=sql.substring(0,sql.length()-1)+")";
System.out.println(sql);
this.commOper(sql);
st.close();
} catch (SQLException e) {
e.printStackTrace();
}
String str = "";
if(!reflush)
str += "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"> \n";
str += "<script language=javascript>\n";
if(alert){
str+="alert('操作成功');\n";
}
if(tzurl.equals(""))
{
if(reflush){
str+="parent.location=parent.location;\n";
}else{
str+="window.location=String(window.location).replace(new RegExp('f=f', 'g'), '');";
}
}
else
{
str+="location.href='"+tzurl+"';\n";
}
str+="</script>";
PrintWriter wrt = null;
try {
wrt = response.getWriter();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
wrt.write(str);
}
return "";
}
public void delete(HttpServletRequest request,String tablename)
{
int i = 0;
try {
String did = request.getParameter("did");
if(did==null)did = request.getParameter("scid");
if(did!=null){
if(did.length()>0){
Statement st = conn.createStatement();
System.out.println("delete from "+tablename+" where id="+did);
st.execute("delete from "+tablename+" where id="+did);
st.close();
}
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public String getCols(String table)
{
String str = "";
Connection conn = this.getConn();
try {
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery("select * from "+table);
ResultSetMetaData rsmd = rs.getMetaData();
int i = rsmd.getColumnCount();
for(int j=2;j<=i;j++)
{
str+=rsmd.getColumnName(j)+",";
}
}catch (Exception e) {
e.printStackTrace();
}
str = str.substring(0,str.length()-1);
return str;
}
public String update(HttpServletRequest request,HttpServletResponse response, String tablename,HashMap extmap,boolean alert,boolean reflush,String tzurl)
{
if(request.getParameter("f")!=null){
Enumeration enumeration = request.getParameterNames();
String names = ",";
while(enumeration.hasMoreElements())
{
names += enumeration.nextElement().toString()+",";
}
HashMap typemap = new HashMap();
ArrayList<String> collist = new ArrayList();
String sql = "update "+tablename+" set ";
Connection conn = this.getConn();
try {
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery("select * from "+tablename);
ResultSetMetaData rsmd = rs.getMetaData();
int i = rsmd.getColumnCount();
System.out.println(i);
for(int j=1;j<=i;j++)
{
if(rsmd.getColumnName(j).equals("id"))continue;
if(rsmd.getColumnName(j).equals("ID"))continue;
if(rsmd.getColumnName(j).equals("Id"))continue;
if(rsmd.getColumnName(j).equals("iD"))continue;
typemap.put(rsmd.getColumnName(j)+"---", rsmd.getColumnTypeName(j));
collist.add(rsmd.getColumnName(j));
if(names.indexOf(","+rsmd.getColumnName(j)+",")>-1)
{
String[] values = request.getParameterValues(rsmd.getColumnName(j));
String value="";
for(String vstr:values)
{
if(vstr==null)vstr="";
if(vstr.equals("null"))vstr="";
if(vstr.trim().equals(""))continue;
if(request.getParameter(vstr)!=null&&!"".equals(request.getParameter(vstr))&&request.getParameter("dk-"+rsmd.getColumnName(j)+"-value")!=null)
{
String dkv = request.getParameter(vstr);
String dknamevalue = request.getParameter("dk-"+rsmd.getColumnName(j)+"-value");
vstr+=" - "+dknamevalue+":"+dkv;
System.out.println(vstr);
}
//if(vstr.length()<)
value+=vstr+" ~ ";
}
if(value==null)value="";
if(value.equals("null"))value="";
if(value.length()>0)value=value.substring(0,value.length()-3);
if(rsmd.getColumnTypeName(j).equals("int"))
{
sql+=rsmd.getColumnName(j)+"="+value+",";
}else{
sql+=rsmd.getColumnName(j)+"='"+value+"',";
}
}else{
if(extmap.get(rsmd.getColumnName(j))!=null)
{
if(rsmd.getColumnTypeName(j).equals("int"))
{
sql+=rsmd.getColumnName(j)+"="+extmap.get(rsmd.getColumnName(j))+",";
}else{
sql+=rsmd.getColumnName(j)+"='"+extmap.get(rsmd.getColumnName(j))+"',";
}
}
}
}
sql = sql.substring(0,sql.length()-1);
sql+=" where id="+request.getParameter("id");
System.out.println(sql);
Statement st1 = conn.createStatement();
st1.execute(sql);
st1.close();
rs.close();
st.close();
} catch (SQLException e) {
e.printStackTrace();
}
String str = "";
if(!reflush)
str += "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n" ;
str += "<script language=javascript>\n";
if(alert){
str+="alert('操作成功');\n";
}
if(tzurl.equals(""))
{
if(reflush){
str+="parent.location=parent.location;\n";
}else{
str+="window.location=String(window.location).replace(new RegExp('f=f', 'g'), '');";
}
}
else
{
str+="location.href='"+tzurl+"';\n";
}
str+="</script>\n";
PrintWriter wrt = null;
try {
//request.get
wrt = response.getWriter();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
wrt.write(str);
}
return "";
}
public Connection getConn()
{
try
{
if(conn==null||conn.isClosed()){
Class.forName("com.mysql.cj.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://192.168.182.129:3306/jsp_jzfw_site?useSSL=false&serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf-8","root","123456");
// Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
// conn = DriverManager.getConnection("jdbc:sqlserver://localhost:1433;databaseName=jsp_jzfw_site","sa","sa123456");
}}
catch(Exception e)
{
e.printStackTrace();
}
return conn;
}
public int getInt(String sql)
{
int i = 0;
try {
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery(sql);
if(rs.next())
{
i = rs.getInt(1);
}
st.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return i;
}
public double getDouble(String sql)
{
double i = 0;
try {
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery(sql);
if(rs.next())
{
i = rs.getDouble(1);
}
st.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return i;
}
public void commOper(String sql)
{
System.out.println(sql);
try {
Statement st = conn.createStatement();
st.execute(sql);
st.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void commOperSqls(ArrayList<String> sql)
{
try {
conn.setAutoCommit(false);
for(int i=0;i<sql.size();i++)
{
Statement st = conn.createStatement();
System.out.println(sql.get(i));
st.execute(sql.get(i));
st.close();
}
conn.commit();
} catch (SQLException e) {
try {
conn.rollback();
} catch (SQLException e1) {
e1.printStackTrace();
}
e.printStackTrace();
}finally{
try {
conn.setAutoCommit(true);
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public List<HashMap> select(String sql)
{
System.out.println(sql);
List<HashMap> list = new ArrayList();
try {
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery(sql);
ResultSetMetaData rsmd = rs.getMetaData();
while(rs.next())
{
HashMap map = new HashMap();
int i = rsmd.getColumnCount();
for(int j=1;j<=i;j++)
{
if(!rsmd.getColumnName(j).equals("ID"))
{
String str = rs.getString(j)==null?"": rs.getString(j);
if(str.equals("null"))str = "";
map.put(rsmd.getColumnName(j), str);
}
else
map.put("id", rs.getString(j));
}
list.add(map);
}
rs.close();
st.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
if(sql.equals("show tables"))
list = select("select table_name from INFORMATION_SCHEMA.tables");
else
e.printStackTrace();
}
return list;
}
public List<List> selectforlist(String sql)
{
List<List> list = new ArrayList();
try {
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery(sql);
ResultSetMetaData rsmd = rs.getMetaData();
while(rs.next())
{
List<String> list2 = new ArrayList();
int i = rsmd.getColumnCount();
for(int j=1;j<=i;j++)
{
if(!rsmd.getColumnName(j).equals("ID"))
{
String str = rs.getString(j)==null?"": rs.getString(j);
if(str.equals("null"))str = "";
list2.add( str);
}
else
list2.add(rs.getString(j));
}
list.add(list2);
}
rs.close();
st.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return list;
}
public void close()
{
}
/**
* 执行一条查询sql,以 List<hashmap> 的形式返回查询的记录,记录条数,和从第几条开始,由参数决定,主要用于翻页
* pageno 页码 rowsize 每页的条数
*/
public List<HashMap> select(String sql, int pageno, int rowsize) {
List<HashMap> list=new ArrayList<HashMap>();
List<HashMap> mlist=new ArrayList<HashMap>();
try{
list=this.select(sql);
int min = (pageno-1)*rowsize;
int max = pageno*rowsize;
for(int i=0;i<list.size();i++)
{
if(!(i<min||i>(max-1)))
{
mlist.add(list.get(i));
}
}
}catch(RuntimeException re){
re.printStackTrace();
throw re;
}
return mlist;
}
public static void main(String[] args) {
}
}
源码获取:俺的博客首页 "资源" 里下载!