com.entity.TblUser.java
package com.entity;
public class TblUser {
private int operator_id;
private String name;
private String password;
private Integer status;
public int getOperator_id() {
return operator_id;
}
public void setOperator_id(int operator_id) {
this.operator_id = operator_id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
}
basedao.java
package com.dao;
import java.sql.*;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
public class BaseDao {
public final static String driver = "com.microsoft.sqlserver.jdbc.SQLServerDriver"; // 数据库驱动
public final static String url = "jdbc:sqlserver://localhost:3306;databaseName=order";// url
public final static String dbName = "root"; // 数据库用户名
public final static String dbPass = "root"; // 数据库密码
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs=null;
/**
* 得到数据库连接
* @throws ClassNotFoundException
* @throws SQLException
* @return 数据库连接
* @throws NamingException
*/
public Connection getConn() throws ClassNotFoundException, SQLException, NamingException{
Class.forName(driver); //注册驱动
Connection conn = DriverManager .getConnection(url,dbName,dbPass); //获得数据库连接
// InitialContext cxt = new InitialContext();
// DataSource ds = (DataSource) cxt.lookup( "java:/comp/env/jdbc/postgres" );
// Connection conn=ds.getConnection();
return conn ; //返回连接
}
/**
* 释放资源
* @param conn 数据库连接
* @param pstmt PreparedStatement对象
* @param rs 结果集
*/
public void closeAll( Connection conn, PreparedStatement pstmt, ResultSet rs ) {
/* 如果rs不空,关闭rs */
if(rs != null){
try { rs.close();} catch (SQLException e) {e.printStackTrace();}
}
/* 如果pstmt不空,关闭pstmt */
if(pstmt != null){
try { pstmt.close();} catch (SQLException e) {e.printStackTrace();}
}
/* 如果conn不空,关闭conn */
if(conn != null){
try { conn.close();} catch (SQLException e) {e.printStackTrace();}
}
}
/**
* 执行SQL语句,可以进行增、删、改的操作,不能执行查询
* @param sql 预编译的 SQL 语句
* @param param 预编译的 SQL 语句中的‘?’参数的字符串数组
* @return 影响的条数
*/
public int executeSQL(String preparedSql,String[] param) {
Connection conn = null;
PreparedStatement pstmt = null;
int num = 0;
/* 处理SQL,执行SQL */
try {
conn = getConn(); // 得到数据库连接
pstmt = conn.prepareStatement(preparedSql); // 得到PreparedStatement对象
if( param != null ) {
for( int i = 0; i < param.length; i++ ) {
pstmt.setString(i+1, param[i]); // 为预编译sql设置参数
}
}
num = pstmt.executeUpdate(); // 执行SQL语句
} catch (ClassNotFoundException e) {
e.printStackTrace(); // 处理ClassNotFoundException异常
} catch (Exception e) {
e.printStackTrace(); // 处理SQLException异常
} finally {
closeAll(conn,pstmt,null); // 释放资源
}
return num;
}
}
index.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>My JSP 'index.jsp' starting page</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">
-->
</head>
<body>
<form action="getall" method="post">
用户名:<input name="uname"> <br>
密码:<input name="upass" ><br>
<input type="submit" value="提交">
<form>
</body>
</html>
UserDao.java
package com.dao;
import java.util.ArrayList;
import java.util.List;
import com.entity.TblUser;
public class UserDao extends BaseDao {
public List getAll(TblUser u){
List list=new ArrayList();
String sql="SELECT * FROM [njry].[dbo].[tbl_user] where 1=1 ";
if(u!=null){
if(u.getName()!=null && !u.getName().trim().equals("")){
sql+=" and name like '%" +u.getName()+"%'";
}
if(u.getStatus()!=null){
sql+=" and status =" +u.getStatus();
}
}
System.out.println(sql);
try {
conn=getConn();
pstmt=conn.prepareStatement(sql);
rs=pstmt.executeQuery();
while (rs.next()) {
TblUser user = new TblUser();
user.setName(rs.getString("name"));
user.setOperator_id(rs.getInt("operator_id"));
user.setPassword(rs.getString("password"));
user.setStatus(rs.getInt("status"));
list.add(user);
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return list;
}
public TblUser getUserByName(String name){
TblUser user = null;
String sql="SELECT * FROM [njry].[dbo].[tbl_user] where name = '" +name+"'";
try {
conn=getConn();
pstmt=conn.prepareStatement(sql);
rs=pstmt.executeQuery();
if (rs.next()) {
user=new TblUser();
user.setName(rs.getString("name"));
user.setOperator_id(rs.getInt("operator_id"));
user.setPassword(rs.getString("password"));
user.setStatus(rs.getInt("status"));
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return user;
}
public TblUser getUserById(String id){
TblUser user = null;
String sql="SELECT * FROM [njry].[dbo].[tbl_user] where operator_id = '" +id+"'";
try {
conn=getConn();
pstmt=conn.prepareStatement(sql);
rs=pstmt.executeQuery();
if (rs.next()) {
user=new TblUser();
user.setName(rs.getString("name"));
user.setOperator_id(rs.getInt("operator_id"));
user.setPassword(rs.getString("password"));
user.setStatus(rs.getInt("status"));
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return user;
}
public int add(TblUser u){
int r = 0;
String sql="insert into tbl_user values(?,?,?)";
try {
conn=getConn();
pstmt=conn.prepareStatement(sql);
pstmt.setString(1, u.getName());
pstmt.setString(2, u.getPassword());
pstmt.setInt(3, u.getStatus());
r=pstmt.executeUpdate();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return r;
}
public int delById(int id){
int r = 0;
String sql="delete from tbl_user where operator_id=?";
try {
conn=getConn();
pstmt=conn.prepareStatement(sql);
pstmt.setInt(1, id);
r=pstmt.executeUpdate();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return r;
}
public static void main(String[] args) {
System.out.println(new UserDao().getUserById("2").getName());
}
public int update(TblUser u) {
// TODO Auto-generated method stub
int r = 0;
String sql="update tbl_user set password=?,status=? where operator_id=?";
try {
conn=getConn();
pstmt=conn.prepareStatement(sql);
pstmt.setString(1, u.getPassword());
pstmt.setInt(2, u.getStatus());
pstmt.setInt(3, u.getOperator_id());
r=pstmt.executeUpdate();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return r;
}
}
com.action.add.java
package com.action;
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 javax.xml.registry.infomodel.User;
import com.dao.UserDao;
import com.entity.TblUser;
public class add extends HttpServlet {
/**
* 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 {
response.setContentType("text/html;charset=UTF-8");
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
PrintWriter out = response.getWriter();
String name=request.getParameter("name");
UserDao ud=new UserDao();
TblUser u=ud.getUserByName(name);
if(u!=null){
request.setAttribute("msg", "该用户名已经存在");
request.getRequestDispatcher("add.jsp").forward(request, response);
}else{
String pass=request.getParameter("password");
String status=request.getParameter("status");
u=new TblUser();
u.setName(name);
u.setPassword(pass);
u.setStatus(Integer.parseInt(status));
int r=ud.add(u);
if(r>0){
out.print("<script>alert('恭喜你,用户添加成功!');close();</script>");
}else{
out.print("<script>alert('对不起,用户添加失败,请稍后重试!');close();</script>");
}
}
}
/**
* 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 {
doGet(request, response);
// response.setContentType("text/html");
// PrintWriter out = response.getWriter();
// out
// .println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
// out.println("<HTML>");
// out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>");
// out.println(" <BODY>");
// out.print(" This is ");
// out.print(this.getClass());
// out.println(", using the POST method");
// out.println(" </BODY>");
// out.println("</HTML>");
// out.flush();
// out.close();
}
}
com.action.getall.java
package com.action;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.dao.UserDao;
import com.entity.TblUser;
public class getall extends HttpServlet {
/**
* 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 {
HttpSession session = request.getSession();
Cookie[] cookies=request.getCookies();
Cookie ckUname;
Cookie ckUpass;
String uname="";
String upass="";
if(cookies!=null){
for (int i = 0; i < cookies.length; i++) {
ckUname=cookies[i];
if(ckUname.getName().equals("uname") ){
uname=ckUname.getValue();
}
else if(ckUname.getName().equals("upass") ){
upass=ckUname.getValue();
}
}
}
if ("abc".equals(uname) && "123".equals(upass)) {
session.setAttribute("uname", uname);
}else{
uname = request.getParameter("uname");
upass = request.getParameter("upass");
if ("abc".equals(uname) && "123".equals(upass)) {
session.setAttribute("uname", uname);
ckUname=new Cookie("uname",uname);
ckUpass=new Cookie("upass",upass);
ckUname.setMaxAge(24*60*60);
ckUpass.setMaxAge(24*60*60);
response.addCookie(ckUname);
response.addCookie(ckUpass);
}else{
response.sendRedirect("index.jsp");
return;
}
}
TblUser user = new TblUser();
user.setName(request.getParameter("name"));
String sts = request.getParameter("status");
if (sts != null && !sts.equals("")) {
user.setStatus(Integer.parseInt(sts));
}
System.out.println(sts);
List list = new UserDao().getAll(user);
request.setAttribute("list", list);
request.getRequestDispatcher("getall.jsp").forward(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 {
doGet(request, response);
/*
* response.setContentType("text/html"); PrintWriter out =
* response.getWriter(); out .println("<!DOCTYPE HTML PUBLIC
* \"-//W3C//DTD HTML 4.01 Transitional//EN\">"); out.println("<HTML>");
* out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>");
* out.println(" <BODY>"); out.print(" This is ");
* out.print(this.getClass()); out.println(", using the POST method");
* out.println(" </BODY>"); out.println("</HTML>"); out.flush();
* out.close();
*/
}
}
getall.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>My JSP 'index.jsp' starting page</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">
-->
<script type="text/javascript">
function toadd(){
open('add.jsp','add','width=200, height=300');
}
function dodel(op,id){
if(confirm("确认删除用户"+op)){
location.href('delete?id='+id);
}
}
</script>
</head>
<body>
<a href="javascript:toadd()">创建用户</a>
<form id="form1" name="form1" method="post" action="getall">
<table width="600" border="0" align="center" cellpadding="10">
<tr>
<td>按姓名查找:</td>
<td><input name="name" type="text" /></td>
<td>
<select name="status" id="select">
<option value="">请选择</option>
<option value="1">有效</option>
<option value="0">无效</option>
</select></td>
<td><input type="submit" name="button" id="button" value="提交" /></td>
</tr>
</table>
</form>
<table width="600" border="0" align="center" cellpadding="10">
<tr>
<td align="left"><strong>帐号</strong></td>
<td align="left"><strong>姓名</strong></td>
<td align="left"><strong>密码</strong></td>
<td align="left"><strong>状态</strong></td>
<td align="left"><strong>删除</strong></td>
<td align="left"><strong>修改</strong></td>
</tr>
<c:forEach var="user" items="${requestScope.list}">
<tr>
<td>${user.operator_id }</td>
<td>${user.name }</td>
<td>${user.password }</td>
<td>${user.status }</td>
<td><a href="javascript:dodel('${user.name }','${user.operator_id }')">删除</a> </td>
<td><a href="update?id=${user.operator_id }">修改</a> </td>
</tr>
</c:forEach>
</table>
</body>
</html>
com.action.delete.java
package com.action;
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.dao.UserDao;
public class delete extends HttpServlet {
/**
* 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 {
String id=request.getParameter("id");
int r=new UserDao().delById(Integer.parseInt(id));
response.sendRedirect("getall");
}
/**
* 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 {
doGet(request, response);
// response.setContentType("text/html");
// PrintWriter out = response.getWriter();
// out
// .println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
// out.println("<HTML>");
// out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>");
// out.println(" <BODY>");
// out.print(" This is ");
// out.print(this.getClass());
// out.println(", using the POST method");
// out.println(" </BODY>");
// out.println("</HTML>");
// out.flush();
// out.close();
}
}
update.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>update</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">
-->
<script type="text/javascript">
function cheAll(){
var name=document.form1.name.value;
var password=document.form1.password.value;
if(name.length==0 || password.length==0){
alert("用户名密码必填");
return false;
}
return true;
}
</script>
</head>
<body>
<form id="form1" name="form1" method="post" action="doupdate" οnsubmit="return cheAll()">
<input type="hidden" name="id" value="${user.operator_id }">
<table width="200" border="0" align="center" cellpadding="10">
<tr>
<td align="left"><strong>姓名</strong></td>
<td><input name="name" value="${sessionScope.user.name }" readonly="readonly" style="border: 0"> </td>
</tr>
<tr>
<td align="left"><strong>密码</strong></td>
<td><input name="password" value="${user.password }"></td>
</tr>
<tr>
<td align="left"><strong>状态</strong></td>
<td>
<select name="status" id="select">
<option value="1" <c:if test="${user.status==1 }" >selected</c:if>>有效</option>
<option value="0" <c:if test="${user.status==0 }" >selected</c:if>>无效</option>
</select>
</td>
</tr>
<tr>
<td align="left"><input type="submit" value="提交"/> </td>
<td> </td>
</tr>
</table>
</form>
</body>
</html>
com.action.doupdate.java
package com.action;
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 javax.servlet.http.HttpSession;
import com.dao.UserDao;
import com.entity.TblUser;
public class doupdate extends HttpServlet {
/**
* 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 {
response.setContentType("text/html;charset=UTF-8");
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
PrintWriter out = response.getWriter();
String name = request.getParameter("name");
UserDao ud = new UserDao();
String pass = request.getParameter("password");
String status = request.getParameter("status");
String id=request.getParameter("id");
TblUser u = new TblUser();
u.setOperator_id(Integer.parseInt(id));
u.setName(name);
u.setPassword(pass);
u.setStatus(Integer.parseInt(status));
int r = ud.update(u);
if (r > 0) {
HttpSession session=request.getSession();
session.removeAttribute("user");
out.print("<script>alert('恭喜你,用户更新成功!');close();</script>");
} else {
out.print("<script>alert('对不起,用户更新失败,请稍后重试!');close();</script>");
}
}
/**
* 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 {
doGet(request, response);
// response.setContentType("text/html");
// PrintWriter out = response.getWriter();
// out
// .println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01
// Transitional//EN\">");
// out.println("<HTML>");
// out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>");
// out.println(" <BODY>");
// out.print(" This is ");
// out.print(this.getClass());
// out.println(", using the POST method");
// out.println(" </BODY>");
// out.println("</HTML>");
// out.flush();
// out.close();
}
}
fileupload.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>My JSP 'index.jsp' starting page</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">
-->
</head>
<body>
<form action="getfile" method="post" enctype="multipart/form-data" >
文件:<input type="file" name="nfile"><br>
介绍:<input name="miaoshu" type="text"><br>
<input type="submit" value="提交">
<form>
</body>
</html>
com.action.update.java
package com.action;
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 javax.servlet.http.HttpSession;
import com.dao.UserDao;
import com.entity.TblUser;
public class update extends HttpServlet {
/**
* 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 {
HttpSession session=request.getSession();
if(session.getAttribute("uname")==null){
response.sendRedirect("index.jsp");
return ;
}
String id=request.getParameter("id");
TblUser user=new UserDao().getUserById(id);
session.setAttribute("user", user);
PrintWriter out = response.getWriter();
out.print("<script>open('update.jsp','update','width=200, height=300');history.go(-1)</script>");
}
/**
* 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 {
doGet(request, response);
// response.setContentType("text/html");
// PrintWriter out = response.getWriter();
// out
// .println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
// out.println("<HTML>");
// out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>");
// out.println(" <BODY>");
// out.print(" This is ");
// out.print(this.getClass());
// out.println(", using the POST method");
// out.println(" </BODY>");
// out.println("</HTML>");
// out.flush();
// out.close();
}
}