servlet增删查改

数据库:

usebean映射数据库中的表

package com.example;

public class userBean {
	
	private int userId;
	private String username;
	private String passwd;
	private int grade;
	
	public int getUserId() {
		return userId;
	}
	public void setUserId(int userId) {
		this.userId = userId;
	}
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getPasswd() {
		return passwd;
	}
	public void setPasswd(String passwd) {
		this.passwd = passwd;
	}
	public int getGrade() {
		return grade;
	}
	public void setGrade(int grade) {
		this.grade = grade;
	}
	
	
}

userbeanCl对数据库处理:

package com.example;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;

public class userBeanCL {
	
	private Connection ct = null;
	private PreparedStatement ps = null;
	private ResultSet rs = null;
	private int pageCount = 0;//共有多少页(计算)
	
	public int getPageCount(){
		return this.pageCount;
	}
	
	//修改用户
public boolean updateUser(String id,String passwd, String grade){
		
		boolean b = false;
		try 
		{
			//得到连接
			connDB cd = new connDB();
			ct = cd.getConn();
			String sql = "UPDATE users SET passwd='"+passwd+ "', grade='"+grade+"'  WHERE userId='"+id + "'";
			ps = ct.prepareStatement(sql);
			int num = ps.executeUpdate();
			if(num == 1){
				//删除成功
				b = true;
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			this.close();
		}
		return b;
	}
	//删除用户
	public boolean delUser(String id){
		
		boolean b = false;
		try 
		{
			//得到连接
			connDB cd = new connDB();
			ct = cd.getConn();
			String sql = "delete from users WHERE userid='"+id + "'";
			ps = ct.prepareStatement(sql);
			int num = ps.executeUpdate();
			if(num == 1){
				//删除成功
				b = true;
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			this.close();
		}
		return b;
	}
	
	//分页显示结果
	public ArrayList getResultByPage(int pageNow,int pageSize){
		
		ArrayList al = new ArrayList();
		
		int rowCount = 0;//共有多少条记录(查表)
		
		try 
		{
			//得到rowCount
			connDB cd = new connDB();
			ct = cd.getConn();
			ps = ct.prepareStatement("SELECT COUNT(*) FROM users");
			rs = ps.executeQuery();
			if(rs.next())
			   rowCount = rs.getInt(1);
			//共分为多少页
			if(rowCount % pageSize == 0){
				pageCount = rowCount/pageSize;
			}else{
				pageCount = rowCount/pageSize + 1;
			}
			ps.close();
			rs.close();
			//每页上需要显示的结果
			ps = ct.prepareStatement("SELECT * FROM users LIMIT " + (pageNow-1)*pageSize + ","
							                 + pageSize +";");
			rs = ps.executeQuery();
			
			while(rs.next()){
				//将rs中的每条记录封装到userbean中
				userBean ub = new userBean();
				ub.setUserId(rs.getInt(1));
				ub.setUsername(rs.getString(2));
				ub.setPasswd(rs.getString(3));
				ub.setGrade(rs.getInt(4));
				//将ub放入ArrayList中
				al.add(ub);
			}
		}catch(Exception ex){
			ex.printStackTrace();
		}finally{
			this.close();
		}
		return al;
	}
	
	//验证用户
	public boolean checkUser(String u,String p){
		boolean b = false;
		try
		{
			//得到连接
			connDB cd = new connDB();
			ct = cd.getConn();
			
			ps = ct.prepareStatement("SELECT passwd FROM users WHERE username=? LIMIT 1;");
			ps.setString(1, u);
			rs = ps.executeQuery();
			if(rs.next()){
				String dbPasswd = rs.getString(1);
				if(dbPasswd.equals(p)){
					b = true;
				}
			}
			
			
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			this.close();
		}
		
		return b;
	}
	
	//关闭资源
	public void close(){
		try {
			if(rs != null){
				rs.close();
				rs = null;
			}
			if(ps != null){
				ps.close();
				ps = null;
			}
			if(ct != null){
				ct.close();
				ct = null;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

connDB连接数据库得到Connection

package com.example;

import java.sql.Connection;
import java.sql.DriverManager;

public class connDB {

	private Connection ct = null;

	public Connection getConn() {
		
		try 
		{
			Class.forName("com.mysql.jdbc.Driver");
			ct = DriverManager.getConnection("jdbc:mysql://localhost:3306/yuippe", "root", "123456");
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		
		return ct;
	}
}

----------------------------------------------------------------------------------------------------------------------------------------------

登陆页面login:

package com.example;

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;

public class Login extends HttpServlet{

	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		
		resp.setContentType("text/html;charset=utf-8");
		
		PrintWriter pw = resp.getWriter();
		pw.println("");
		pw.println("");
		pw.println("
"); pw.println("

登陆界面

"); pw.println("
"); pw.println("用户名:
"); pw.println("密码:
"); pw.println("两周内不再重新登陆
"); pw.println("
"); pw.println("
"); pw.println("
"); pw.println(""); pw.println(""); } public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { this.doGet(req, resp); } }

主页面Main

//主界面
package com.example;

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;

public class Main extends HttpServlet{

	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		
		resp.setContentType("text/html;charset=utf-8");
		
		PrintWriter pw = resp.getWriter();
		pw.println("");
		pw.println("");
		pw.println("
"); pw.println("

主界面

"); pw.println("管理用户
"); pw.println("添加用户
"); pw.println("查找用户
"); pw.println("安全退出
"); pw.println("

"); pw.println(""); pw.println(""); } public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { this.doGet(req, resp); } }

loginCl登陆验证处理:

//用户验证
package com.example;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

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;

public class LoginCL extends HttpServlet{
	
	//重写
	public void init() throws ServletException {
		try {
			FileReader fr = new FileReader("E:/workspace/myWebApp/MyCount.txt");
			BufferedReader br = new BufferedReader(fr);
			//读取一行数据
			String numVal = br.readLine();
			//关闭
			br.close();
			
			//将文本中的数据写入Context中
			this.getServletContext().setAttribute("visitTimes", numVal);
			
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	@Override
	public void destroy() {
		try {
			FileWriter fw = new FileWriter("E:/workspace/myWebApp/MyCount.txt");
			BufferedWriter bw = new BufferedWriter(fw);
			bw.write(this.getServletContext().getAttribute("visitTimes").toString());
			bw.close();
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		
		//接受用户名和密码
		String u = req.getParameter("username");
		String p = req.getParameter("passwd");
		
		//操作数据库
		Connection ct = null;
		Statement stat = null;
		ResultSet rs = null;
		
		try {
			//调用userBeanCL
			userBeanCL ubc = new userBeanCL();
			if(ubc.checkUser(u, p)){
				//查看是否有需要设置cookie
				String keep = req.getParameter("keep");
				if(keep != null){
					//将用户名与密码保存在客户端
					Cookie name = new Cookie("myname", u);
					Cookie pass = new Cookie("mypasswd", p);
					//设置时间
					name.setMaxAge(14*24*3600);
					pass.setMaxAge(14*24*3600);
						
					resp.addCookie(name);
					resp.addCookie(pass);
				}
					
				//用户信息存入session
				HttpSession hs = req.getSession(true);
				hs.setMaxInactiveInterval(60);
				hs.setAttribute("name", u);
				
				//将访问次数加1
				String time = this.getServletContext().getAttribute("visitTimes").toString();
				this.getServletContext().setAttribute("visitTimes", (Integer.parseInt(time) + 1)+""); 
				
				//跳转
				resp.sendRedirect("Main");
			}
			else{
				resp.sendRedirect("login");
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			try 
			{
				if(rs != null){
					rs.close();
				}
				if(stat != null){
					stat.close();
				}
				if(ct != null){
					ct.close();
				}
			
			} catch (Exception e) {
					e.printStackTrace();
				
			}
		}
	}
	
	public void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		this.doGet(req, resp);
	}
}


update与updateCl

package com.example;

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;

public class Update extends HttpServlet{

	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		
		resp.setContentType("text/html;charset=utf-8");
		
		PrintWriter pw = resp.getWriter();
		pw.println("");
		pw.println("");
		pw.println("
"); pw.println("

修改用户界面

"); pw.println("
"); pw.println(""); pw.println(""); pw.println(""); pw.println(""); pw.println(""); pw.println(""); pw.println("
id
name
passwd
grade
"); pw.println("

"); pw.println(""); pw.println(""); } public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { this.doGet(req, resp); } }

package com.example;

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;

public class UpdateCl extends HttpServlet{

	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
			try 
			{
				resp.setContentType("text/html;charset=utf-8");
				userBeanCL ubc = new userBeanCL();
				//接受从wel.java中传递的id
				if(ubc.updateUser(req.getParameter("userid"), req.getParameter("newPass"), req.getParameter("newGrade")))
				{
					//删除成功
					resp.sendRedirect("Ok");
				}else
				{
					//删除失败
					resp.sendRedirect("Err");
				}
				
			} catch (Exception e) {
				e.printStackTrace();
			}
	}
	
	public void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		this.doGet(req, resp);
	}
}


delUserCl

package com.example;

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;

public class DelUserCl extends HttpServlet{

	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
			try 
			{
				resp.setContentType("text/html;charset=utf-8");
				userBeanCL ubc = new userBeanCL();
				//接受从wel.java中传递的id
				String id = req.getParameter("userid");
				if(ubc.delUser(id))
				{
					//删除成功
					resp.sendRedirect("Ok");
				}else
				{
					//删除失败
					resp.sendRedirect("Err");
				}
				
			} catch (Exception e) {
				e.printStackTrace();
			}
	}
	
	public void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		this.doGet(req, resp);
	}
}

wel:

//欢迎界面
package com.example;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;

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;

public class Wel extends HttpServlet{
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		
		HttpSession hs = req.getSession(true);
		String val = (String)hs.getAttribute("name");
		String name="";
		String passwd="";
		
		//判断
		if(val == null){
			//session中没有用户信息,在查看cookie信息
			Cookie[] allCookies = req.getCookies();
			int i = 0;
			if(allCookies != null){
				for(i = 0; i < allCookies.length; i++){
					//依次取出
					Cookie temp = allCookies[i];
					if(temp.getName().equals("myname")){
						name = temp.getValue();
					}else if(temp.getName().equals("mypasswd")){
						passwd = temp.getValue();
					}
				}
				
				if(!name.equals("")&&!passwd.equals("")){
					//跳转到logincl去验证信息
					resp.sendRedirect("logincl?username=" + name + "&passwd=" + passwd);
					return;
				}
				
			}
			
			resp.sendRedirect("login");
		}
		
		//分页
		int pageSize = 3;//一页显示几条记录
		int pageNow = 1; //目前显示的页数
		
		
		//动态的接受pageNow
		String spageNow = req.getParameter("pageNow");
		if(spageNow != null)
		pageNow = Integer.parseInt(spageNow);
		
		//调用userBeanCL
		userBeanCL ubc = new userBeanCL();
		ArrayList al = ubc.getResultByPage(pageNow, pageSize);
		
			resp.setContentType("text/html;charset=utf-8");
			PrintWriter pw = resp.getWriter();
			pw.println("");
			
			pw.println("");
			pw.println("");
			pw.println("返回到主界面");
			pw.println("

管理用户

"); //做一个超链接 pw.println("
返回重新登陆"); pw.println(""); //显示结果表格 pw.println(""+ ""+""); //定义一颜色数组 String[] mycol = {"silver", "pink"}; for(int i = 0; i < al.size(); i++) { userBean ub = al.get(i); pw.println(""); pw.println(""); pw.println(""); pw.println(""); pw.println(""); pw.println(""); pw.println(""); pw.println(""); } pw.println("
userIdusernamepasswdgrade修改用户删除用户
" + ub.getUserId() + "" + ub.getUsername() + "" + ub.getPasswd() + "" + ub.getGrade() + "修改用户删除用户
"); //显示上一页 if(pageNow != 1) pw.println(""+"上一页"+""); //显示5个页面超链接 for(int i=pageNow; i < pageNow+5; i++){ pw.println("" +i+ ""); } //显示下一页 int pageCount = ubc.getPageCount(); if(pageNow != pageCount) pw.println(""+"下一页"+"
"); //指定跳转到页 pw.println("
"); pw.println(""); pw.println(""); pw.println("
"); pw.println("您的页面被访问了" + this.getServletContext().getAttribute("visitTimes") +"次
"); pw.println("您的ip=" + req.getRemoteAddr() + "
"); pw.println("您的机器名为=" + req.getRemoteHost() + "
"); pw.println("

"); pw.println(""); pw.println(""); } public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { this.doGet(req, resp); } }

Err:

package com.example;

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;

public class Err extends HttpServlet{

	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		
		resp.setContentType("text/html;charset=utf-8");
		
		PrintWriter pw = resp.getWriter();
		pw.println("");
		pw.println("");
		pw.println("
"); pw.println("

很遗憾,操作失败

"); pw.println("返回主界面     继续删除"); pw.println("

"); pw.println(""); pw.println(""); } public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { this.doGet(req, resp); } }


ok:

package com.example;

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;

public class Ok extends HttpServlet{

	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		
		resp.setContentType("text/html;charset=utf-8");
		
		PrintWriter pw = resp.getWriter();
		pw.println("");
		pw.println("");
		pw.println("
"); pw.println("

恭喜你,操作成功

"); pw.println("返回主界面     继续"); pw.println("

"); pw.println(""); pw.println(""); } public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { this.doGet(req, resp); } }



你可能感兴趣的:(java)