Servlet增删改查案例经典实现

合集下载

JDBC+Servlet+JSP的学生案例增删改查

JDBC+Servlet+JSP的学生案例增删改查

JDBC+Servlet+JSP的学⽣案例增删改查数据库信息传输到页⾯实现。

先进⾏学⽣信息页⾯展⽰:接⼝IStudentDaopublic interface IStudentDao {/*** 保存操作* @param stu 学⽣对象,封装了需要保存的对象*/void save(Student stu);/*** 删除操作* @param id 被删除学⽣的主键操作*/void delete(Long id);/**** @param id 被更改学⽣的主键值* @param newStu 学⽣新的信息*/void update(Student newStu);/*** 查询指定id的学⽣对象* @param id 被查询学⽣的主键值* @return如果id存在,返回学⽣对象,否则为null*/Student get(Long id);/*** 查询并返回所有学⽣对象* @return如果结果集为空,返回⼀个空的list对象*/List<Student> listall();}IStudentDaoImplpublic class IStudentDaoImpl implements IStudentDao{public void save(Student stu) {String sql ="insert into t_student (name,age) values (?,?)";PreparedStatement ps = null;//贾琏Connection conn = null;try {conn = JDBCUtil.getConn();ps = conn.prepareStatement(sql);//欲ps.setString(1, stu.getName());ps.setInt(2, stu.getAge());ps.executeUpdate();//执⾏} catch (SQLException e) {e.printStackTrace();}JDBCUtil.close(conn, ps, null);//事务}@Overridepublic void delete(Long id) {String sql ="delete from t_student where id = ?";PreparedStatement ps =null;//贾琏Connection conn = null;try {conn = JDBCUtil.getConn();ps =conn.prepareStatement(sql);ps.setLong(1, id);ps.executeUpdate();}JDBCUtil.close(conn, ps, null);}//update t_student set name='xx',age=17 where id=12@Overridepublic void update(Student stu) {String sql="update t_student set name =? ,age=? where id=?"; PreparedStatement ps =null;//贾琏Connection conn =null;try {conn = JDBCUtil.getConn();ps=conn.prepareStatement(sql);ps.setString(1, stu.getName());ps.setInt(2, stu.getAge());ps.setLong(3, stu.getId());ps.executeUpdate();} catch (Exception e) {e.printStackTrace();}JDBCUtil.close(conn, ps, null);}public Student get(Long id) {String sql ="select * from t_student where id=?";PreparedStatement ps =null;//贾琏Connection conn =null;ResultSet rs = null;try {conn = JDBCUtil.getConn();ps = conn.prepareStatement(sql);ps.setLong(1, id);rs= ps.executeQuery();if (rs.next()) {Student stu = new Student();stu.setId(rs.getLong("id"));stu.setName(rs.getString("name"));stu.setAge(rs.getInt("age"));return stu;}} catch (Exception e) {e.printStackTrace();}JDBCUtil.close(conn, ps, rs);return null;}@Overridepublic List<Student> listall() {List<Student> list = new ArrayList<>();String sql ="select * from t_student";PreparedStatement ps = null;Connection conn = null;ResultSet rs =null;try {conn = JDBCUtil.getConn();ps = conn.prepareStatement(sql);rs = ps.executeQuery();while(rs.next()){Student stu = new Student();stu.setId(rs.getLong("id"));stu.setName(rs.getString("name"));stu.setAge(rs.getInt("age"));list.add(stu);}}finally {JDBCUtil.close(conn, ps, rs);}return list;}domain类public class Student {private Long id;private String name;private Integer age;public Student(){}public Student(String name,Integer age){this.age=age;=name;}public Long getId() {return id;}public void setId(Long id) {this.id = id;}public String getName() {return name;}public void setName(String name) { = name;}public Integer getAge() {return age;}public void setAge(Integer age) {this.age = age;}@Overridepublic String toString() {return "Student [id=" + id + ", name=" + name + ", age=" + age + "]";}}设计个util类,⽅便维护public class JDBCUtil {private static DataSource ds =null;static{//当JDBCUtil执⾏后,直接加载⾄JVM就⽴即执⾏try {Properties p = new Properties();p.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("db.properties")); ds = DruidDataSourceFactory.createDataSource(p);} catch (Exception e) {e.printStackTrace();}}public static Connection getConn(){try {return ds.getConnection();} catch (SQLException e) {e.printStackTrace();}return null;}public static void close(Connection conn,Statement st,ResultSet rs){try {if (rs!=null) {rs.close();}} catch (Exception e) {}finally {try {if (st!=null) {st.close();}} catch (Exception e) {e.printStackTrace();}finally {try {if (conn!=null) {conn.close();}} catch (Exception e) {e.printStackTrace();}}}}}在⽹页展⽰全部信息,将数据⽤student传输过去,在前台获取。

最简单的jsp+servlet的增删改查代码

最简单的jsp+servlet的增删改查代码

最简单的jsp+servlet的增删改查代码package .dao;import java.sql.Connection;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;import java.util.ArrayList;import java.util.List;import .model.Admin;public class AdminDao {public List<Admin> getAllAdmin(){ //查询所有信息List<Admin> list = new ArrayList<Admin>(); //创建集合Connection conn = DbHelper.getConnection();String sql = "select * from admin"; //SQL查询语句try {PreparedStatement pst = conn.prepareStatement(sql);ResultSet rst = pst.executeQuery();while (rst.next()) {Admin admin = new Admin();admin.setId(rst.getInt("id")); //得到IDadmin.setUsername(rst.getString("username"));admin.setUserpwd(rst.getString("userpwd"));list.add(admin);}rst.close(); //关闭pst.close(); //关闭} catch (SQLException e) {e.printStackTrace(); //抛出异常}return list; //返回⼀个集合}public boolean addAdmin(Admin admin){ //添加信息String sql = "INSERT INTO `admin`(`id`,`username`,`userpwd`) VALUES (?,?,?)"; //添加的SQL语句Connection conn = DbHelper.getConnection();try {PreparedStatement pst = conn.prepareStatement(sql);pst.setInt(1, admin.getId());pst.setString(2, admin.getUsername());pst.setString(3, admin.getUserpwd());int count = pst.executeUpdate();pst.close();return count>0?true:false; //是否添加的判断} catch (SQLException e) {e.printStackTrace();}return false;}public boolean updateAdmin(Admin admin){ //修改String sql = "UPDATE `admin` SET `username`=?,`userpwd`=? WHERE `id` = ?"; //修改的SQL语句,根据ID修改Connection conn = DbHelper.getConnection();try {PreparedStatement pst = conn.prepareStatement(sql);pst.setString(1, admin.getUsername());pst.setString(2, admin.getUserpwd());pst.setInt(3, admin.getId()); //根据的IDint count = pst.executeUpdate();pst.close(); //关闭return count>0?true:false; //是否修改的判断} catch (SQLException e) {e.printStackTrace();}return false;}public boolean deleteAdmin(int id){ //删除String sql = "delete from admin where id = ?"; //删除的SQL语句,根据ID删除Connection conn = DbHelper.getConnection();try {PreparedStatement pst = conn.prepareStatement(sql);pst.setInt(1, id);int count = pst.executeUpdate();pst.close();return count>0?true:false; //是否删除的判断} catch (SQLException e) {e.printStackTrace();}return false;}public Admin selectAdminById(int id){ //根据ID进⾏查询Connection conn = DbHelper.getConnection();String sql = "select * from admin where id = "+id;Admin admin = null;try {PreparedStatement pst = conn.prepareStatement(sql);ResultSet rst = pst.executeQuery();while (rst.next()) {admin = new Admin();admin.setId(rst.getInt("id"));admin.setUsername(rst.getString("username"));admin.setUserpwd(rst.getString("userpwd"));}rst.close();pst.close();} catch (SQLException e) {e.printStackTrace();}return admin; //返回}}package .dao;import java.sql.Connection;import java.sql.DriverManager;/*** 连接数据库* @author画船听⾬眠**/public class DbHelper {private static String url = "jdbc:mysql://localhost:3306/admin"; //数据库地址private static String userName = "root"; //数据库⽤户名private static String passWord = "359129127"; //数据库密码private static Connection conn = null;private DbHelper(){}public static Connection getConnection(){if(null == conn){try {Class.forName("com.mysql.jdbc.Driver");conn = DriverManager.getConnection(url, userName, passWord);} catch (Exception e) {e.printStackTrace();}}return conn;}public static void main(String[] args) { //测试数据库是否连通System.err.println(getConnection());}}package .model;import java.io.Serializable;public class Admin implements Serializable{ //数据封装类private static final long serialVersionUID = 1L;private int id;private String username;private String userpwd;public int getId() {return id;}public void setId(int id) {this.id = id;}public String getUsername() {return username;}public void setUsername(String username) {ername = username;}public String getUserpwd() {return userpwd;}public void setUserpwd(String userpwd) {erpwd = userpwd;}}package .servlet;import java.io.IOException;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import .dao.AdminDao;import .model.Admin;public class AddServlet extends HttpServlet{ //添加数据private static final long serialVersionUID = 1L;protected void doGet(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {this.doPost(req, resp);}protected void doPost(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {String username = req.getParameter("username");String userpwd = req.getParameter("userpwd");Admin admin = new Admin();admin.setUsername(new String(username.getBytes("ISO-8859-1"),"UTF-8")); //转值,中⽂需要转换为utf-8 admin.setUserpwd(new String(userpwd.getBytes("ISO-8859-1"),"UTF-8"));AdminDao dao = new AdminDao();dao.addAdmin(admin);req.getRequestDispatcher("ShowServlet").forward(req, resp);}}package .servlet;import java.io.IOException;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import .dao.AdminDao;public class DeleteServlet extends HttpServlet{ //删除数据private static final long serialVersionUID = 1L;protected void doGet(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {this.doPost(req, resp);}protected void doPost(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {String idStr = req.getParameter("id"); //删除数据的ID,根据ID删除if(idStr != null && !idStr.equals("")){int id = Integer.valueOf(idStr);AdminDao dao = new AdminDao();dao.deleteAdmin(id);}req.getRequestDispatcher("ShowServlet").forward(req, resp);}}package .servlet;import java.io.IOException;import java.util.List;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import .dao.AdminDao;import .model.Admin;public class ShowServlet extends HttpServlet{ //显⽰全部数据private static final long serialVersionUID = 1L;protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {this.doPost(req, resp);}protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {AdminDao dao = new AdminDao();List<Admin> list = dao.getAllAdmin();req.setAttribute("list", list);req.getRequestDispatcher("index.jsp").forward(req, resp);}}package .servlet;import java.io.IOException;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import .dao.AdminDao;import .model.Admin;public class UpdateServlet extends HttpServlet{ //修改private static final long serialVersionUID = 1L;protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //查询到选中ID的值所对应的数据 String idStr = req.getParameter("id");if(idStr != null && !idStr.equals("")){int id = Integer.valueOf(idStr);AdminDao dao = new AdminDao();Admin admin = dao.selectAdminById(id);req.setAttribute("admin", admin);}req.getRequestDispatcher("update.jsp").forward(req, resp);}protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //根据此ID对数据的值进⾏修改 String username = req.getParameter("username");String userpwd = req.getParameter("userpwd");String idStr = req.getParameter("id");Admin admin = new Admin();admin.setId(Integer.valueOf(idStr));admin.setUsername(new String(username.getBytes("ISO-8859-1"),"UTF-8")); admin.setUserpwd(new String(userpwd.getBytes("ISO-8859-1"),"UTF-8")); AdminDao dao = new AdminDao();dao.updateAdmin(admin);req.getRequestDispatcher("ShowServlet").forward(req, resp);}}<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html><head><title>添加</title><link rel="stylesheet" href="css/index.css" type="text/css" /></head><body><form action="AddServlet" method="post"><table border="1" class="t1"><td colspan="2"><h1>添加管理员</h1></td></tr><tr><td>管理员帐号:</td><td><input type="text" name="username"/></td></tr><tr><td>管理员密码:</td><td><input type="password" name="userpwd"/></td></tr><tr><td colspan="2"><input type="submit" value="提交"/><input type="reset" value="清空"/></td></tr></table></form></body></html><%@ page language="java" contentType="text/html; charset=utf-8"pageEncoding="utf-8"%><%@ taglib prefix="c" uri="/jsp/jstl/core" %><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"><title>显⽰</title><style type="text/css">table {border: 1px solid pink;margin: 0 auto;}td{width: 150px;border: 1px solid pink;text-align: center;}</style></head><body><table><tr><td>编号</td><td>帐号</td><td>密码</td><td>操作</td></tr><c:forEach items="${list}" var="item"><tr><td>${item.id }</td><td>${ername }</td><td>${erpwd }</td><td><a href="DeleteServlet?id=${item.id }">删除</a>|<a href="UpdateServlet?id=${item.id }">修改</a></td> </tr></c:forEach><tr><td colspan="6" style="text-align: left;"><a href="add.jsp">添加管理员</a></td></tr></table></body></html><%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html><head><title>修改</title><link rel="stylesheet" href="css/index.css" type="text/css" /></head><body><form action="UpdateServlet" method="post"><table border="1" class="t1"><tr><td colspan="2"><h1>修改管理员信息</h1></td></tr><tr><td>编号:</td><td><input type="text" name="id" value="${admin.id}" readonly="readonly"/></td></tr><tr><td>管理员帐号:</td><td><input type="text" name="username" value="${ername}"/></td></tr><tr><td>管理员密码:</td><td><input type="text" name="userpwd" value="${erpwd}"/></td></tr><tr><td colspan="2"><input type="submit" value="提交"/><input type="button" value="返回" onclick="history.go(-1)"/></td></tr></table></form></body></html>@CHARSET "UTF-8";table.t1 {margin-top:10px;margin-left:20px;margin-right:20px;margin-bottom:5px;#background-color: #FFF;#background:#EEF4F9;#border: none;border: 1;#color:#003755;border-collapse:collapse;font: 14px "宋体";text-align: center;}table.t1 th{background:#7CB8E2;color:#fff;padding:6px 4px;text-align:center;}table.t1 td{background:#C7DDEE none repeat-x scroll center left;color:#000;padding:4px 2px;}table.t1 a{text-decoration:none;height:1em;}table.t1 a:link, table.t1 a:visited{color:#3366CC;}table.t1 a:hover{color:#B50000;text-decoration:underline;}最简单的jsp+servlet的增删改查代码。

jsp+servlet+jdbc实现对数据库的增删改查

jsp+servlet+jdbc实现对数据库的增删改查

jsp+servlet+jdbc实现对数据库的增删改查⼀、JSP和Servlet的简单介绍:1、Servlet和JSP简介: Java开发Web应⽤程序时⽤到的技术主要有两种,即Servlet和JSP,Servlet是在服务器端执⾏的Java程序,⼀个被称为Servlet容器的程序(其实就是服务器)负责执⾏Java程序,⽽JSP(Java Server Page)则是⼀个页⾯,由JSP容器负责执⾏。

2、Servlet和JSP的区别:Servlet以Java程序为主,输出HTML代码时需要使⽤out.println函数,也就是说Java中内嵌HTML;⽽JSP则以HTML页⾯为主,需要写Java代码时则在页⾯中直接插⼊Java代码,即HTML中内嵌Java。

3、MVC模型MVC模型就是将数据、逻辑处理、⽤户界⾯分离的⼀种⽅法。

1)、M(Model,模型):⽤于数据处理、逻辑处理2)、V(View,视图):⽤于显⽰⽤户界⾯3)、C(Controller,控制器):根据客户端的请求控制逻辑⾛向和画⾯⽽在Java中,MVC这三个部分则分别对应于 JavaBeans、JSP和Servlet1)、M = JavaBeans:⽤于传递数据,拥有与数据相关的逻辑处理2)、V = JSP:从Model接收数据并⽣成HTML3)、C = Servlet:接收HTTP请求并控制Model和View⼆、代码演⽰,实现了book的添加删除和修改功能1、环境的配置myeclipse+tomcat+MySQL2、Book中bean类:提供字段属性,并提供get/set⽅法package example.bean.book;public class Book {// 编号private int id;// 图书名称private String name;// 价格private double price;// 数量private int bookCount;// 作者private String author;public int getId() {return id;}public void setId(int id) {this.id = id;}public String getName() {return name;}public void setName(String name) { = name;}public double getPrice() {return price;}public void setPrice(double price) {this.price = price;}public int getBookCount() {return bookCount;}public void setBookCount(int bookCount) {this.bookCount = bookCount;}public String getAuthor() {return author;}public void setAuthor(String author) {this.author = author;}}3、Servlet类1)、FindServlet.javapackage example.servlet.book;import java.io.IOException;import java.sql.Connection;import java.sql.DriverManager;import java.sql.ResultSet;import java.sql.Statement;import java.util.ArrayList;import java.util.List;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import example.bean.book.Book;//导⼊包下的Book类/*** Servlet implementation class FindServlet*/public class FindServlet extends HttpServlet {private static final long serialVersionUID = 1L;/*** @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse* response)*/protected void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {try {// 加载数据库驱动,注册到驱动管理器Class.forName("com.mysql.jdbc.Driver");// 数据库连接字符串String url = "jdbc:mysql://localhost:3306/db_book?useUnicode=true&characterEncoding=utf-8";// 数据库⽤户名String username = "root";// 数据库密码String password = "";// 创建Connection连接Connection conn = DriverManager.getConnection(url, username,password);// 添加图书信息的SQL语句String sql = "select * from tb_books";// 获取StatementStatement statement = conn.createStatement();ResultSet resultSet = statement.executeQuery(sql);List<Book> list = new ArrayList<Book>();while (resultSet.next()) {Book book = new Book();book.setId(resultSet.getInt("id"));book.setName(resultSet.getString("name"));book.setPrice(resultSet.getDouble("price"));book.setBookCount(resultSet.getInt("bookCount"));book.setAuthor(resultSet.getString("author"));list.add(book);}request.setAttribute("list", list);resultSet.close();statement.close();conn.close();} catch (Exception e) {e.printStackTrace();}request.getRequestDispatcher("book_list.jsp").forward(request, response);}/*** @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse* response)*/protected void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {// TODO Auto-generated method stubdoGet(request, response);}}2)、UpdateServlet.java类package example.servlet.book;import java.io.IOException;import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;/*** Servlet implementation class UpdateServlet*/public class UpdateServlet extends HttpServlet {private static final long serialVersionUID = 1L;/*** @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse * response)*/protected void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {int id = Integer.valueOf(request.getParameter("id"));int bookCount = Integer.valueOf(request.getParameter("bookCount"));try {// 加载数据库驱动,注册到驱动管理器Class.forName("com.mysql.jdbc.Driver");// 数据库连接字符串String url = "jdbc:mysql://localhost:3306/db_book";// 数据库⽤户名String username = "root";// 数据库密码String password = "";// 创建Connection连接Connection conn = DriverManager.getConnection(url, username,password);// 更新SQL语句String sql = "update tb_books set bookcount=? where id=?";// 获取PreparedStatementPreparedStatement ps = conn.prepareStatement(sql);// 对SQL语句中的第⼀个参数赋值ps.setInt(1, bookCount);// 对SQL语句中的第⼆个参数赋值ps.setInt(2, id);// 执⾏更新操作ps.executeUpdate();// 关闭PreparedStatementps.close();// 关闭Connectionconn.close();} catch (Exception e) {e.printStackTrace();}// 重定向到FindServletresponse.sendRedirect("FindServlet");}/*** @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse * response)*/protected void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {// TODO Auto-generated method stubdoGet(request, response);}}3)、DeleteServlet类package example.servlet.book;import java.io.IOException;import java.sql.Connection;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import example.dao.book.BookJdbcDao;import example.dao.book.ConnectionFactory;/*** Servlet implementation class DeleteServlet*/public class DeleteServlet extends HttpServlet {private static final long serialVersionUID = 1L;/*** @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse * response)*/protected void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {int id = Integer.valueOf(request.getParameter("id"));try {//// 加载数据库驱动,注册到驱动管理器// Class.forName("com.mysql.jdbc.Driver");//// 数据库连接字符串// String url = "jdbc:mysql://localhost:3306/db_book";//// 数据库⽤户名// String username = "root";//// 数据库密码// String password = "";//// 创建Connection连接// Connection conn = DriverManager.getConnection(url, username,// password);//// 删除图书信息的SQL语句// String sql = "delete from tb_books where id=?";//// 获取PreparedStatement// PreparedStatement ps = conn.prepareStatement(sql);//// 对SQL语句中的第⼀个占位符赋值// ps.setInt(1, id);//// 执⾏更新操作// ps.executeUpdate();//// 关闭PreparedStatement// ps.close();//// 关闭Connection// conn.close();BookJdbcDao bookDao=new BookJdbcDao();Connection conn=ConnectionFactory.getInstance().getConnection();bookDao.delete(conn,id);} catch (Exception e) {e.printStackTrace();}// 重定向到FindServletresponse.sendRedirect("FindServlet");}/*** @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse* response)*/protected void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {doGet(request, response);}}4、servlet访问url映射配置: 由于客户端是通过URL地址访问web服务器中的资源,所以Servlet程序若想被外界访问,必须把servlet程序映射到⼀个URL地址上,这个⼯作在web.xml⽂件中使⽤<servlet>元素和<servlet-mapping>元素完成,<servlet>元素⽤于注册Servlet,它包含有两个主要的⼦元素:<servlet-name>和<servlet-class>,分别⽤于设置Servlet的注册名称和Servlet的完整类名。

struts2+spring+hibernate3.3增删改查的实例图文详解(II)

struts2+spring+hibernate3.3增删改查的实例图文详解(II)

S2SH的增删改查的实现第一步通过逆向工程得到实体类和Dao类实体类点击红色方框中的选项点击红色方框左边的展开标识右键单击TABLE下的datas点击红色方框中选项点击Browse选择项目和创建实体类被放的包,并选中相应的选项,点击Next点击Next点击FinishDao类点击红色方框中的选项点击红色方框左边的展开标识右键单击TABLE下的datas点击红色方框中选项包名改成com.beijing.dao,选择相应选项,点击Next点击Next点击Finish选中dao,用快捷键Ctrl+Shift+O导入实体类的包第二步在applicationContext.xml中添加数据源节点左键连击点击Source右键单击选中红色方框的选项,添加数据源点击FinishapplicationContext.xml代码如下<?xml version="1.0"encoding="UTF-8"?> <beansxmlns="/schema/beans"xmlns:xsi="/2001/XMLSchema-instance"xmlns:p="/schema/p"xsi:schemaLocation="/schema/beans /schema/beans/spring-beans-3.0.xsd"><bean id="dataSource"class="mons.dbcp.BasicDataSource"><property name="driverClassName"value="com.microsoft.sqlserver.jdbc.SQLServerDriver"> </property><property name="url"value="jdbc:sqlserver://localhost:1433"></property><property name="username" value="sa"></property> </bean><bean id="sessionFactory"class="org.springframework.orm.hibernate3.LocalSessionFactoryBean "><property name="dataSource" ref="dataSource"></property><property name="configLocation"value="classpath:hibernate.cfg.xml"></property></bean><bean id="DatasDAO"class="com.beijing.dao.DatasDAO"><property name="sessionFactory"><ref bean="sessionFactory"/></property></bean></beans>第三步用hibernate提供的方法进行增删改查注意:将dao方法里的一些不用的方法删除留下的方法如下:package com.beijing.dao;import java.util.List;import org.hibernate.HibernateException;import org.hibernate.LockMode;import org.hibernate.Query;import org.hibernate.Session;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.context.ApplicationContext;import org.springframework.dao.DataAccessResourceFailureException; importorg.springframework.orm.hibernate3.support.HibernateDaoSupport; import org.springframework.stereotype.Repository;import com.beijing.pojo.Datas;public class DatasDAO extends HibernateDaoSupport {private static final Logger log= LoggerFactory.getLogger(DatasDAO.class);//保存的方法public void save(Datas transientInstance) {log.debug("saving Datas instance");try {getHibernateTemplate().save(transientInstance);log.debug("save successful");} catch (RuntimeException re) {log.error("save failed", re);throw re;}}//删除的方法public void delete(Datas persistentInstance) {log.debug("deleting Datas instance");try {getHibernateTemplate().delete(persistentInstance);log.debug("delete successful");} catch (RuntimeException re) {log.error("delete failed", re);throw re;}}//根据实体的主键Id得到实体的方法public Datas findById(ng.Integer id) {log.debug("getting Datas instance with id: " + id);try {Datas instance = (Datas) getHibernateTemplate().get("com.beijing.pojo.Datas", id);return instance;} catch (RuntimeException re) {log.error("get failed", re);throw re;}}//数据全查的方法,不含分页public List findAll() {log.debug("finding all Datas instances");try {String queryString = "from Datas";return getHibernateTemplate().find(queryString);} catch (RuntimeException re) {log.error("find all failed", re);throw re;}}//数据全查的方法,含分页public List findAll(int pageSize, int pageNow) { log.debug("finding all Datas instances");Session session = null;try {String queryString = "from Datas";session = this.getSession();Query query = session.createQuery(queryString);int firstResultIndex = pageSize * (pageNow - 1);query.setFirstResult(firstResultIndex);query.setMaxResults(pageSize);List list = query.list();return list;} catch (RuntimeException re) {log.error("find all failed", re);throw re;} finally {//记得session要关闭,不然导致浏览器加载数据缓慢session.close();}}//修改的方法有两个调用任何都行,区别是第一个返回一个实体,第二个不返回//修改的方法1public Datas merge(Datas detachedInstance) {log.debug("merging Datas instance");try {Datas result = (Datas) getHibernateTemplate().merge(detachedInstance);log.debug("merge successful");return result;} catch (RuntimeException re) {log.error("merge failed", re);throw re;}}//修改的方法2public void update(Datas detachedInstance) {log.debug("merging Datas instance");try {super.getHibernateTemplate().update(detachedInstance);log.debug("merge successful");} catch (RuntimeException re) {log.error("merge failed", re);throw re;}}//得到总共多少条数据的方法public int getCount() {System.out.println("pageCount");Session session = null;int count = 0;try {String queryString = "select count(*) from Datas";session = this.getSession();Query query = session.createQuery(queryString);count = Integer.valueOf(query.uniqueResult().toString());} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();} finally {//记得session要关闭,不然导致浏览器加载数据缓慢session.close();}return count;}//每pageSize个数据,有几页数据public int getPageCount(int count,int pageSize) { int pageCount = count/pageSize;if(count%pageSize > 0) {pageCount++;}return pageCount;}}第四步做一个biz包,也叫业务包,和biz的接口1 bizpackage ;import java.util.List;import javax.annotation.Resource;import org.springframework.stereotype.Service;import com.beijing.dao.DatasDAO;import com.beijing.pojo.Datas;public class DataBiz implements IDataBiz {private DatasDAO datasDao;//set了datasDao是用来spring注入管理的public void setDatasDao(DatasDAO datasDao) {this.datasDao = datasDao;}//下面也是调用dao增删改查的一些方法public void delete(Datas data) {datasDao.delete(data);}public List find() {return datasDao.findAll();}public void save(Datas d) {datasDao.save(d);}public void update(Datas data) {datasDao.merge(data);}public List find(int pageSize, int nowPage) {return datasDao.findAll(pageSize, nowPage);}public int getCount() {return datasDao.getCount();}public int getPageCount(int count,int pageSize) { // TODO Auto-generated method stubreturn datasDao.getPageCount(count,pageSize);}public Datas findById(int id) {// TODO Auto-generated method stubreturn datasDao.findById(id);}}2 IBizpackage ;import java.util.List;import com.beijing.pojo.Datas;public interface IDataBiz {//action调用的是这个接口public void save(Datas d);public void delete(Datas daId);public void update(Datas data);public Datas findById(int id);public List find();public int getCount();public List find(int pageSize, int nowPage);public int getPageCount(int count,int pageSize);}第五步做一个action写入调用biz增删改查的方法代码如下:package com.beijing.ac;import java.util.Iterator;import java.util.List;import javax.annotation.Resource;import org.springframework.stereotype.Service;import .IDataBiz;import com.beijing.pojo.Datas;import com.opensymphony.xwork2.ActionSupport;public class DataAction extends ActionSupport { //biz接口的声明,用来调用bizIDataBiz idata;//这些对象set和get后,都会被hibernate自动放进request里private Integer daId;private String daName;private String daAge;private List<Datas> datas;private Datas data;private int nowPage = 1;private int pageSize = 5;private int pageCount;private int count;public int getCount() {return count;}public void setCount(int count) {this.count = count;}public int getNowPage() {return nowPage;}public void setNowPage(int nowPage) { this.nowPage = nowPage;}public int getPageSize() {return pageSize;}public void setPageSize(int pageSize) { this.pageSize = pageSize;}public int getPageCount() {return pageCount;}public void setPageCount(int pageCount) { this.pageCount = pageCount;}public List<Datas> getDatas() {return datas;}public void setDatas(List<Datas> datas) { this.datas = datas;}public IDataBiz getIdata() {return idata;}public Integer getDaId() {return daId;}public void setDaId(Integer daId) { this.daId = daId;}public String getDaName() {return daName;}public void setDaName(String daName) { this.daName = daName;}public String getDaAge() {return daAge;}public void setDaAge(String daAge) { this.daAge = daAge;}public void setIdata(IDataBiz idata) { this.idata = idata;}public String save(){System.out.println("save");data = new Datas();data.setDaAge(daAge);data.setDaName(daName);idata.save(data);System.out.println("保存成功");return"save";}public String delete(){System.out.println("delete");System.out.println(daId);data = new Datas(daId);idata.delete(data);return"delete";}public String update(){System.out.println("update");data = new Datas(daId,daName, daAge);idata.update(data);return"update";}public String findById(){System.out.println("findById");data= idata.findById(daId);daAge = data.getDaAge();daName = data.getDaName();daId = data.getDaId();return"findById";}public String find(){System.out.println("find");System.out.println(idata);datas = idata.find(pageSize,nowPage);count = idata.getCount();pageCount = idata.getPageCount(count,pageSize);for (Datas data : datas) {System.out.println(data.getDaAge() + " "+ data.getDaName());}return"find";}}第六步在applicationContext.xml添加biz和action的节点,进入注入代码如下:<?xml version="1.0"encoding="UTF-8"?><beansxmlns="/schema/beans"xmlns:xsi="/2001/XMLSchema-instance"xmlns:p="/schema/p"xsi:schemaLocation="/schema/bean s/schema/beans/spring-beans-3.0.xsd" ><bean id="dataSource"class="mons.dbcp.BasicDataSource"><property name="driverClassName"value="com.microsoft.sqlserver.jdbc.SQLServerDriver"> </property><property name="url" value="jdbc:sqlserver://localhost:1433"></property><property name="username"value="sa"></property> </bean><bean id="sessionFactory"class="org.springframework.orm.hibernate3.LocalSessionFactoryB ean"><property name="dataSource"ref="dataSource"></property><property name="configLocation"value="classpath:hibernate.cfg.xml"></property></bean><bean id="datasDao" class="com.beijing.dao.DatasDAO"> <property name="sessionFactory"><ref bean="sessionFactory" /></property></bean><bean id="idata" class=".DataBiz"><property name="datasDao" ref="datasDao"></property> </bean><bean id="data" class="com.beijing.ac.DataAction"><property name="idata" ref="idata"></property> </bean></beans>第七步在struts.xml中添加action节点代码如下:<?xml version="1.0"encoding="UTF-8"?><!DOCTYPE struts PUBLIC"-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "/dtds/struts-2.1.dtd"><struts><package name="test"extends="struts-default"><action name="data"class="com.beijing.ac.DataAction"><resultname="update"type="redirectAction">/Data_find.action</result> <resultname="findById">/update.jsp</result></action><action name="*_*"class="com.beijing.ac.{1}Action" method="{2}"><resultname="save"type="redirectAction">/Data_find.action</result> <resultname="delete"type="redirectAction">/Data_find.action</result> <resultname="find">/{2}.jsp</result></action></package></struts>注意:之所以用两个action,是想用不同的方法实现action的方法调用第八步find.jsp, ind ex.jsp, save.jsp, update.jsp的实现1 find.jsp代码如下:<%@page language="java"import="java.util.*"contentType="text/html; charset=gbk"%><%@taglib prefix="c"uri="/jsp/jstl/core"%> <%@taglib prefix="s"uri="/struts-tags"%><!DOCTYPE HTML PUBLIC"-//W3C//DTD HTML 4.01 Transitional//EN"><html><head><title>My JSP 'index.jsp' starting page</title><!--<link rel="stylesheet" type="text/css" href="styles.css">--></head><body>================================================<br>全查数据<table align="center"width="80%"><tr><th>年龄</th><th>姓名</th><th>编号</th><th>操作</th></tr><s:iterator value="datas"><tr onmouseover="this.bgColor='green'" onmouseout="this.bgColor='white'" align="center"><td><s:property value="daAge"/></td><td><s:property value="daName"/></td><td><s:property value="daId"/></td><td><ahref="${pageContext.request.contextPath}/Data_delete.action?daId= ${daId}">删除</a></td><td><a href="data!findById.action?daId=${daId}">修改</a></td></tr></s:iterator><tr></tr><tr align="center"><td>共<s:property value="pageCount"/>页</td><td><s:if test="%{nowPage==1}">首页&nbsp;上一页</s:if><s:else><ahref="${pageContext.request.contextPath}/Data_find.action?nowPage=1">首页</a>&nbsp;<ahref="${pageContext.request.contextPath}/Data_find.action?nowPage=${nowPage-1}">上一页</a>&nbsp;</s:else><s:if test="%{nowPage != pageCount}"><ahref="${pageContext.request.contextPath}/Data_find.action?nowPage=${nowPage+1}">下一页</a>&nbsp;<ahref="${pageContext.request.contextPath}/Data_find.action?nowPage=${pageCount}">末页</a>&nbsp;</s:if><s:else>下一页&nbsp;末页</s:else></td><td><ahref="${pageContext.request.contextPath}/save.jsp">新增</a></td> </tr></table></body></html>2 index.jsp 代码入戏<%@page language="java"import="java.util.*"contentType="text/html; charset=gbk"%><!DOCTYPE HTML PUBLIC"-//W3C//DTD HTML 4.01 Transitional//EN"><html><head><title>My JSP 'index.jsp' starting page</title><!--<link rel="stylesheet" type="text/css" href="styles.css">--></head><script type="text/javascript">function indexFind(){document.location="${pageContext.request.contextPath}/Data_fin d.action";}</script><body onload="indexFind()">================================================<br>struts2+spring+hibernate的增删改查</body></html>3 save.jsp 代码如下<%@page language="java"import="java.util.*"contentType="text/html; charset=gbk"%><!DOCTYPE HTML PUBLIC"-//W3C//DTD HTML 4.01 Transitional//EN"><html><head><title>My JSP 'index.jsp' starting page</title><!--<link rel="stylesheet" type="text/css" href="styles.css">--></head><body>================================================<br> <div align="center"><form action="Data_save">姓名<input name="daName"type="text"><br>年龄<input name="daAge"type="text"><br>编号<input name="daId"type="text" readonly="readonly"><br><input type="submit"value="提交"></form></div></body></html>4 update.jsp 代码如下<%@page language="java"import="java.util.*"contentType="text/html; charset=gbk"%><%@taglib prefix="s"uri="/struts-tags"%><!DOCTYPE HTML PUBLIC"-//W3C//DTD HTML 4.01 Transitional//EN"><html><head><title>My JSP 'index.jsp' starting page</title><!--<link rel="stylesheet" type="text/css" href="styles.css">--></head><body>================================================<br><div align="center"><form action="Data_save">姓名<input value="${daName}"type="text"><br>年龄<input value="${daAge}"type="text"><br>编号<input value="${daId}"type="text" readonly="readonly"><br><input type="submit"value="提交"></form><s:form action="data!update.action"><s:textfield label="姓名"name="daName"/><br><s:textfield label="年龄"name="daAge"/><br><s:textfield label="编号"name="daId" readonly="true"/><br><s:submit value="提交"></s:submit></s:form></body></html>第九步启动tomcat如下图所示。

Servlet实现增删改查功能

Servlet实现增删改查功能

MVC模式M:Model,即模型,对于JavaBeanV:View,即试图,对应JSP页面C:Controller,即控制器,对应Servlet1.以下为MVC实现一个简单的增删改查功能1>显示记录2>增加一条记录3>修改一条记录4>删除一条记录程序源代码:M层:模型层1.封装一条信息的所有属性JavaBean.java ,即VO package muta.bean;/*** @author help*封装一条信息的所有属性*/public class JavaBean {private int id;private String name;private String password;private String sex;private int age;public int getId() {return id;}public void setId(int id) {this.id = id;}public String getName() {return name;}public void setName(String name) { = name;}public String getPassword() {return password;}public void setPassword(String password) { this.password = password;}public String getSex() {return sex;}public void setSex(String sex) {/*** @author help*操作数据库的方法*/public class SqlBean {Connection con;PreparedStatement pre;ResultSet rs;public SqlBean(){try {Class.forName("com.mysql.jdbc.Driver");} catch (ClassNotFoundException e) {e.printStackTrace();}try {con=DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/MyServl et","root","122828");} catch (SQLException e) {e.printStackTrace();}}/*** @author help**插入新的一条记录* @return*/public int getInsert(String sql,JavaBean jBean) {int count =0;try {pre = con.prepareStatement(sql);pre.setString(1,jBean.getName());pre.setString(2,jBean.getPassword());pre.setString(3,jBean.getSex());pre.setInt(4,jBean.getAge());count=pre.executeUpdate();} catch (SQLException e) {e.printStackTrace();}finally{try {pre.close();con.close();} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();}}return count;}/*** @author help**删除一条记录* @return*/public int getDelete(String sql,int id){int count =0;try {pre = con.prepareStatement(sql);pre.setInt(1, id);count=pre.executeUpdate();} catch (SQLException e) {e.printStackTrace();}finally{try {pre.close();con.close();} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();}}return count;}/*** @author help**根据ID查询某一条记录* @return*/public JavaBean getSearchById(String sql,int id){JavaBean jBean = new JavaBean();try {pre = con.prepareStatement(sql);pre.setInt(1, id);rs=pre.executeQuery();while(rs.next()){jBean.setId(rs.getInt("id"));jBean.setName(rs.getString("name"));jBean.setPassword(rs.getString("password"));jBean.setSex(rs.getString("sex"));jBean.setAge(rs.getInt("age"));}} catch (SQLException e){e.printStackTrace();}return jBean;}/*** @author help**更新某一条记录* @return*/public int getUpdate(String sql,JavaBean jBean) {int count =0;try {pre = con.prepareStatement(sql);pre.setInt(5,jBean.getId());pre.setString(1,jBean.getName());pre.setString(2,jBean.getPassword());pre.setString(3,jBean.getSex());pre.setInt(4,jBean.getAge());count = pre.executeUpdate();} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();}finally{try {pre.close();con.close();} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();}}return count;}jBean.setAge(rs.getInt("age"));list.add(jBean);}} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();}finally{try {pre.close();con.close();} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();}}return list;}}V层:试图层1.显示记录集的页面 SearchList.jsp<%@page language="java"import="java.util.*" pageEncoding="UTF-8"%><%String path = request.getContextPath();String basePath =request.getScheme()+"://"+request.getServerName() +":"+request.getServerPort()+path+"/";%><!DOCTYPE HTML PUBLIC"-//W3C//DTD HTML 4.01 Transitional//EN"><html><head><meta http-equiv="Content-Type"content="text/html; charset=UTF-8"><title>显示记录</title></head><body><center><font color=red size=72>学生信息如下:</font><hr><table border=1bgColor="#ffffff"width="500px" height="100px"><tr><td>ID</td><td>姓名</td><td>密码</td><td>性别</td><td>年龄</td><td><center>操作</center></td></tr><jsp:useBean id="sBean"class="muta.bean.SqlBean"/> <jsp:useBean id="jBean"class="muta.bean.JavaBean"/><%String sql ="select * from student order by id";java.util.List list =sBean.getSearch(sql);for(java.util.Iterator it=list.iterator();it.hasNext();){//获取一个JavaBean对象jBean =(muta.bean.JavaBean)it.next();%><tr><td><%=jBean.getId() %></td><td><%=jBean.getName() %></td><td><%=jBean.getPassword() %></td><td><%=jBean.getSex() %></td><td><%=jBean.getAge() %></td><td><a href="Insert.jsp">增加</a><a href="Delete?id=<%=jBean.getId()%>">删除</a>&nbsp;<ahref="SearchById?id=<%=jBean.getId()%>">更新</a> </td></tr><% }%></table>2.插入页面Insert.jsp<center><font color=red size=72>学生管理页面</font><hr><form action="Insert"method="post"><table border="1"><tr><td>姓名:</td><td><input name ="name"></td></tr><tr><td>密码:</td><td><input type="password"name ="password"></td> </tr><tr><td>性别:</td><td><input type="radio"name ="sex"value="男">男<input type="radio"name ="sex"value="女">女</td><tr><td>年龄:</td><td><input type="text"name ="age"></td> </tr><tr><td colspan="2"><center><input type="submit"value="提交"><input type="reset"value="重置"></center></td></tr></table></form><a href="SearchList.jsp">查询</a></center></body></html>3.更新页面Update.jsp<%@page language="java"import="java.util.*" pageEncoding="UTF-8"%><%String path = request.getContextPath();String basePath =request.getScheme()+"://"+request.getServerName() +":"+request.getServerPort()+path+"/";%><!DOCTYPE HTML PUBLIC"-//W3C//DTD HTML 4.01 Transitional//EN"><html><head><meta http-equiv="Content-Type"content="text/html; charset=UTF-8"><title>更新</title></head><body><center><font color=red size=72>学生管理页面</font><hr><form action="Update"method="post""><table border="1"><tr><td>学生ID:</td><td><input name="id"value="<%=request.getAttribute("id") %>" readonly></td></tr><tr><td>学生姓名:</td><td><input name="name"value="<%=request.getAttribute("name") %>"></td> </tr><tr><td>学生密码:</td><td><input type="password"name="password"value="<%=request.getAttribute("password") %>"> </td></tr><tr><td>学生性别:</td><td><input type="radio"name ="sex"value="男"<%=request.getAttribute("man") %>>男<input type="radio"name ="sex"value="女"<%=request.getAttribute("woman") %>>女</td></tr><tr><td>学生年龄:</td><td><input type="text"name="age"value="<%=request.getAttribute("age") %>"></td> </tr><tr><td colspan="2"><center><input type="submit"value="提交"><input type="reset"value="重置"></center>4.出错页面Error.jspC层:控制层—Servlet1.显示记录集的Servlet----SearchById.javapackage muta.servlet;import java.io.IOException;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import muta.bean.JavaBean;import muta.bean.SqlBean;public class SearchById extends HttpServlet {private static final long serialVersionUID = 1L;/*** The doDelete method of the servlet. <br>** This method is called when a HTTP delete request is received.** @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 doDelete(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {// 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, HttpServletResponseresponse)throws ServletException, IOException {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 {response.setContentType("text/html");request.setCharacterEncoding("utf-8"); response.setCharacterEncoding("utf-8");//获取用户IDString sid = request.getParameter("id");int id =Integer.parseInt(sid);String sql ="select * from student where id=?"; SqlBean sBean = new SqlBean();JavaBean jBean = sBean.getSearchById(sql, id);//用户IDrequest.setAttribute("id",jBean.getId());//用户姓名request.setAttribute("name",jBean.getName());//用户密码request.setAttribute("password",jBean.getPassword());//用户性别String sex="";String man="";String woman="";if(jBean.getSex()!=null){sex=jBean.getSex().trim();if(sex.equals("男")){man ="checked";}else{woman ="checked";}}request.setAttribute("man",man);request.setAttribute("woman",woman);//用户年龄request.setAttribute("age",jBean.getAge());//转发request.getRequestDispatcher("Update.jsp").forward(request,2.增加记录的Servlet----Insert.javaprivate static final long serialVersionUID = 1L;/*** The doDelete method of the servlet. <br>** This method is called when a HTTP delete request is received.** @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 doDelete(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {// 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 {response.setContentType("text/html");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 {response.setContentType("text/html");request.setCharacterEncoding("utf-8");response.setCharacterEncoding("utf-8");//获取前台页面数据String name =request.getParameter("name");String password =request.getParameter("password");String sex =request.getParameter("sex");String sage = request.getParameter("age");int age =Integer.parseInt(sage);//封装到JavaBean对象中去JavaBean jBean = new JavaBean();jBean.setName(name);jBean.setPassword(password);jBean.setSex(sex);jBean.setAge(age);//调用模型层String sql = "insert into student(name,password,sex,age) values(?,?,?,?)";SqlBean sBean = new SqlBean();int count =sBean.getInsert(sql,jBean);String url="";if(count>0){url="SearchList.jsp";}else{url ="error.jsp";request.setAttribute("error", "ע��");}//转发ת3.更新记录的Servlet----Updated.java/****/private static final long serialVersionUID = 1L;/*** The doDelete method of the servlet. <br>** This method is called when a HTTP delete request is received.** @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 doDelete(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {// 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 {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 {response.setContentType("text/html");request.setCharacterEncoding("utf-8");response.setCharacterEncoding("utf-8");//获得前台表单信息String sid = request.getParameter("id");int id =Integer.parseInt(sid);String name =request.getParameter("name");String password =request.getParameter("password");String sex =request.getParameter("sex");String sage = request.getParameter("age");int age =Integer.parseInt(sage);//封装到JavaBean对象中去JavaBean jBean = new JavaBean();jBean.setId(id);jBean.setName(name);jBean.setPassword(password);jBean.setSex(sex);jBean.setAge(age);String sql ="update student set name=?,password=?,sex=?,age=? where id=?";SqlBean sBean = new SqlBean();int count =sBean.getUpdate(sql,jBean);String url="";if(count>0){url="SearchList.jsp";}4.删除记录的Servlet----Delete.javaimport muta.bean.SqlBean;public class Delete extends HttpServlet {private static final long serialVersionUID = 1L;/*** The doDelete method of the servlet. <br>** This method is called when a HTTP delete request is received.** @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 doDelete(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {// 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 {response.setContentType("text/html");doPost(request,response);}/*** The doPost method of the servlet. <br>** This method is called when a form has its tag value method equals topost.** @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 {response.setContentType("text/html");//获取超链接传来的数据String sId = request.getParameter("id");int id =Integer.parseInt(sId);////调用模型层删除方法String sql = "delete from student where id=?";SqlBean sBean = new SqlBean();int count =sBean.getDelete(sql, id);XML文件xsi:schemaLocation="/xml/ns /javaee/xml/ns/javaee/web-app_2_5. xsd"><servlet><servlet-name>Update</servlet-name><servlet-class>muta.servlet.Update</servlet-class ></servlet><servlet><servlet-name>SearchById</servlet-name><servlet-class>muta.servlet.SearchById</servlet-c lass></servlet><servlet><servlet-name>Insert</servlet-name><servlet-class>muta.servlet.Insert</servlet-class ></servlet><servlet><servlet-name>Delete</servlet-name><servlet-class>muta.servlet.Delete</servlet-class ></servlet><servlet-mapping><servlet-name>Update</servlet-name><url-pattern>/Update</url-pattern></servlet-mapping><servlet-mapping><servlet-name>SearchById</servlet-name><url-pattern>/SearchById</url-pattern></servlet-mapping><servlet-mapping><servlet-name>Insert</servlet-name><url-pattern>/Insert</url-pattern></servlet-mapping>。

图书管理系统 增删查改 jspservlet基础项目BaseDao

图书管理系统 增删查改 jspservlet基础项目BaseDao

图书管理系统增删查改jspservlet基础项目BaseDao这是图书管理系统的课后作业增删查改 BaseDaojsp提交到servletBaseDao.java 数据库操作通用类package combook.dao;import java.sql.*;import com.dao.util.ConfigManager;import common.*;public class BaseDao {//数据库操作通用类protected Connection conn;/**定义静态变量接收加载驱动*/private static String driver;/**定义静态变量得到连接*/private static String url;private static String userName;//数据库用户名private static String password;//数据库密码//静态的Connection 对象static{driver=ConfigManager.getInstance().getS tring("driver");url=ConfigManager.getInstance().getStri ng("url");userName=ConfigManager.getInstance().ge tString("userName");password=ConfigManager.getInstance().ge tString("password");}protected ResultSet rs;protected Statement stmt;protected PreparedStatement ps;//获取链接的方法public boolean getConnection(){if(conn!=null){//判断连接对象是否为空return false;}try {Class.forName(driver);//加载驱动//根据url,用户名和密码获取链接获取的是connection对象conn=DriverManager.getConnection(url,us erName,password);} catch (ClassNotFoundException e) {e.printStackTrace();} catch (SQLException e) {e.printStackTrace();}return true;}//增删改的方法子类可以调用这个方法帮助执行sql语句public int execute(Stringsql,Object[]params){try {ps=conn.prepareStatement(sql);//预编译传过来的sql语句if(params!=null){//如果子类传过来的参数不为空的话遍历循环判断使参数兼容for (int i = 0; i < params.length; i++) {//遍历参数数组Object obj=params[i];//参数是Object类型的所以Object先接收然后判断if(obj instanceof String){ps.setString((i+1), (String)obj);//如果该参数是String类型的就强转设置数组的的该位置元素是String类型} else if(obj instanceof Integer){ps.setInt((i+1),(Integer)obj);}else if(obj==null){//这样判断一下因为有图片传入判断不了类型obj="";//赋值为空ps.setString((i+1), (String)obj);//默认设置为String类型}}}//执行sqlint count=ps.executeUpdate();return count;} catch (SQLException e) {e.printStackTrace();return 0;}}//获取结果集的方法public ResultSet excuteSql(String sql,Object[]params){try {rs=ps.executeQuery(sql);for (int i = 0; i < params.length; i++){if(params[i] instanceof String){ps.setString((i+1),(String)params[i]);}else if(params[i] instanceof Integer){ps.setInt((i+1),(Integer)params[i]);}}} catch (SQLException e) {e.printStackTrace();}return rs;}public boolean closeResource(){if(rs!=null){try {rs.close();} catch (SQLException e) {e.printStackTrace();return false;}}if(ps!=null){try {ps.close();} catch (SQLException e) {e.printStackTrace();return false;}}if(conn!=null){try {conn.close();conn=null;} catch (SQLException e) {e.printStackTrace();return false;}}return true;}//方法重载如果需要关闭几个资源就选择哪个方法public void closeResource(Connection conn){if(conn==null){try {conn.close();} catch (SQLException e) {e.printStackTrace();}}}}Dao层接口 --BookDao.javapackage combook.dao;import java.util.List;import combook.dto.Book;import common.dto.PageDto;public interface BookDao {public List<Book> getBooksList(PageDto pagedto)throws Exception;//获得图书集合的方法--所有信息//增加一本图书信息public int insertBooks(Book book)throws Exception;//根据图书编号删除新闻public int delete(int bid)throws Exception;//修改信息 --传入的是图书对象public int update(Book book)throws Exception;//根据图书编号查找该图书//根据图书编号查找该图书public Book query(int bid) throws Exception;public List<Book> query(String bookname) throws Exception;//获得总记录的方法public int getAllRowCount() throws Exception;}BookImpl.java 实现类实现了接口继承了BaseDao.java package combook.dao.impl;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.Statement;import java.util.ArrayList;import java.util.List;import combook.dao.BaseDao;import combook.dao.BookDao;import combook.dto.Book;import common.dto.PageDto;public class BookImpl extends BaseDao implements BookDao{//1、查询所有信息返回一个带有泛型的集合public List<Book> getNewsList() throws Exception {//定义一个集合集合是对应的要返回出去的泛型集合List<Book> bookList=new ArrayList<Book>();super.getConnection();//获得连接通过父类的方法conn.prepareStatement("select * from news");rs=ps.executeQuery();//返回结果集while(rs.next()){//循环结果集中的数据判断结果集中是否还有下一个内容Book book=new Book();//创建一个实例对象//把结果集中的图书信息封装到图书对象中去book.setBid(rs.getInt("bid"));book.setBookName(rs.getString("bookName "));book.setImage(rs.getString("image"));book.setPrice(Double.parseDouble(rs.get String("b_price")));book.setStock(rs.getInt("stock"));//将图书对象添加到集合中去因为集合是带有图书泛型所以不需要强转直接添加图书对象bookList.add(book);}//调用父类方法释放资源super.closeResource();return bookList;}//获得数据库中所有的图书信息public List<Book> getBooksList(PageDto pagedto) throws Exception {//新建一个带有book泛型的集合List<Book> bookList=new ArrayList<Book>();super.getConnection();//第一步获得与数据库的连接int start=pagedto.getStartIndex();//分页查询开始int end =pagedto.getEndIndex();//分页查询结束//写分页查询的sql语句String sql="select * from (select b.*,rownum rn from books b) where rn>=? and rn<?";ps=conn.prepareStatement(sql);//预编译sql语句ps.setInt(1,start);//设置第一个参数的值ps.setInt(2,end);//设置第二个参数的值//执行查询语句rs=ps.executeQuery();//循环结果集的数据while(rs.next()){//实例化一个图书的对象Book book =new Book();//把结果集中的图书信息封装到图书对象中去book.setBid(rs.getInt("bid"));book.setBookName(rs.getString("bookName "));book.setImage(rs.getString("image"));book.setPrice(Double.parseDouble(rs.get String("b_price")));book.setStock(rs.getInt("stock"));//将图书对象添加到集合中去因为集合是带有图书泛型所以不需要强转直接添加图书对象bookList.add(book);}super.closeResource();return bookList;}//向表中插入新书的方法传入的是图书对象返回影响的行数public int insertBooks(Book book) throws Exception {super.getConnection();//第一步获得与数据库的连接//新建一个参数的数组填充占位符Object params[]=new Object[5];params[0]=book.getBid();params[1]=book.getBookName();params[2]=book.getPrice();params[3]=book.getImage();params[4]=book.getStock();String sql="insert into book values(?,?,?,?,?)";//预编译sql语句ps=conn.prepareStatement(sql);//执行更新数据库的sql语句操作int count=super.execute(sql, params);super.closeResource();return count;}//删除图书的方法根据穿过来的图书idpublic int delete(int bid) throws Exception {super.getConnection();//第一步获得与数据库的连接//填充占位符Object params[]=new Object[1];params[0]=bid;String sql="delete from book where bid=?";//删除的sql语句//预编译sql语句ps=conn.prepareStatement(sql);//调用父类的执行sqlint count=super.execute(sql, params);//释放资源super.closeResource();//返回受影响的行数return count;}//修改图书的方法传入图书的对象public int update(Book book) throws Exception {super.getConnection();//第一步获得与数据库的连接//填充占位符Object params[]=new Object[4];params[0]=book.getBookName();params[1]=book.getPrice();params[2]=book.getImage();params[3]=book.getStock();String sql="update book set bookname=?,b_price=?,image=?,stock=?";ps=conn.prepareStatement(sql);int count=super.execute(sql, params);super.closeResource();return count;}public Book query(int bid) throws Exception{super.getConnection();//第一步获得与数据库的连接Book book=new Book();//填充占位符Object params[]=new Object[1];params[0]=bid;String sql="select * from books where bid=?";conn.prepareStatement(sql);rs=super.excuteSql(sql, params);if(rs.next()){//把结果集中的图书信息封装到图书对象中去book.setBid(rs.getInt("bid"));book.setBookName(rs.getString("bookName "));book.setImage(rs.getString("image"));book.setPrice(rs.getDouble("b_price"));book.setStock(rs.getInt("stock"));}super.closeResource();return book;}public List<Book> query(String bookname) throws Exception {super.getConnection();//第一步获得与数据库的连接//新建一个带有book泛型的集合List<Book> bookList=new ArrayList<Book>();//填充占位符//Object params[]=new Object[1];//params[0]=bookname;String sql="select * from books where bookname like ?";ps=conn.prepareStatement(sql);ps.setString(1, "%"+bookname+"%");//rs=super.excuteSql(sql, params);rs=ps.executeQuery();while(rs.next()){Book book=new Book();//把结果集中的图书信息封装到图书对象中去book.setBid(rs.getInt("bid"));book.setBookName(rs.getString("bookName "));book.setImage(rs.getString("image"));book.setPrice(rs.getDouble("b_price"));book.setStock(rs.getInt("stock"));bookList.add(book);}super.closeResource();return bookList;}public int getAllRowCount() throws Exception {super.getConnection();//获得连接int count=0;//查找到所有记录String sql="select count(*) frombooks";ps=conn.prepareStatement(sql);//预编译sql语句rs=ps.executeQuery();//返回一个结果集if(rs.next()){count=rs.getInt(1);//获得结果集的第一条}super.closeResource();return count;}}用户表UserInfoDao.java 接口package combook.dao;import java.util.List;import combook.dto.Book;import erInfo;import common.dto.PageDto;public interface UserInfoDao {//传入一个用户的对象判断这个对象是否在数据库中存在public int queryObject(UserInfo user) throws Exception;//根据用户名查找该数据库表中有没有重复的用用户public int query(String userName) throws Exception;//增加一个用户信息 --传入一个用户对象public int insertUserInfo(UserInfo user)throws Exception;//修改信息 --传入的是用户对象public int update(UserInfo user)throws Exception;UserInfoDaoImpl实现类package combook.dao.impl;import java.sql.SQLException;import java.util.List;import combook.dao.BaseDao;import erInfoDao;import combook.dto.Book;import erInfo;import common.dto.PageDto;public class UserInfoDaoImpl extends BaseDao implements UserInfoDao {//向用户表中添加一个新的用户信息public int insertUserInfo(UserInfo user) throws Exception {super.getConnection();//第一步获得与数据库的连接//定义数组用于填充占位符Object params[]=new Object[3];params[0]=user.getUserName();params[1]=user.getPassword();params[2]=user.getEmail();//定义一个sql语句向表中插入数据String sql="insert into userInfo values(?,?,?)";//预编译sql语句//ps=conn.prepareStatement(sql);//ps.setString(1, x)//调用父类的执行sql的操作int count=super.execute(sql, params);super.closeResource();return count;}public int update(UserInfo user) throws Exception {return 0;}//传入一个用户名判断这个用户名是否存在返回一个查找的记录public int query(String userName) throws Exception {super.getConnection();//第一步获得与数据库的连接int count=0;String sql="select count(*) from userInfo where userName=?";try {//预编译sqlps=conn.prepareStatement(sql);//用ps填充占位符ps.setString(1, userName);rs=ps.executeQuery();//执行sql返回一个结果集//找到结果集的第一条数据if(rs.next()){count=rs.getInt(1);}} catch (SQLException e1) {e1.printStackTrace();}//释放资源super.closeResource();return count;}public int queryObject(UserInfo user) throws Exception {super.getConnection();//第一步获得与数据库的连接String sql="select count(*) from userInfo where userName=? and passwords=?";//预编译sqlps=conn.prepareStatement(sql);//填充占位符ps.setString(1, user.getUserName());ps.setString(2, user.getPassword());//执行sql语句rs=ps.executeQuery();int count=0;//找到结果集的第一条数据if(rs.next()){count=rs.getInt(1);}super.closeResource();return count;}}数据库当中的表对应的实体类 DTO层package combook.dto;/***图书类**/public class Book {private int bid;//图书编号private String bookName;//图书名字private double price;//图书价格private String image;//图书图片private int stock;//库存public int getBid() {return bid;}public void setBid(int bid) {this.bid = bid;}public String getBookName() {return bookName;}public void setBookName(String bookName) { this.bookName = bookName;}public double getPrice() {return price;}public void setPrice(double price) {this.price = price;}public String getImage() {return image;}public void setImage(String image) {this.image = image;}public int getStock() {return stock;}public void setStock(int stock) {this.stock = stock;}}用户表的实体类package combook.dto;/**用户类*/public class UserInfo {private String userName;//用户名private String password;//密码private String email;//邮箱public String getUserName() {return userName;}public void setUserName(String userName) { erName = userName;}public String getPassword() {return password;}public void setPassword(String password) { this.password = password;}public String getEmail() {return email;}public void setEmail(String email) {this.email = email;}}注册的servlet的提交地址package combook.servlet;import java.io.IOException;importjava.io.UnsupportedEncodingException; import java.sql.PreparedStatement; import java.sql.SQLException;import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; importjavax.servlet.http.HttpServletRequest; importjavax.servlet.http.HttpServletResponse;import combook.dao.BaseDao;import erInfoDao;import erInfoDaoImpl; import erInfo;import erInfoService;importerInfoServiceImpl;public class RegisterServlet extends HttpServlet{/****/private static final long serialVersionUID = 1L;protected void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException{//在地址栏直接敲代码会调用doGetSystem.out.println("进入doGet方法");//调用doPost方法实现代码重用省掉代码try {doPost(request,response);} catch (Exception e) {e.printStackTrace();}}protected void doPost(HttpServletRequest request,HttpServletResponse response){System.out.println("进入doPost方法");try {//获得表单提交过来的用户名try {request.setCharacterEncoding("utf-8");} catch (UnsupportedEncodingException e1) {e1.printStackTrace();}//设置编码格式解决中文乱码response.setCharacterEncoding("utf-8");StringuserName=request.getParameter("userName") ;//实例化一个用户表数据层的实例UserInfoDao userInfo=newUserInfoDaoImpl();//调用根据传入提交过来的用户名查询获得该用户是否存在返回一个int类型intcount=userInfo.query(userName);if(count>0){//说明该用户存在-跳到错误页面-返回重新注册response.sendRedirect("./jbook/register error.jsp");}else if(count==0){//说明可以进入下一步 --把新注册的用户存到数据库中的用户表中去//实例化用户表的信息UserInfo user=new UserInfo();//封装表单提交过来的表单数据//将提交过来的表单元素值赋值给用户表对象StringuserNames=request.getParameter("userName" );Stringpassword=request.getParameter("password") ;Stringemail=request.getParameter("email");user.setUserName(userNames);user.setPassword(password);user.setEmail(email);//实例化业务逻辑层的操作将数据放到数据库中去intcounts=userInfo.insertUserInfo(user);//将用户名保存在request作用域中进入首页可以用request.setAttribute("userName", userName);response.sendRedirect("./jbook/login.js p");}} catch (Exception e) {e.printStackTrace();}}//初始化方法只会初始化一次public void init(ServletConfig config){ System.out.println("初始化注册提交servlet");}//销毁实例的方法public void destroy(){System.out.println("销毁注册提交servlet");}}登录的jsp提交到这个Servletpackage combook.servlet;import java.io.IOException;importjava.io.UnsupportedEncodingException;import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; importjavax.servlet.http.HttpServletRequest; importjavax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession;import erInfoDao;import erInfoDaoImpl; import erInfo;public class LoginServlet extends HttpServlet{/****/private static final long serialVersionUID = 1L;@Overrideprotected void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {System.out.println("登录提交进入doGet方法");doPost(request, response);}@Overrideprotected void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {System.out.println("登录提交进入doPost方法");try {//获得表单提交过来的用户名try {request.setCharacterEncoding("utf-8");} catch (UnsupportedEncodingException e1) {e1.printStackTrace();}//设置编码格式解决中文乱码response.setCharacterEncoding("utf-8");StringuserName=request.getParameter("userName") ;Stringpassword=request.getParameter("password") ;//实例化一个用户表数据层的实例UserInfoDao userInfo=new UserInfoDaoImpl();//实例化用户表的信息UserInfo user=new UserInfo();//封装表单提交过来的表单数据//将提交过来的表单元素值赋值给用户表对象user.setUserName(userName);user.setPassword(password);//调用查询该用户对象存在与否的方法intcount=userInfo.queryObject(user);if(count>0){//说明该登录用户存在是合法的用户-跳到图书首页HttpSessionsession=request.getSession();//获取会话对象session.setAttribute("userName", userName);//对象保存到session作用域response.sendRedirect("./jbook/BookIndex.jsp");}else if(count==0){//说明该登录用户并不存在response.sendRedirect("./jbook/loginerr or.jsp");}} catch (Exception e) {e.printStackTrace();}}//初始化方法只会初始化一次public void init(ServletConfig config){ System.out.println("初始化登录提交servlet");}//销毁实例的方法public void destroy(){System.out.println("销毁登录提交servlet");}}配置文件类 ConfigManager.java package combook.util;import java.io.IOException;import java.io.InputStream;import java.util.Properties;/*** 构造数据库访问的工具类用于读取配置文件* @author Administrator**/public class ConfigManager {private static ConfigManager configManager;//自身对象private static Properties properties;//读取配置文件类//在构造工具类时,进行配置文件的读取private ConfigManager(){//私有的构造方法StringconfigFile="database.properties";//定义配置文件路径properties=new Properties();//定义Properties对象//将文件读取成流的方法--加载获得资源流InputStreamin=ConfigManager.class.getClassLoader().g etResourceAsStream(configFile);try {properties.load(in);//加载流里面的数据读到配置文件中去in.close();} catch (IOException e) {e.printStackTrace();}}//因为构造方法是私有的所以通过这个方法实例化一个对象//设置实例化对象的个数public static ConfigManager getInstance(){if(configManager==null){//如果自身对象为空就实例化一个对象configManager=new ConfigManager();}return configManager;}//通过key获得对应的value 到配置流里面读取指定的数据public String getString(String key){ return properties.getProperty(key);}}database.propertiesdriver=oracle.jdbc.driver.OracleDriverurl=jdbc:oracle:thin:@localhost:1521:MyOracleuserName=liftminepassword=liftpwdregister.jsp<%@page language="java"import="java.util.*"pageEncoding="utf-8"%><%String path = request.getContextPath();String basePath =request.getScheme()+"://"+request.getServerName()+":"+request. getServerPort()+path+"/";request.setCharacterEncoding("utf-8");response.setCharacterEncoding("utf-8");%><!DOCTYPE HTML PUBLIC"-//W3C//DTD HTML 4.01 Transitional//EN"> <html><head><base href="<%=basePath%>"><title>注册页面</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"> --><style type="text/css">.right{color:#92BB22;}.wrong{color:#F80102;}#head ul{list-style:none;}#head ul li{float:left;}#head ul li a{text-decoration:none;}#mytable{margin-left:300px; margin-top:50px;}.near{margin-left:10px;}</style><script type="text/javascript">function check(){var form=document.registerform;//获得表单的对象//验证用户名var userName=erName.value;//根据表单获得用户名的值if(userName.length==0){//说明没有输入用户名wrong("userNamespan","用户名不可以为空");return;}else{right("userNamespan");}//验证密码var password=form.password.value;if(password.length==0){wrong("passwordspan","密码输入不能为空");return;}else{right("passwordspan");//调用正确输入的方法}//验证确认密码var repassword=form.repassword.value;if(repassword.length==0||repassword!=password){wrong("repasswordspan","确认密码输入不能为空或两次密码输入不一致");return;}else{right("repasswordspan");//调用正确输入的方法}//验证邮箱var email=form.email.value;//以字符开头一次到多次然后@然后又是字符一个或多个再加.字母2到3次点及以后的内容匹配1到2次例如会有var reg=/^\w+@\w+(\.[a-zA-Z]{2,3}){1,2}$/;if(email.length==0||reg.test(email)==false){wrong("emailspan","Email地址不能为空或格式填写有误");return;}else{right("emailspan");}form.submit();}//用户输入合法时的提示方法function right(id){document.getElementById(id).innerHTML="ok";document.getElementById(id).className="right";}//用户输入不合法时的提示方法function wrong(id,message){document.getElementById(id).innerHTML=message;//设置样式document.getElementById(id).className="wrong";}</script></head><body><h1style="margin-left:200px;">欢迎注册北大青鸟网上书城</h1> <div id="head"><ul><li style="margin-left:200px;"><ahref="register.jsp">1.填写注册信息</a></li><li style="margin-left:500px;"><ahref="./jbook/BookIndex.jsp">2.注册成功</a></li></ul></div><form action="RegisterServlet"method="post"name="registerform"><table id="mytable"width="70%"align="center"><tr><td>用户名:</td><td><input type="text"name="userName"><spanid="userNamespan"></span></td></tr><tr><td>密码:</td><td><input type="password"name="password"><spanid="passwordspan"></span></td></tr><tr><td>确认密码:</td><td><input type="password"name="repassword"><spanid="repasswordspan"></span></td></tr><tr><td>email:</td><td class="near"><input type="text"name="email"><span id="emailspan"></span></td></tr><tr><td colspan="2"style="margin-left:800px;"><button type="button"onclick="check()">注册</button><button type="reset">重置</button></td></tr></table></form></body></html>registererror.jsp<%@page language="java"import="java.util.*"pageEncoding="utf-8"%><%String path = request.getContextPath();String basePath =request.getScheme()+"://"+request.getServerName()+":"+request. getServerPort()+path+"/";request.setCharacterEncoding("utf-8");response.setCharacterEncoding("utf-8");%><!DOCTYPE HTML PUBLIC"-//W3C//DTD HTML 4.01 Transitional//EN"> <html><head><base href="<%=basePath%>"><title>注册失败</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><img src="images/2016-07-09_181427.png"/><h1>注册失败,该用户名已经存在。

servlet增删改查

servlet增删改查

Servlet(增删改查)准备:1.新建一个web项目(StudentZSGC)2.分层,分包一.查(查询学员信息表)(1)新建一个JSP页面(通过form表单进一个servlet(StudentAction))<%@page language="java"import="java.util.*"pageEncoding="utf-8"%> <%String path = request.getContextPath();String basePath =request.getScheme()+"://"+request.getServerName()+":"+request.getServ erPort()+path+"/";%><html><head><title>查询学员表</title></head><BODY bgcolor="#FFCCCC"><form action="StudentAction"method="post"><TABLE width="100%"height="100%"><TR align="center"><TD><INPUT TYPE="submit"value="查询学员信息"></TD></TR></TABLE></form></BODY></html>(2)通过web.xml(中转站)找到对应的servlet(StudentAction)(3)进入action层package com.student.action;import java.io.IOException;import java.util.List;import java.util.Map;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import com.student.service.StudentService;public class StudentAction extends HttpServlet {/*** 查询所有人员*/private static final long serialVersionUID = 1L;@Overrideprotected void service(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {//转码req.setCharacterEncoding("utf-8");resp.setCharacterEncoding("utf-8");resp.setContentType("text/html; charset=utf-8");//调方法StudentService studentService=new StudentService();List<Map<String, Object>> list=null;list=studentService.selectAll();req.setAttribute("StudentList", list);--传回前台进行set//转向if(!list.isEmpty()){ --跳转到该页面req.getRequestDispatcher("Student.jsp").forward(req, resp);}else{req.getRequestDispatcher("Student.jsp").forward(req, resp);}}}(4)进入service类中package com.student.service;import java.util.List;import java.util.Map;import com.student.dao.StudentDao;/*** 查询所有学员信息方法* @author Administrator*/public class StudentService {public List<Map<String, Object>> selectAll() {StudentDao StudentDao=new StudentDao();return StudentDao.selectAll();}}(5)进入dao中连接数据库package com.student.dao;import java.util.List;/*** 查询数据库所有学员放到list中*/import java.util.Map;import com.student.util.Dao;public class StudentDao {Dao dao=new Dao();public List<Map<String, Object>> selectAll() {S tring sql="select s_id, s_number, s_name, s_sex, s_class, s_age, s_add, s_college, s_mobile, s_hobby from student";return dao.select(sql,new Object[]{});}}(6)查询出数据后跳到Student.jsp页面<%@page language="java"import="java.util.*"pageEncoding="utf-8"%><%@page import="java.sql.Array"%><%String path = request.getContextPath();String basePath =request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><!DOCTYPE HTML PUBLIC"-//W3C//DTD HTML 4.01 Transitional//EN"><html><head><title>学员列表</title></head><BODY bgcolor="#FFCCCC"><form action=""method="post"><TABLE width="100%"height="100%"><TR><TD align="center"valign="top"><TABLE border="1"><TR><TD colspan="5">学号:<INPUT TYPE="text"NAME="Snumber"></TD><TD colspan="4">姓名:<INPUT TYPE="text"NAME="Sname"></TD><TD colspan="2"><INPUT TYPE="button"value="提交"></TD> </TR><TR><td><input type="checkbox"id="selAll"/></td><TD>id</TD><TD>学号</TD><TD>姓名</TD><TD>性别</TD><TD>班级</TD><TD>年龄</TD><TD>住址</TD><TD>就读院校</TD><TD>联系方式</TD><TD>爱好</TD></TR><!- 接后台容器中的元素-><%List<Map<String, Object>> list=(List<Map<String, Object>>)request.getAttribute("StudentList");for(int i=0;i<list.size();i++){Map<String, Object> map=list.get(i);%><!-前台通过map取值-><TR><td><input type="checkbox" name="selItem"value="<%=map.get("s_id")%>"/></td><TD><%=map.get("s_id")%></TD><TD><%=map.get("s_number")%></TD><TD><%=map.get("s_name")%></TD><TD><%=map.get("s_sex")%></TD><TD><%=map.get("s_class")%></TD><TD><%=map.get("s_age")%></TD><TD><%=map.get("s_add")%></TD><TD><%=map.get("s_college")%></TD><TD><%=map.get("s_mobile")%></TD><TD><%=map.get("s_hobby")%></TD></TR><%}%><TR><TD><A HREF="javascript:openW();">添加</A></TD><TD><A HREF="javascript:upPerson()">修改</A></TD><TD><A HREF="javascript:delPerson()">删除</A></TD></TR></TABLE></TD></TR></TABLE></form></BODY><script LANGUAGE="JavaScript">document.getElementById("selAll").onclick=function(){ var chItem=document.getElementsByName("selItem");for(i=0;i<chItem.length;i++){chItem[i].checked=this.checked;}}function openW(){window.showModalDialog("<%=request.getContextPath()%>/insertPe rson.jsp","","dialogwidth:380px;dialogheight:380px");}="myIndex"function upPerson(){var num = 0;var postId = "";var chItem = document.getElementsByName("selItem");for(i = 0 ; i <chItem.length;i++){if(chItem[i].checked == true){num ++;postId = chItem[i].value;}}if(num != 1){alert("请选择一条数据");}else{location.href ="upServlet?id="+postId;}}function delPerson(){var num = 0;var postId = "";var chItem = document.getElementsByName("selItem");for(i = 0 ; i <chItem.length;i++){if(chItem[i].checked == true){num ++;postId = chItem[i].value;}}if(num <1){alert("请至少选择一条数据");}else{document.forms[0].action="delServlet";document.forms[0].submit();}}</script></html>如下示例:二.增(添加学员)(1)在学员列表页面的添加按钮写一个方法调用函数function openW(){window.showModalDialog("<%=request.getContextPath()%>/insertPerso n.jsp","","dialogwidth:380px;dialogheight:380px");}="myIndex"知识点:1.点击添加跳转该添加页面insertPerson.jsp2. 当表单将要被提交时触发(onsubmit)="javascript:window.close()提交后立即关闭该窗体3.设置或获取目标内容要显示于哪个窗口或框架(target)="myIndex"(2)添加页面单机添加通过form 走servlet( AddPersonAction)<%@page language="java"import="java.util.*"pageEncoding="utf-8"%> <%String path = request.getContextPath();String basePath =request.getScheme()+"://"+request.getServerName()+":"+request.getServ erPort()+path+"/";%><html><head><title>添加页面</title></head><BODY bgcolor="#FFCCCC"><form method="get"action="<%=request.getContextPath()%>/AddPersonAction"target="myIndex" onsubmit="javascript:window.close()"><TABLE width="343"height="139"><TR><TD>学&nbsp;&nbsp;&nbsp;&nbsp;号:</TD><TD><INPUT TYPE="text"NAME="snumber"></TD><TD>*只能输入中文</TD></TR><TR><TD>姓&nbsp;&nbsp;&nbsp;&nbsp;名:</TD><TD><INPUT TYPE="text"NAME="sname"></TD><TD>*只能输入中文</TD></TR><TR><TD>性&nbsp;&nbsp;&nbsp;&nbsp;别:</TD><TD><INPUT TYPE="text"NAME="ssex"></TD><TD>*只能输入英文</TD></TR><TR><TD>班&nbsp;&nbsp;&nbsp;&nbsp;级:</TD><TD><INPUT TYPE="text"NAME="sclass"></TD><TD>*只能输入中文</TD></TR><TR><TD>年&nbsp;&nbsp;&nbsp;&nbsp;龄:</TD><TD><INPUT TYPE="text" NAME="sage"></TD><TD>*只能输入中文</TD></TR><TR><TD>地&nbsp;&nbsp;&nbsp;&nbsp;址:</TD><TD><INPUT TYPE="text"NAME="sadd"></TD><TD>*只能输入中文</TD></TR><TR><TD>毕业院校:</TD><TD><INPUT TYPE="text"NAME="scollege"></TD><TD>*只能输入中文</TD></TR><TR><TD>联系方式:</TD><TD><INPUT TYPE="text"NAME="smobile"></TD><TD>*只能输入中文</TD></TR><TR><TD>爱&nbsp;&nbsp;&nbsp;&nbsp;好:</TD><TD><INPUT TYPE="text"NAME="shobby"></TD><TD>*只能输入中文</TD></TR><tr><td colspan="2"><INPUT TYPE="submit" value="添加"><INPUT TYPE="reset"value="重置"/></td></tr></TABLE></form></BODY></html>(3)找到web.xml(中转站) AddPersonAction<servlet><servlet-name>AddPersonAction</servlet-name><servlet-class>com.student.action.AddPersonAction</servlet-class> </servlet><servlet-mapping><servlet-name>AddPersonAction</servlet-name><url-pattern>/AddPersonAction</url-pattern></servlet-mapping>(4)通过com.student.action.AddPersonAction进action中package com.student.action;import java.io.IOException;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import com.student.service.AddPersonService;public class AddPersonAction extends HttpServlet {/*** 添加人员*/private static final long serialVersionUID = 1L;@Overrideprotected void service(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {//转码req.setCharacterEncoding("utf-8");resp.setCharacterEncoding("utf-8");resp.setContentType("text/html;charset=utf-8");//接值 s_id, s_number, s_name, s_sex, s_class, s_age, s_add, s_college, s_mobile, s_hobby知识点:通过添加页面中的 input中的name值接过来的String snumber=(String)req.getParameter("snumber");snumber = new String(snumber.getBytes("ISO8859-1"),"utf-8");String sname=(String)req.getParameter("sname");sname = new String(sname.getBytes("ISO8859-1"),"utf-8");String ssex=(String)req.getParameter("ssex");ssex = new String(ssex.getBytes("ISO8859-1"),"utf-8");String sclass=(String)req.getParameter("sclass");sclass = new String(sclass.getBytes("ISO8859-1"),"utf-8");String sage=(String)req.getParameter("sage");sage = new String(sage.getBytes("ISO8859-1"),"utf-8");String sadd=(String)req.getParameter("sadd");sadd = new String(sadd.getBytes("ISO8859-1"),"utf-8");String scollege=(String)req.getParameter("scollege");scollege = new String(scollege.getBytes("ISO8859-1"),"utf-8");String smobile=(String)req.getParameter("smobile");smobile = new String(smobile.getBytes("ISO8859-1"),"utf-8");String shobby=(String)req.getParameter("shobby");shobby = new String(shobby.getBytes("ISO8859-1"),"utf-8");//调方法AddPersonService addPersonService=new AddPersonService();addPersonService.addPerson(snumber,sname,ssex,sclass,sage,sadd,scolle ge,smobile,shobby);//转向req.getRequestDispatcher("StudentAction").forward(req, resp);知识点:添加完后跳到StudentAction重新查询一遍数据库}}(5)service层package com.student.service;import com.student.dao.AddPersonDao;public class AddPersonService {public boolean addPerson(String snumber, String sname, String ssex, String sclass, String sage, String sadd, String scollege,String smobile, String shobby) {AddPersonDao addPersonDao=new AddPersonDao();Object[] paras=new Object[9];paras[0]=snumber;paras[1]=sname;paras[2]=ssex;paras[3]=sclass;paras[4]=sage;paras[5]=sadd;paras[6]=scollege;paras[7]=smobile;paras[8]=shobby;return addPersonDao.addPerson(paras);}}(6)dao层package com.student.dao;import com.student.util.Dao;public class AddPersonDao {public boolean addPerson(Object[] paras) {Dao dao=new Dao();String sql="insert into student(s_id, s_number, s_name, s_sex,s_class, s_age, s_add, s_college, s_mobile, s_hobby) values(seq.nextval, ?, ?, ?, ?, ?, ?, ?, ?, ?)";int num=dao.executeDML(sql, paras);return num>0?true:false;}}三.改(修改学员信息)分析:总共分两步1.首先走一个servlet查询出要修改的用户信息2.然后再走一个servlet更新用户新输入的学员信息(1)单机修改按钮(2)调用函数uplPerson()(3)根据location连接到servlet(upServlet)知识点:location.href ="upServlet?id="+postId;将选中用户id传入后台以用查询(4)根据web.xml(中转站)找到对应的servlet(5)找到upServletActionpackage com.student.action;import java.io.IOException;import java.util.List;import java.util.Map;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import com.student.service.upServletService;public class upServletAction extends HttpServlet {/*** 修改类*/private static final long serialVersionUID = 1L;@Overrideprotected void service(HttpServletRequest req,HttpServletResponse resp)throws ServletException, IOException {//转码req.setCharacterEncoding("utf-8");resp.setCharacterEncoding("utf-8");resp.setContentType("text/html;charset=utf-8");//接值//id前台传过来的location.href ="upServlet?id="+postId;String sid=(String)req.getParameter("id");upServletService upServletService=newupServletService();List<Map<String, Object>>list=upServletService.selectStudent(sid);if(!list.isEmpty()){//方便前台取出要被修改学员的信息req.setAttribute("list", list);//下个页面接收传到要跳入的页面UpStudent.jsp页面用该方法接传过来的sidreq.setAttribute("sid", sid);req.getRequestDispatcher("UpStudent.jsp").forward(req, resp);}}}(6)根据其找到对应的service类(7)service类(8)调用upServletDao类(9)前台修改页面取值<%@page language="java"import="java.util.*"pageEncoding="utf-8"%><%String path = request.getContextPath();String basePath =request.getScheme()+"://"+request.getServerName()+":"+request.getServ erPort()+path+"/";%><html><head><title>修改页面</title></head><BODY bgcolor="#FFCCCC"><form method="get"action="<%=request.getContextPath()%>/UpStudentAction"target="myIndex"><%%><%//判断数据库中是否有该学员if(request.getAttribute("list")!=null){List<Map<String,Object>>list=(List<Map<String,Object>>)request.getAttribute("list");Map<String,Object> map=list.get(0);%><!-- 接上个页面的id(value="<%=request.getAttribute("sid")%>")下个页面通过 name="id"接收id --><input type="hidden"name="id"value="<%=request.getAttribute("sid")%>"/><TABLE width="343"height="139"><TR><TD>学&nbsp;&nbsp;&nbsp;&nbsp;号:</TD>//取后台查询出来的值(以下红线均是)<TD><INPUTTYPE="text"NAME="snumber"value="<%=map.get("s_number")%>"></TD><TD>*只能输入中文</TD></TR><TR><TD>姓&nbsp;&nbsp;&nbsp;&nbsp;名:</TD><TD><INPUT TYPE="text"NAME="sname"value="<%=map.get("s_name")%>"></TD><TD>*只能输入中文</TD></TR><TR><TD>性&nbsp;&nbsp;&nbsp;&nbsp;别:</TD><TD><INPUT TYPE="text"NAME="ssex"value="<%=map.get("s_sex")%>"></TD><TD>*只能输入英文</TD></TR><TR><TD>班&nbsp;&nbsp;&nbsp;&nbsp;级:</TD><TD><INPUT TYPE="text"NAME="sclass"value="<%=map.get("s_class")%>"></TD><TD>*只能输入中文</TD></TR><TR><TD>年&nbsp;&nbsp;&nbsp;&nbsp;龄:</TD><TD><INPUT TYPE="text"NAME="sage"value="<%=map.get("s_age")%>"></TD><TD>*只能输入中文</TD></TR><TR><TD>地&nbsp;&nbsp;&nbsp;&nbsp;址:</TD><TD><INPUT TYPE="text"NAME="sadd"value="<%=map.get("s_add")%>"></TD><TD>*只能输入中文</TD></TR><TR><TD>毕业院校:</TD><TD><INPUT TYPE="text"NAME="scollege"value="<%=map.get("s_college")%>"></TD><TD>*只能输入中文</TD></TR><TR><TD>联系方式:</TD><TD><INPUT TYPE="text"NAME="smobile"value="<%=map.get("s_mobile")%>"></TD><TD>*只能输入中文</TD></TR><TR><TD>爱&nbsp;&nbsp;&nbsp;&nbsp;好:</TD><TD><INPUT TYPE="text"NAME="shobby"value="<%=map.get("s_hobby")%>"></TD><TD>*只能输入中文</TD></TR><tr><td colspan="2"><INPUT TYPE="submit"value="修改"><INPUT TYPE="reset"value="重置"/></td></tr></TABLE><%} %></form></BODY></html>完成以上即完成第一步查询出要修改的学员信息并返回给前台页面(如图所示)选中一条数据单机修改第二步骤更新用户新输入的学员信息(10)用户对其进行修改,改完后单机修改按钮根据form表单走一个servlet(upStudentAction)(11)到web.xmlz中找到对应的servlet(12)action层package com.student.action;import java.io.IOException;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import com.student.service.UpStudentService;public class UpStudentAction extends HttpServlet {/*** 修改选中的用户信息*/private static final long serialVersionUID = 1L;@Overrideprotected void service(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {//转码req.setCharacterEncoding("utf-8");resp.setCharacterEncoding("utf-8");resp.setContentType("text/html;charset=utf-8");//接值跟据修改页面里的input里的name属性接到的String sid=(String)req.getParameter("id");String snumber=(String)req.getParameter("snumber");snumber = new String(snumber.getBytes("ISO8859-1"),"utf-8");String sname=(String)req.getParameter("sname");sname = new String(sname.getBytes("ISO8859-1"),"utf-8");String ssex=(String)req.getParameter("ssex");ssex = new String(ssex.getBytes("ISO8859-1"),"utf-8");String sclass=(String)req.getParameter("sclass");sclass = new String(sclass.getBytes("ISO8859-1"),"utf-8");String sage=(String)req.getParameter("sage");sage = new String(sage.getBytes("ISO8859-1"),"utf-8");String sadd=(String)req.getParameter("sadd");sadd = new String(sadd.getBytes("ISO8859-1"),"utf-8");String scollege=(String)req.getParameter("scollege");scollege = newString(scollege.getBytes("ISO8859-1"),"utf-8");String smobile=(String)req.getParameter("smobile");smobile = new String(smobile.getBytes("ISO8859-1"),"utf-8");String shobby=(String)req.getParameter("shobby");shobby = new String(shobby.getBytes("ISO8859-1"),"utf-8");//调方法UpStudentService upStudentService=new UpStudentService();if(upStudentService.upStudent(snumber,sname,ssex,sclass,sage,sadd,s college,smobile,shobby,sid)){// 修改后跳到(StudentAction)servlet中在重新查询遍更新后的信息 req.getRequestDispatcher("StudentAction").forward(req, resp);}}}(13)走到service层(14)走到dao层四.删(删除学员信息)(1)单机删除按钮调用delPerson()(2)调用函数走delServlet(3)通过web.xml找到对应的servlet(4)action层package com.student.action;import java.io.IOException;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import com.student.service.delServletService;/*** 删除数据* @author Administrator*/public class delServletAction extends HttpServlet { private static final long serialVersionUID = 1L;@Overridep rotected void service(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException { // 转码req.setCharacterEncoding("utf-8");resp.setCharacterEncoding("utf-8");resp.setContentType("text/html;charset=utf-8");//接值// String sid=(String)req.getParameter("id");//根据该条接收到的idString[] ids=req.getParameterValues("selItem");//掉方法delServletService delServletService=newdelServletService();if(delServletService.delStudent(ids)){req.getRequestDispatcher("StudentAction").forward(req, resp);}else{S ystem.out.println("删除失败");}}}(5)service层(6)dao层五.实现学员信息单独放在一个区域如下:将学员信息列表table外放一个div知识点:auto Content is clipped and scrolling is added only when necessary.<table>…………..</table></div>六.模糊查询1.两个参数:学号和用户名同时模糊(两个都需要like)Sql:select s_id, s_number, s_name, s_sex, s_class, s_age, s_add, s_college, s_mobile, s_hobby from student where s_number like ? and s_name like ?Dao: 将参数前后加%:如果其他地方用到select方法的将其sql语句改成like(修改时查修改用户信息时用)。

图书管理系统增删查改jspservlet基础项目BaseD

图书管理系统增删查改jspservlet基础项目BaseD

这是图书管理系统的课后作业增删查改 BaseDaojsp提交到servlet数据库操作通用类package ;import .*;import common.*;public class BaseDao {etString("driver");url=().getString("url");userName=().getString("userName");password=().getString("password");}protected ResultSet rs;protected Statement stmt;protected PreparedStatement ps;,rownum rn from books b) where rn>=? and rn<?";ps=(sql);jbook/");}else if(count==0){jbook/");}} catch (Exception e) {();}}jbook/");}else if(count==0){jbook/");}} catch (Exception e) {();}}"pageEncoding="utf-8"%><%String path = ();String basePath = ()+":ight{color:#92BB22;}.wrong{color:#F80102;}#head ul{list-style:none;}#head ul li{float:left;}#head ul li a{text-decoration:none;}#mytable{margin-left:300px; margin-top:50px;}.near{margin-left:10px;}</style><script type="text/javascript">function check(){var form=;var reg=/^\w+@\w+(\.[a-zA-Z]{2,3}){1,2}$/;if==0||(email)==false){wrong("emailspan","Email地址不能为空或格式填写有误");return;}else{right("emailspan");}();}nnerHTML="ok";(id).className="right";}nnerHTML=message;lassName="wrong";}</script></head><body><h1style="margin-left:200px;">欢迎注册北大青鸟网上书城</h1><div id="head"><ul><li style="margin-left:200px;"><a href="">1.填写注册信息</a></li><li style="margin-left:500px;"><a href="./jbook/">2.注册成功</a></li></ul></div><form action="RegisterServlet"method="post"name="registerform"><table id="mytable"width="70%"align="center"><tr><td>用户名:</td><td><input type="text"name="userName"><spanid="userNamespan"></span></td></tr><tr><td>密码:</td><td><input type="password"name="password"><spanid="passwordspan"></span></td></tr><tr><td>确认密码:</td><td><input type="password"name="repassword"><spanid="repasswordspan"></span></td></tr><tr><td>email:</td><td class="near"><input type="text"name="email"><spanid="emailspan"></span></td></tr><tr><td colspan="2"style="margin-left:800px;"><button type="button"onclick="check()">注册</button><button type="reset">重置</button></td></tr></table></form></body></html><%@page language="java"import=".*"pageEncoding="utf-8"%><%String path = ();String basePath = ()+":"pageEncoding="utf-8"%><%String path = ();String basePath = ()+":ight{color:#92BB22;}.wrong{color:#F80102;}</style><script type="text/javascript">function check(){var form=;var userName= if==0){nnerHTML="用户名不得为空";("userNamespan").className="wrong";}else{("userNamespan").innerHTML="ok";("userNamespan").className="right";}var password= if==0){nnerHTML="用户名不得为空";("passwordspan").className="wrong";}else{("passwordspan").innerHTML="ok";("passwordspan").className="right";}();"pageEncoding="utf-8"%><%String path = ();String basePath = ()+":"pageEncoding="utf-8"%><%String path = ();String basePath = ()+":alue;jbook/?pageIndex="+pageCount;}else if(pagesIndex<=1){jbook/?pageIndex="+1;}else{jbook/?pageIndex="+pagesIndex;}}function buy(){var price=0;var count=0;var money=0;var prices=("price");alue;count=counts[i].value;nnerHTML=money;}function bigPicture(img){="./jbook/?img="+img;}</script></head><body bgcolor="#96D7EB"><jsp:include page=""></jsp:include><%jbook/">首页</a><a href="./jbook/?pageIndex=<%=()%>">上一页</a><a href="./jbook/?pageIndex=<%=()%>">下一页</a><a href="./jbook/?pageIndex=<%=pageCount%>">末页</a><span><input type="text"id="gotopage"value="<%=()%>"name="gotopage" style="width:28px;"/><input type="button"value="go"onclick="gotoPage('<%=(rowCount, ())%>')"/></span></div></div></body></html><%@page language="java"import=".*"pageEncoding="utf-8"%><%String path = ();String basePath = ()+":istyle{background-color:#FFFFFF;width:25px;height:35px;}</style><script type="text/javascript">function search(){var bookName=("search").value;="./jbook/?bookName="+bookName;}</script></head><%String userName=(String)("userName");if(userName==null){jbook/"class="listyle">首页</a></li><li><a href=""class="listyle">我的订单</a></li><li><a href=""class="listyle">购物车</a></li><li><a href=""class="listyle">注销</a></li><li style="float:right;line-height:45px;margin-right:25px"><input type="text"id="search">&nbsp;<input type="button"value="搜索"onclick="search()"/> </li></ul></div></div></body></html><%@page import=""%><%@page import=""%><%@page import=""%><%@page import=""%><%@page import=""%><%@page language="java"import=".*"pageEncoding="utf-8"%><%String path = ();String basePath = ()+":o扩展名的请求匹配 --></servlet-mapping><!-- 登录servlet --><servlet><servlet-name>LoginServlet</servlet-name><servlet-class></servlet><servlet-mapping><servlet-name>LoginServlet</servlet-name><url-pattern>/LoginServlet</url-pattern><!--对所有.do扩展名的请求匹配 --> </servlet-mapping><!-- 购物车的保存 --><servlet><servlet-name> SavetoCar</servlet-name><servlet-class>. SavetoCar</servlet-class></servlet><servlet-mapping><servlet-name>SavetoCar</servlet-name><url-pattern>/SavetoCar</url-pattern><!--对所有.do扩展名的请求匹配 --> </servlet-mapping><!-- 设置session的有效时间 --><session-config><session-timeout>50</session-timeout></session-config><!-- servlet配置 --><servlet><servlet-name>NewsServlet</servlet-name><servlet-class></servlet-class></servlet><servlet-mapping><servlet-name>NewsServlet</servlet-name><url-pattern>/NewsServlet</url-pattern><!--精准匹配 --></servlet-mapping><servlet><servlet-name>updateServlet</servlet-name><servlet-class></servlet-class></servlet><servlet-mapping><servlet-name>updateServlet</servlet-name><url-pattern>/updateServlet</url-pattern><!--精准请求匹配 --></servlet-mapping><servlet><servlet-name>deleteServlet</servlet-name><servlet-class>comServlet. deleteServlet</servlet-class></servlet><servlet-mapping><servlet-name>deleteServlet</servlet-name><url-pattern>/deleteServlet</url-pattern><!--对所有.do扩展名的请求匹配 --> </servlet-mapping><!-- 配置过滤器 --><filter><display-name>CharacterEncodingFilter</display-name><filter-name>CharacterEncodingFilter</filter-name><filter-class></filter-class></filter><filter-mapping><filter-name>CharacterEncodingFilter</filter-name><url-pattern>/updateServlet</url-pattern><!-- 设置过滤器和更改的servlet进行关联 --></filter-mapping><!--监听器配置 --><listener><listener-class></listener-class></listener></web-app>。

SpringBoot实现简单的增删改查

SpringBoot实现简单的增删改查

SpringBoot实现简单的增删改查在pom.xml添加相应的依赖<dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-jdbc</artifactId></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><scope>runtime</scope></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope><exclusions><exclusion><groupId>org.junit.vintage</groupId><artifactId>junit-vintage-engine</artifactId></exclusion></exclusions></dependency><dependency><groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter</artifactId><version>2.1.3</version></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><!-- 前端使⽤thymeleaf来代替jsp --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-thymeleaf</artifactId></dependency></dependencies>配置⽂件配置数据库等#serverserver.port=80#项⽬名:server.servlet.context-path#spring dataSourcespring.datasource.url=jdbc:mysql:///dbgoods?serverTimezone=GMT%2B8&characterEncoding=utf8ername=rootspring.datasource.password=rootmybatis.mapper-locations=classpath:/mapper/*/*.xml#spring log.cy=debug#spring thymeleaf(假如没有配置也会默认配置,在默认配置中prefix默认值为classpath:/templates/,后缀默认为.html)#不⽤重启服务器,⽹页就能刷新spring.thymeleaf.cache=falsespring.thymeleaf.prefix=classpath:/templates/pages/spring.thymeleaf.suffix=.html数据层添加相应注解实现sql语句(或者通过xml配置来实现)数据层封装了商品信息,并提供get和set⽅法,为Goods类1.查询所有数据@Select("select * from tb_goods")List<Goods> findAll();2.按照id删除数据@Delete("delete from tb_goods where id=#{id}")int deleteById(Integer id);3.修改数据(1)修改数据⾸先要新建⼀个界⾯,按照id查找内容,并将查找到的内容显⽰到⽂本框内@Select("select * from tb_goods where id=#{id}")Goods findById(Integer id);(2)再添加查找的⽅法@Update("update tb_goods set name=#{name},remark=# {remark},createdTime=now() where id=#{id}")int update(Goods goods);4.新增数据@Insert("insert into tb_goods(name,remark,createdTime) values (#{name},#{remark},now())")int add(Goods goods);业务层提供对应接⼝⽅法和实现类1.业务层接⼝public interface GoodsService {List<Goods> findObject();int add(Goods goods);int update(Goods goods);Goods findById(Integer id);}2.业务层实现类@Servicepublic class GoodsServiceImpl implements GoodsService {@Autowiredprivate GoodsDao goodsDao;@Overridepublic List<Goods> findObject() {long start=System.currentTimeMillis();List<Goods> list = goodsDao.findObjects();long end=System.currentTimeMillis();System.out.println("query time:"+(end-start));return list;}@Overridepublic int add(Goods goods) {return goodsDao.add(goods);}@Overridepublic int update(Goods goods) {return goodsDao.update(goods);}@Overridepublic Goods findById(Integer id) {return goodsDao.findById(id);}控制层写具体实现1.跳转到⾸页并且查找所有商品@RequestMapping("doGoodsUI")public String doGoodsUI(Model model) {List<Goods> list = goodsService.findObject();model.addAttribute("goods",list);return "goods";}2.业务层实现类@Servicepublic class GoodsServiceImpl implements GoodsService {@Autowiredprivate GoodsDao goodsDao;@Overridepublic List<Goods> findObject() {long start=System.currentTimeMillis();List<Goods> list = goodsDao.findObjects();long end=System.currentTimeMillis();System.out.println("query time:"+(end-start));return list;}@Overridepublic int add(Goods goods) {return goodsDao.add(goods);}@Overridepublic int update(Goods goods) {return goodsDao.update(goods);}@Overridepublic Goods findById(Integer id) {return goodsDao.findById(id);}控制层写具体实现1.跳转到⾸页并且查找所有商品@RequestMapping("doGoodsUI")public String doGoodsUI(Model model) {List<Goods> list = goodsService.findObject();model.addAttribute("goods",list);return "goods";}2.删除商品@RequestMapping("doDeleteById/{id}")// (@PathVariable Integer id)告诉服务器,id拿到的是从⽹页上同样叫id的数据 public String dodeletebyId(@PathVariable Integer id){int delete = goodsDao.deleteById(id);//doGoodsUI前⾯没有加/的话,跳转的⽹址是替代了最后⼀个/后⾯的内容 return "redirect:/goods/doGoodsUI";}3.修改商品(1)先将查找出来的商品显⽰在⽂本框中@RequestMapping("doFindById/{id}")public String doFindByID(@PathVariable Integer id,Model model){Goods goods = goodsService.findById(id);model.addAttribute("goods",goods);return "goods-update";}(2)实现修改@RequestMapping("doUpdateGoods")public String doUpdateGoods(Goods goods){goodsService.update(goods);return "redirect:/goods/doGoodsUI";}4.新增商品@RequestMapping("doSaveGoods")public String doSaveGoods(Goods goods){goodsService.add(goods);return "redirect:/goods/doGoodsUI";}前端采⽤html+thymeleaf模板代替jsp2.each表⽰遍历拿到的数组,goods是从控制层拿到的model的名字3.id,name和remark与数据库对应,date要格式化拿到数据,该语法是thymeleaf固定写法<tr th:each="g:${goods}"><td th:text="${g.id}">1</td><td th:text="${}">AAAAAAA</td><td th:text="${g.remark}">aa</td><td th:text="${#dates.format(g.createdTime,'yyyy-MM-dd HH:mm')}">aa</td><!-- <td><a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" th:href="@{/goods/doDeleteById(id=${g.id})}" rel="external nofollow" ><button>删除</button></a></td>--><td><a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" th:href="@{/goods/doDeleteById/{doDeleteById}(doDeleteById=${g.id})}" rel="external nofollow" ><button>删除</button></a></td> <td><a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" th:href="@{/goods/doFindById/{id}(id=${g.id})}" rel="external nofollow" ><button>修改</button></a></td></tr>4.新增商品界⾯(1)标签⾥的name属性要和sql语句⼀致(2)这⾥由于数据库中的id列设置了⾃增长,所以不需要id属性,createdTime列使⽤了now()获取当前时间,所以也不需要传值,所以在控制层的doUpdateGoods⽅法⾥可以使⽤封装好的Goods来接收从html拿到的参数<form th:action="@{/goods/doSaveGoods}" method="post"><ul><li>name:<input type="text" name="name"></li><li>remark:<textarea rows="3" cols="20" name="remark"></textarea></li><li><input type="submit" value="Save Goods"></li></ul></form>5.修改商品界⾯(1)因为id列⾃增长,所以修改商品信息不需要id这⼀列,但传参数有需要⼀起传送过去,所以添加了⼀个输⼊框,默认设置为隐藏,将其value设置为id的值<form th:action="@{/goods/doUpdateGoods}" method="post"><input type="hidden" name="id" th:value="${goods.id}"><ul><li>name:<input type="text" name="name" th:value="${}"></li><li>remark:<textarea rows="3" cols="20" name="remark" th:text="${goods.remark}"></textarea></li><li><input type="submit" value="Update Goods"></li></ul></form>以上就是Spring Boot实现简单的增删改查的详细内容,更多关于Spring Boot增删改查的资料请关注其它相关⽂章!。

java myeclipse tomcat (六)详解servlet和dao数据库增删改查操作myeclipseservlet

java myeclipse tomcat (六)详解servlet和dao数据库增删改查操作myeclipseservlet

Java+MyEclipse+Tomcat (六)详解Servlet和DAO数据库增删改查操作,myeclipseservlet此篇文章主要讲述DAO、Java Bean和Servlet实现操作数据库,把链接数据库、数据库操作、前端界面显示分模块化实现。

其中包括数据的CRUD增删改查操作,并通过一个常用的JSP网站前端模板界面进行描述。

参考前文:Java+MyEclipse+Tomcat (一)配置过程及jsp网站开发入门Java+MyEclipse+Tomcat (二)配置Servlet及简单实现表单提交Java+MyEclipse+Tomcat (三)配置MySQL及查询数据显示在JSP网页中Java+MyEclipse+Tomcat (四)Servlet提交表单和数据库操作Java+MyEclipse+Tomcat (五)DAO和Java Bean 实现数据库和界面分开操作免费资源下载地址:/detail/eastmount/8733385PS:这篇文章可以认为是对前面五篇文章的一系列总结和应用,同时我认为理解该篇文章基本就能简单实现一个基于数据库操作的JSP网站,对你的课程项目或毕设有所帮助!但同时没有涉及事务、触发器、存储过程、并发处理等数据库知识,也没有Struts、Hibernate、Spring框架知识,它还是属于基础性文章吧!希望对你有所帮助~ 一. 项目结构该项目的结构如下图所示:这是典型的DAO模式,其中bean文件夹中TrainManage.java类封装了数据库表TrainManage中的属性和get/set操作;DAO文件夹中TrainManageDAO.java是对类TrainManage(或火车表)的数据库增删改查操作;util中JDBCConnect.java主要是连接数据库MySQL的操作;servlet主要是POST方法请求表单。

二. 数据库初始化操作打开MySQL,输入默认超级root用户的密码,然后数据库的操作如下代码:--创建数据库create database ManageTrain;--使用数据库use ManageTrain;--创建表车次信息管理表主键:车次--属性:车次出发地目的地行车时间硬座票价软座票价硬卧票价软卧票价车辆路线create table TrainManage(trainid varchar(20) primary key,start varchar(20),end varchar(20),time varchar(20),yzprice decimal(10,1),rzprice decimal(10,1),ywprice decimal(10,1),rwprice decimal(10,1),root varchar(200));--插入数据insert TrainManage(trainid,start,end,time,yzprice,rzprice,ywprice,rwprice,root) values ("T87","Beijing","Guiyang","28小时","278","320","464.5","550","Beijing Shijiazhuang Guiyang");insert TrainManage(trainid,start,end,time,yzprice,rzprice,ywprice,rwprice,root) values ("T87","Guiyang","Beijing","28小时","278","320","464.5","550","Guiyang Shijiazhuang Beijing");--查询数据select * from TrainManage;注意:上面操作在MySQL黑框中输出增删改查的SQL语言就可以,不要把中文注释也执行。

servlet增删改查

servlet增删改查

servlet增删改查Servlet使⽤Servlet进⾏增删改查步骤1.导⼊以下⼏个jar包到WEB-INF下的lib包⾥,必要时build path,其中jstl.jar和standard.jar是使⽤jstl要⽤的(eclipse中)2.写对应的dao,service,以及实现类3.写对应的servlet类,必须继承HttpServlet类1. 在此servlet类⾥加私有的service实现类;2. 添加doPost()和doGet⽅法:⼀般是在doPost()⾥写具体操作代码,doGet()⽅法⾥调⽤doPost,这样,不管提交⽅式是post还是get,都可以访问;3. doPost()⽅法⾥要先加request.setCharacterEncoding("utf-8");response.setContentType("text/html;charset=utf-8");1. 取参和传参,转发和重定向取参:String age1=request.getParameter("age");int age = Integer.parseInt(age1);传参:request.setAttribute("emp", emp);转发:request.getRequestDispatcher("/emp.jsp").forward(request, response);重定向:response.sendRedirect(request.getContextPath()+"/error.jsp");5配置web.xml,写对应的servlet和其映射访问时:先通过url定位到web.xml⾥servlet的url-pattern,再对应到servlet-name,再找到对应的servlet类,根据访问时提交的⽅法调⽤相应的doPost()或者doGet()⽅法6.写对应的前台页⾯取后台传过来的数据:${ }提交的url路径:<form action="/servletTest/updateEmp" method="post"></form><a href="/servletTest/deleteEmp?id=${emp.id }">删除</a>⽰例代码DbUtil.javapackage util;import mons.dbutils.QueryRunner;import boPooledDataSource;public class DbUtil {private static ComboPooledDataSource ds=new ComboPooledDataSource(); public static QueryRunner getQueryRunner(){QueryRunner qr = new QueryRunner(ds);return qr;}}c3p0-config.xml<c3p0-config><default-config><property name="driverClass">com.mysql.jdbc.Driver</property><property name="jdbcUrl">jdbc:mysql://localhost/test</property><property name="user">root</property><property name="password"></property><property name="initialPoolSize">5</property><property name="maxPoolSize">10</property></default-config></c3p0-config>EmpDao.javapackage dao;import java.util.List;import entity.Emp;public interface EmpDao {public int add(Emp emp);public int delete(int id);public int update(Emp emp);public Emp find(int id);public List<Emp> findAll();}EmpDaoImpl.javapackage dao.impl;import java.sql.SQLException;import java.util.List;import mons.dbutils.QueryRunner;import mons.dbutils.handlers.BeanHandler;import mons.dbutils.handlers.BeanListHandler;import util.DbUtil;import dao.EmpDao;import entity.Emp;public class EmpDaoImpl implements EmpDao {QueryRunner qr = DbUtil.getQueryRunner();@Overridepublic int add(Emp emp) {String sql="insert into emp(age,name) values(?,?) ";int num=0;try {num = qr.update(sql, emp.getAge(),emp.getName());} catch (SQLException e) {e.printStackTrace();}return num;}@Overridepublic List<Emp> findAll() {String sql="select*from emp";List<Emp> emps=null;try {emps=qr.query(sql, new BeanListHandler<Emp>(Emp.class)); } catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();}return emps;}@Overridepublic int delete(int id) {String sql="delete from emp where id="+id;int num=0;try {num=qr.update(sql);} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();}return num;}@Overridepublic int update(Emp emp) {String sql="update emp set name=?,age=? where id=?"; System.out.println("sql---------"+sql);int num=0;try {num=qr.update(sql, emp.getName(),emp.getAge(),emp.getId()); } catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();}return num;}@Overridepublic Emp find(int id) {String sql="select * from emp where id="+id;Emp emp=null;try {emp=qr.query(sql, new BeanHandler<Emp>(Emp.class));} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();}return emp;}}EmpService.javapackage service;import java.util.List;import entity.Emp;public interface EmpService {public int addEmp(Emp emp);public List<Emp> findAll();public int delete(int id);public int update(Emp emp);public Emp find(int id);}EmpServiceImpl.javapackage service.impl;import java.util.List;import service.EmpService;import dao.impl.EmpDaoImpl;import entity.Emp;public class EmpServiceImpl implements EmpService {private EmpDaoImpl empDao=new EmpDaoImpl();@Overridepublic int addEmp(Emp emp) {int num = empDao.add(emp);return num;}@Overridepublic List<Emp> findAll() {return empDao.findAll();}@Overridepublic int delete(int id) {return empDao.delete(id);}@Overridepublic int update(Emp emp) {return empDao.update(emp);}@Overridepublic Emp find(int id) {return empDao.find(id);}}AddEmpServlet.javapackage servlet;import java.io.IOException;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import service.impl.EmpServiceImpl;import entity.Emp;public class AddEmpServlet extends HttpServlet {private EmpServiceImpl empService=new EmpServiceImpl();@Overridepublic void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {request.setCharacterEncoding("utf-8");response.setContentType("text/html;charset=utf-8");String age1=request.getParameter("age");int age = Integer.parseInt(age1);String name = request.getParameter("name");Emp emp=new Emp();emp.setAge(age);emp.setName(name);int num = empService.addEmp(emp);if(num>0){response.sendRedirect(request.getContextPath()+"/empList");}else{response.sendRedirect(request.getContextPath()+"/error.jsp");}}@Overridepublic void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {doPost(request, response);;}}DeleteEmpServlet.javapackage servlet;import java.io.IOException;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import service.impl.EmpServiceImpl;import entity.Emp;public class DeleteEmpServlet extends HttpServlet {private EmpServiceImpl empService=new EmpServiceImpl();@Overridepublic void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {request.setCharacterEncoding("utf-8");response.setContentType("text/html;charset=utf-8");String id1 = request.getParameter("id");Integer id=Integer.parseInt(id1);System.out.println("进⼊删除,id="+id);int num = empService.delete(id);System.out.println("删除?---"+num);if(num>0){response.sendRedirect(request.getContextPath()+"/empList");}else{response.sendRedirect("/error.jsp");}}@Overridepublic void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {doPost(request, response);}}//修改时,先找到要修改的对象,再转发到需要修改的页⾯,显⽰要修改的对象信息,然后提交时修改FindUpdEmpServlet .javapackage servlet;import java.io.IOException;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import entity.Emp;import service.impl.EmpServiceImpl;public class FindUpdEmpServlet extends HttpServlet {private EmpServiceImpl empService=new EmpServiceImpl();@Overridepublic void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {request.setCharacterEncoding("utf-8");response.setContentType("text/html;charset=utf-8");Integer id=Integer.parseInt(request.getParameter("id"));Emp emp = empService.find(id);System.out.println("要修改的emp"+emp.getName());if(emp!=null){request.setAttribute("emp", emp);request.getRequestDispatcher("/update.jsp").forward(request, response);;}else{response.sendRedirect(request.getContextPath()+"/error.jsp");}}@Overridepublic void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {doPost(request, response);}}UpdateEmpServlet.javapackage servlet;import java.io.IOException;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import service.impl.EmpServiceImpl;import entity.Emp;public class UpdateEmpServlet extends HttpServlet {private EmpServiceImpl empService=new EmpServiceImpl();@Overridepublic void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {request.setCharacterEncoding("utf-8");response.setContentType("text/html;charset=utf-8");String id1 = request.getParameter("id");Integer id=Integer.parseInt(id1);String name = request.getParameter("name");String age1 = request.getParameter("age");Integer age=Integer.parseInt(age1);Emp emp=new Emp();emp.setId(id);emp.setAge(age);emp.setName(name);//empService.find(id);int num = empService.update(emp);if(num>0){response.sendRedirect(request.getContextPath()+"/empList");}else{response.sendRedirect("/error.jsp");}}@Overridepublic void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {doPost(request, response);}}FindEmpServlet.javapackage servlet;import java.io.IOException;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import entity.Emp;import service.impl.EmpServiceImpl;public class FindEmpServlet extends HttpServlet {private EmpServiceImpl empService=new EmpServiceImpl();@Overridepublic void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {request.setCharacterEncoding("utf-8");response.setContentType("text/html;charset=utf-8");Integer id=Integer.parseInt(request.getParameter("id"));Emp emp = empService.find(id);System.out.println("emp---"+emp.getName()+"---"+emp.getAge());if(emp!= null){request.setAttribute("emp", emp);request.getRequestDispatcher("/emp.jsp").forward(request, response);}else{response.sendRedirect(request.getContextPath()+"/error.jsp");}}@Overridepublic void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {doPost(request, response);}}FindEmp s Servlet.javapackage servlet;import java.io.IOException;import java.util.List;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import entity.Emp;import service.impl.EmpServiceImpl;public class FindEmpsServlet extends HttpServlet {private EmpServiceImpl empService=new EmpServiceImpl();@Overridepublic void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {request.setCharacterEncoding("utf-8");response.setContentType("text/html;charset=utf-8");List<Emp> emps = empService.findAll();if(emps!=null){request.setAttribute("emps", emps);request.getRequestDispatcher("/list.jsp").forward(request, response);}else{response.sendRedirect(request.getContextPath()+"/error.jsp");}}@Overridepublic void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {doPost(request, response);}}web.xml前台页⾯add.jsp<%@ page language="java" contentType="text/html; charset=utf-8"pageEncoding="utf-8"%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "/TR/html4/loose.dtd"> <html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"><title>添加员⼯</title></head><body><form action="/servletTest/addEmp" method="post">姓名:<input type="text" name="name"/><p>年龄:<input type="text" name="age"/><p><input type="submit" value="添加"/></form></body></html>list.jsp<%@ page language="java" contentType="text/html; charset=utf-8"pageEncoding="utf-8"%><%@taglib uri="/jsp/jstl/core" prefix="c"%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "/TR/html4/loose.dtd"> <html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"><title>员⼯列表</title></head><body>添加成功<table><tr ><td colspan="3"><a href="index.jsp">添加</a></td></tr><tr><th>编号</th><th>年龄</th><th>age</th><th colspan="3">操作</th></tr><!--items⾥⾯写${requestScope.emps}也可以 --><c:forEach items="${emps }" var="emp" varStatus="vs"><tr><td>${emp.id }</td><td>${ }</td><td>${emp.age }</td><td><a href="/servletTest/deleteEmp?id=${emp.id }">删除</a></td><td><a href="/servletTest/findUpdEmp?id=${emp.id }">修改</a></td><td><a href="/servletTest/findEmp?id=${emp.id }">查看</a></td></tr></c:forEach></table></body></html>emp.jsp<%@ page language="java" contentType="text/html; charset=utf-8"pageEncoding="utf-8"%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "/TR/html4/loose.dtd"> <html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"><title>Insert title here</title></head><body>编号:${emp.id }<p>姓名:${ }<p>年龄:${emp.age }</body></html>update.jsp<%@ page language="java" contentType="text/html; charset=utf-8"pageEncoding="utf-8"%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "/TR/html4/loose.dtd"> <html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"><title>修改员⼯</title></head><body><form action="/servletTest/updateEmp" method="post">编号:<input type="text" name="id" value="${emp.id }" readonly="readonly"/><p>姓名:<input type="text" name="name" value="${ }"/><p>年龄:<input type="text" name="age" value="${emp.age }"/><p><input type="submit" value="提交"/></form></body></html>error.jsp<%@ page language="java" contentType="text/html; charset=utf-8"pageEncoding="utf-8"%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "/TR/html4/loose.dtd"> <html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"><title>Insert title here</title></head><body><h1>出错了</h1></body></html>。

Servlet.service()forservlet[jsp]incontext....错误

Servlet.service()forservlet[jsp]incontext....错误

Servlet.service()forservlet[jsp]incontext....错误Servlet.service() for servlet [jsp] in context with path [/mvcTest] threw exception [ng.NullPointerException] with root causeng.NullPointerException这是在⽤tomcat写⼀个⼩应⽤时遇到的错误,在⽹上看了很多没看明⽩,最终试错n次后发现了问题,其实这个问题(我遇到的那种情况,可能这个报错不⽌我遇到的这种情况导致)的根本原因是:.jsp页⾯代码导致的,因为为了实现前端和后台的交互,在有些jsp代码中需要后台传⼊相应的数据到该jsp中,所以jsp代码中就有了接收的代码段,⽽当我们想跳转到该jsp页⾯时却没有传⼊相应的数据就会报上⾯所⽰的错误:空指针(因为后端没有参数传⼊时那么jsp中的参数就是⼀个空值,⽽空值是不能进⾏很多操作的)。

我们有时直接跳到jsp页⾯成功是因为该jsp页⾯是不需要传⼊数据的。

如何处理这个问题:当然是传⼊相应的数据了,注意⽤request对象传数据时,requset对象域空间中的数据只能存活于⼀个请求中,那么就可能需要多次setAttribute()和多次getAttribute()当然如果在jsp页⾯中对⽤到传⼊参数的相关代码块做判断也是可以的,即满⾜相应的条件时再执⾏该代码块即在jsp页⾯端时判断时要加上判断接收到的数据是否为null,不为空的话再执⾏含有参数的代码块;你也可以⾃⼰测试,如果你想跳到相应的页⾯,则直接在浏览器中访问看是否可以访问到,访问出错,那肯定就说明该jsp页⾯是不能直接访问的,可能需要传⼊参数,当然前提是你的代码要是正确的;说到这⾥你明⽩的话就不必往下看了,下⾯是我遇到的场景-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------当然导致这个问题的原因可能不⽌我下⾯所说的这⼀种。

JavaWeb应用实例servlet实现oracle基本增删改查(精)

JavaWeb应用实例servlet实现oracle基本增删改查(精)

Java Web 应用实例 servlet实现oracle 基本增删改查分类:JAVA WEB应用实例2012-08-31 16:51 3515人阅读评论(0 收藏举报/a542214712/article/details/7924444很久没有写博客了,可能是太懒散,不愿意把时间花在这上面,可是我心里还是知道写博客的重要性的,所以从今天开始,我将与大家分享一下我学JAVA WEB写的一些小实例,我个人是不太喜欢书本上的晦涩的概念的,所以我花了更多的时间在一些应用实例上,我觉得这样的学习方式很适合我,由简到繁,由浅入深废话不多话,开始我们的第一个实例:servlet实现oracle 基本增删改查开发环境:JDK7 +Myeclipse10+tomcat7.0+oracle 11g首先附上数据库创建脚本:[sql]view plaincopy1. create table student(2. id VARCHAR2(50 PRIMARY KEY NOT NULL,3. name varchar2(50 NOT NULL,4. calssGrent varchar2(50 NOT NULL ,5. result varchar(12 NOT NULL6. ;7. insert into student(id,name,calssGrent,result values(perseq.nextval,'张三','33','98'下图为代码结构图和功能演示界面做的比较糟糕只为实现功能:MMC_01.java页面 //主界面提供添加,修改删除的方法[java]view plaincopy1. package org.lsy.servlet;2.3. import java.io.IOException;4. import java.io.PrintWriter;5. import java.sql.Connection;6. import java.sql.DriverManager;7. import java.sql.ResultSet;8. import java.sql.Statement;9.10. import javax.servlet.ServletException;11. import javax.servlet.http.HttpServlet;12. import javax.servlet.http.HttpServletRequest;13. import javax.servlet.http.HttpServletResponse;14.15. import oracle.jdbc.oracore.TDSPatch;16.17. public class MMC_01 extends HttpServlet18. {19. // 驱动程序就是之前在classpath中配置的jdbc的驱动程序的jar包中20.21. // 连接地址是由各个数据库生产商单独提供的,所以需要单独记住22. public static final String DBURL = "jdbc:oracle:thin:@localhost:1521:LIUSY ";23. // 连接数据库的用户名24. public static final String DBUSER = "scott";25. // 连接数据库的密码26. public static final String DBPASS = "tiger";27.28. public void doGet(HttpServletRequest request, HttpServletResponse response29. throws ServletException, IOException30. {31. //设置请求和响应的编码,不然页面上容易出现乱码32. request.setCharacterEncoding("UTF-8";33. response.setCharacterEncoding("UTF-8";34.35. response.setContentType("text/html;UTF-8";36. //输出流37. PrintWriter out = response.getWriter(;38. //数据库连接代码39. try40. {41. Connection conn = null; // 表示数据库的连接的对象42. Statement stmt = null; // 表示数据库的更新操作43. String sql="insert into student(id,name,calssGrent,result values( '67','刘12宇','33','98'";44. System.out.println(sql ;45. // 1、使用Class类加载驱动程序46. Class.forName("oracle.jdbc.driver.OracleDriver";47. // 2、连接数据库48. conn = DriverManager.getConnection(DBURL, DBUSER, DBPASS;49. // 3、Statement接口需要通过Connection接口进行实例化操作50. stmt = conn.createStatement(;51. //用 rs获取查询结果,这里的SQL语句最好不要用* 我的字段比较少所以就偷一下懒,-,-52. ResultSet rs=stmt.executeQuery("select *from student";53. out.println("";54. out.println("";55. out.println(" ";56. out.println(" ";57. //输出表头部分58. out.print(" 姓名" +59. "班级成绩修改删除";60. while(rs.next(61. {62. //获取数据库中的ID63. String id=rs.getString("id";64. //输出一列元素65. out.print(""+rs.getString("name"66. +""+rs.getString("calssGrent"+"" +67. ""+rs.getString("result"+"" +68. " +id+ "'> 修改 " +69. " +id+ "'> 删除 " ;70.71. }72. out.println(" 添加数据";73. out.println(" ";74. out.println("";75. conn.close(;76.77. }78. catch (Exception e79. {80. e.printStackTrace(;81. }82. out.flush(;83. out.close(;84. }85.86. }87.UpdatePage.java //获取要修改的数据,并把修改过的数据提交给Update [java]view plaincopy1. package org.lsy.servlet;2. import java.io.IOException;3. import java.io.PrintWriter;4. import java.sql.Connection;5. import java.sql.DriverManager;6. import java.sql.ResultSet;7. import java.sql.Statement;8.9. import javax.servlet.ServletException;10. import javax.servlet.http.HttpServlet;11. import javax.servlet.http.HttpServletRequest;12. import javax.servlet.http.HttpServletResponse;13.14. import com.sun.crypto.provider.RSACipher;15.16. public class UpdatePage extends HttpServlet17. {18. // 连接地址是由各个数据库生产商单独提供的,所以需要单独记住19. public static final String DBURL = "jdbc:oracle:thin:@localhost:1521: LIUSY";20. // 连接数据库的用户名21. public static final String DBUSER = "scott";22. // 连接数据库的密码23. public static final String DBPASS = "tiger";24.25. public void doGet(HttpServletRequest request, HttpServletResponse response26. throws ServletException, IOException27. {28. String id=request.getParameter("id";29. //设置请求和响应的编码,不然页面上容易出现乱码30. request.setCharacterEncoding("UTF-8";31. response.setCharacterEncoding("UTF-8";32. response.setContentType("text/html;UTF-8";33. PrintWriter out = response.getWriter(;34. try35. {36. Connection conn = null; // 表示数据库的连接的对象37. Statement stmt = null; // 表示数据库的更新操作38. // 1、使用Class类加载驱动程序39. Class.forName("oracle.jdbc.driver.OracleDriver";40. // 2、连接数据库41. conn = DriverManager.getConnection(DBURL, DBUSER, DBPASS;42. // 3、Statement接口需要通过Connection接口进行实例化操作43. stmt = conn.createStatement(;44. //用 rs获取查询结果,这里的SQL语句最好不要用* 我的字段比较少所以就偷一下懒,-,-45. ResultSet rs=stmt.executeQuery("select *from student where id='"+id+"'";46. while (rs.next(47. {48. out.println("";49. out.println("";50. out.println(" ";51. out.println(" ";52. //输入成绩的表单,提交至Update53. out.print(" " ;54. out.print(" 姓名:+rs.getString( "name" +"'[java] view plaincopy1. "white-space:pre"> name='name' size=20 >";2. out.print("班级:+rs.getString( "calssGrent" +"' name='grent' size=20>" ;3. out.print("成绩:+rs.getString( "result" +"' name='result' size=20>" ;4. //为了作为查询数据库的条件,这里要把ID传过去5. out.print(" +id+ "' name='id'>" ;6. out.print(" 修改 '> 重置 '>" ;7. out.print(" ";8. out.println("";9. }10. out.flush(;11. out.close(;12. }13. catch (Exception e {14. e.printStackTrace(;// TODO: handle exception15. }16. }17.18. }Update.java 接收要修改的数据,并更新数据库[java]view plaincopy1. package org.lsy.servlet;2.3. import java.io.IOException;4. import java.io.PrintWriter;5. import java.sql.Connection;6. import java.sql.DriverManager;7. import java.sql.Statement;8.9. import javax.servlet.ServletException;10. import javax.servlet.http.HttpServlet;11. import javax.servlet.http.HttpServletRequest;12. import javax.servlet.http.HttpServletResponse;13.14. public class Update extends HttpServlet15. {16. // 驱动程序就是之前在classpath中配置的jdbc的驱动程序的jar包中17.18. // 连接地址是由各个数据库生产商单独提供的,所以需要单独记住19. public static final String DBURL = "jdbc:oracle:thin:@localhost:1521:LIUSY";20. // 连接数据库的用户名21. public static final String DBUSER = "scott";22. // 连接数据库的密码23. public static final String DBPASS = "tiger";24.25. public void doGet(HttpServletRequest request, HttpServletResponse response26. throws ServletException, IOException27. {28. try29.30. {31. request.setCharacterEncoding("UTF-8";32. response.setCharacterEncoding("UTF-8";33. response.setContentType("text/html;UTF-8";34. PrintWriter out = response.getWriter(;35. Connection conn = null; // 表示数据库的连接的对象36. Statement stmt = null; // 表示数据库的更新操作37. //获取表单提交的参数湖北省武昌区2012届高三年级元月调研测试英语试题本试卷第一至第三部分为选择题,共100分;第四部分为非选择题,共50分,全卷共12页。

servlet+mybatis实现mysql的增删改查实例

servlet+mybatis实现mysql的增删改查实例

servlet+mybatis实现mysql的增删改查实例古⼈云:温故⽽知新。

趁周末,重新来学习了⼀遍servlet + mybatis 实现mysql的增删改查,算是对⾃⼰学习的⼀个总结和记录。

开门见⼭,⾸先我们来看⼀下项⽬⽬录结构:不难发现这是⼀个maven的项⽬结构。

既然是maven项⽬,我们来看看使⽤servlet + mybatis 需要使⽤到哪些jar包,pom.xml⽂件代码如下:<project xmlns="/POM/4.0.0" xmlns:xsi="/2001/XMLSchema-instance"xsi:schemaLocation="/POM/4.0.0 /maven-v4_0_0.xsd"><modelVersion>4.0.0</modelVersion><groupId>com.sunshine</groupId><artifactId>ssm</artifactId><packaging>war</packaging><version>1.0-SNAPSHOT</version><name>ssm</name><url></url><!--设置版本信息--><properties><jdk.version>1.8</jdk.version><slf4j.version>1.7.12</slf4j.version><log4j.version>1.2.14</log4j.version></properties><dependencies><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.12</version></dependency><!--log4j⽇志⽀持--><!-- ⽇志⽂件管理包 --><dependency><groupId>log4j</groupId><artifactId>log4j</artifactId><version>${log4j.version}</version></dependency><!-- 格式化对象,⽅便输出⽇志 --><dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>1.1.41</version></dependency><dependency><groupId>org.slf4j</groupId><artifactId>slf4j-api</artifactId><version>${slf4j.version}</version></dependency><dependency><groupId>org.slf4j</groupId><artifactId>slf4j-log4j12</artifactId><version>${slf4j.version}</version></dependency><!-- log end --><!--mybatis--><dependency><groupId>org.mybatis</groupId><artifactId>mybatis</artifactId><version>3.4.1</version></dependency><!--mysql 使⽤5.X版本--><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>5.1.6</version></dependency><!--servlet--><dependency><groupId>javax.servlet</groupId><artifactId>javax.servlet-api</artifactId><version>3.1.0</version></dependency></dependencies><build><finalName>ssm</finalName><!--配置编译jdk版本--><plugins><plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-compiler-plugin</artifactId><version>3.2</version><configuration><source>1.8</source><target>1.8</target></configuration></plugin></plugins></build></project>其中servlet使⽤到了⼀个包,连接mysql数据库需要⽤⼀个包,注意是使⽤5.X版本,mybatis也是使⽤到了⼀个包,除了这三个还导⼊到了log4j⽇志管理的相关包,以⽅便⽇志的输出和管理,log4j需要⽤到哪些包上⾯代码已标出。

javaWeb-连接mysql数据库增删改查(精)

javaWeb-连接mysql数据库增删改查(精)

连接MYSQL数据库的简单增删改查项目框架如图所示:所需工具:所需工具:所需工具:所需工具:程序代码:package er.action; import java.io.IOException;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import erBean;import erDao;public class InsertOrUpdateAction extends HttpServlet { /****/private static final long serialVersionUID = 1L;private UserDao userDao ;public void doGet(HttpServletRequest request, HttpServletResponse responsethrows ServletException, IOException {doPost(request, response;}public void doPost(HttpServletRequest request, HttpServletResponse responsethrows ServletException, IOException {request.setCharacterEncoding("utf-8";response.setCharacterEncoding("utf-8";userDao = new UserDao(;String str = request.getRequestURI(;str = str.substring(stIndexOf("/"+1;String yx = request.getParameter("yx";String zy = request.getParameter("zy";String age = request.getParameter("age";String dh = request.getParameter("dh"; String qq = request.getParameter("qq"; String sex = request.getParameter("sex"; UserBean userBean = new UserBean(; userBean.setYx(yx;userBean.setZy(zy;if(!"".equals(age&&age!=null{userBean.setAge(Integer.valueOf(age;}else{userBean.setAge(0;}userBean.setDh(dh;userBean.setQq(qq;userBean.setSex(sex;if("InsertUserAction".equals(str{if(userDao.insertUser(userBean{response.sendRedirect("SelectAllUser";}else{response.sendRedirect("SelectAllUser";}}else if("UpdateUserAction".equals(str{ String strId = request.getParameter("id"; if(!"".equals(strId&&strId!=null{ userBean.setId(Integer.valueOf(strId;}else{userBean.setId(-1;}if(userDao.updateUser(userBean{response.sendRedirect("SelectAllUser";}else{response.sendRedirect("SelectAllUser";}}}}package er.action;import java.io.IOException;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;public class LoginAction extends HttpServlet {/****/private static final long serialVersionUID = 1L;public void doGet(HttpServletRequest request, HttpServletResponse responsethrows ServletException, IOException {doPost(request, response;}public void doPost(HttpServletRequest request, HttpServletResponse responsethrows ServletException, IOException {String name= request.getParameter("name";String password = request.getParameter("password"; if("".equals(name||"".equals(password{response.sendRedirect("/javaWebTest/index.jsp";}else{if("123".equals(name&&"123".equals(password{response.sendRedirect("SelectAllUser";}else{response.sendRedirect("/javaWebTest/index.jsp";}}}}package er.action;import java.io.IOException;import java.util.List;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import erBean;import erDao;public class UserAction extends HttpServlet {/****/private static final long serialVersionUID = 1L;private UserDao userDao ;public void doGet(HttpServletRequest request, HttpServletResponse response throws ServletException, IOException {doPost(request, response;}public void doPost(HttpServletRequest request, HttpServletResponse response throws ServletException, IOException {request.setCharacterEncoding("utf-8";response.setCharacterEncoding("utf-8";userDao = new UserDao(;String str = request.getRequestURI(;str = str.substring(stIndexOf("/"+1;if("SelectAllUser".equals(str.trim({List list = userDao.getAllUser(;request.setAttribute("UserList", list;request.getRequestDispatcher("/userList.jsp".forward(request, response;}else if("SelectOneUser".equals(str{String strId = request.getParameter("id";int id = Integer.valueOf(strId;UserBean userBean = userDao.selectUserById(id;request.setAttribute("userBean", userBean;request.getRequestDispatcher("/updateUser.jsp".forward(request, response; }else if("DeleteUserById".equals(str{String strId = request.getParameter("id";int id = Integer.valueOf(strId;if(userDao.deleteUser(id{response.sendRedirect("SelectAllUser";}else{response.sendRedirect("SelectAllUser";}}}}package er.dao;import java.sql.ResultSet;import java.sql.SQLException;import java.util.ArrayList;import java.util.List;import erBean;import com.util.DBUtils;public class UserDao {private DBUtils dbUtil;/*** 查询所有的user* @return*/public List getAllUser({dbUtil = new DBUtils(;List list = new ArrayList (;String sql = "select * from user";ResultSet rs = dbUtil.exceteSQl(sql; try {while(rs.next({int i =1;UserBean userBean = new UserBean(; userBean.setId(rs.getInt(i++; userBean.setName(rs.getString(i++; userBean.setYx(rs.getString(i++; userBean.setZy(rs.getString(i++; userBean.setAge(rs.getInt(i++; userBean.setDh(rs.getString(i++; userBean.setQq(rs.getString(i++; userBean.setSex(rs.getString(i++;list.add(userBean;}} catch (SQLException e {e.printStackTrace(;}finally{dbUtil.close(;}return list;}/*** 根据id查询user* @param id* @return*/public UserBean selectUserById(int id{ dbUtil = new DBUtils(;UserBean userBean = new UserBean(;String sql = "select * from user where id = '"+id+"'";ResultSet rs = dbUtil.exceteSQl(sql;try {if(rs.next({int i =1;userBean.setId(rs.getInt(i++;userBean.setYx(rs.getString(i++;userBean.setZy(rs.getString(i++;userBean.setAge(rs.getInt(i++;userBean.setDh(rs.getString(i++;userBean.setQq(rs.getString(i++;userBean.setSex(rs.getString(i++;}} catch (SQLException e {e.printStackTrace(;}return userBean;}/*** 插入用户* @param userBean* @return*/public boolean insertUser(UserBean userBean{dbUtil = new DBUtils(;String sql = "insert into user (yx,zy,age,dh,qq,sex values(?,?,?,?,?,?"; int row = dbUtil.excete(sql, newObject[]{userBean.getYx(,userBean.getZy(,userBean.getAge(,userBean.getDh(,userBean.getQq(,userBean.getSex(};if(row>0{return true;}return false;}/*** 删除用户* @param id* @return*/public boolean deleteUser(int id{dbUtil = new DBUtils(;String sql = "delete from user where id = '"+id+ "'";int row = dbUtil.excete(sql;if(row>0{return true;}return false;}/*** 修改user* @param userBean* @return*/public boolean updateUser(UserBean userBean{dbUtil = new DBUtils(;String sql = "update user set yx =? ,zy=?,age=?,dh=?,qq=?,sex=? where id = ?";int row = dbUtil.excete(sql, newObject[]{userBean.getYx(,userBean.getZy(,userBean.getAge(,userBean.getD h(,userBean.getQq(,userBean.getSex(,userBean.getId(};if(row>0{return true;}return false;}}package er.bean;public class UserBean {private int id;private String name;//电话private String yx;//院系private String zy;//专业private int age;//年龄private String dh;private String qq;private String sex;public int getId( {return id;}public void setId(int id {this.id = id;}public String getName( {return name;}public void setName(String name { = name;public String getYx( {return yx;}public void setYx(String yx { this.yx = yx;}public String getZy( {return zy;}public void setZy(String zy { this.zy = zy;}public int getAge( {return age;}public void setAge(int age { this.age = age;}public String getDh( {return dh;}public void setDh(String dh { this.dh = dh;}public String getQq( {return qq;public void setQq(String qq { this.qq = qq;}public String getSex( {return sex;}public void setSex(String sex { this.sex = sex;}}package er.dao;import java.sql.ResultSet;import java.sql.SQLException;import java.util.ArrayList;import java.util.List;import erBean; import com.util.DBUtils;public class UserDao {private DBUtils dbUtil;/*** 查询所有的user* @return*/public List getAllUser({dbUtil = new DBUtils(;List list = new ArrayList (;String sql = "select * from user"; ResultSet rs = dbUtil.exceteSQl(sql; try {while(rs.next({int i =1;UserBean userBean = new UserBean(; userBean.setId(rs.getInt(i++; userBean.setName(rs.getString(i++; userBean.setYx(rs.getString(i++; userBean.setZy(rs.getString(i++; userBean.setAge(rs.getInt(i++; userBean.setDh(rs.getString(i++; userBean.setQq(rs.getString(i++; userBean.setSex(rs.getString(i++; list.add(userBean;}} catch (SQLException e {e.printStackTrace(;}finally{dbUtil.close(;}return list;/*** 根据id查询user* @param id* @return*/public UserBean selectUserById(int id{dbUtil = new DBUtils(;UserBean userBean = new UserBean(;String sql = "select * from user where id = '"+id+"'"; ResultSet rs = dbUtil.exceteSQl(sql;try {if(rs.next({int i =1;userBean.setId(rs.getInt(i++;userBean.setYx(rs.getString(i++;userBean.setZy(rs.getString(i++;userBean.setAge(rs.getInt(i++;userBean.setDh(rs.getString(i++;userBean.setQq(rs.getString(i++;userBean.setSex(rs.getString(i++;}} catch (SQLException e {e.printStackTrace(;return userBean;}/*** 插入用户* @param userBean* @return*/public boolean insertUser(UserBean userBean{dbUtil = new DBUtils(;String sql = "insert into user (yx,zy,age,dh,qq,sex values(?,?,?,?,?,?";int row = dbUtil.excete(sql, newObject[]{userBean.getYx(,userBean.getZy(,userBean.getAge(,userBean.getDh(,userBean .getQq(,userBean.getSex(};if(row>0{return true;}return false;}/*** 删除用户* @param id* @return*/public boolean deleteUser(int id{dbUtil = new DBUtils(;String sql = "delete from user where id = '"+id+ "'";int row = dbUtil.excete(sql;if(row>0{return true;}return false;}/*** 修改user* @param userBean* @return*/public boolean updateUser(UserBean userBean{dbUtil = new DBUtils(;String sql = "update user set yx =? ,zy=?,age=?,dh=?,qq=?,sex=? where id = ?";int row = dbUtil.excete(sql, newObject[]{userBean.getYx(,userBean.getZy(,userBean.getAge(,userBean.getDh(,userBean .getQq(,userBean.getSex(,userBean.getId(};if(row>0{return true;}return false;}}package com.util;import java.sql.Date;import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;import com.mysql.jdbc.Connection;import com.mysql.jdbc.Statement;public class DBUtils {private static Connection conn=null;private Statement st=null;private ResultSet rs = null;private PreparedStatement ps;static{try {Class.forName("com.mysql.jdbc.Driver";conn = (ConnectionDriverManager.getConnection("jdbc:mysql://localhost:3306/ygx?useUnicode=true&char acterEncoding=UTF-8","root" ,"123456" ;} catch (ClassNotFoundException e {e.printStackTrace(;} catch (SQLException e {e.printStackTrace(;}}/*** @Title: exceteSQl* @Description: TODO(执行不带参数的sql语句* @param sql* @return ResultSet* @throws*/public ResultSet exceteSQl(String sql{try {st =(Statement conn.createStatement(;rs = st.executeQuery(sql;} catch (SQLException e {e.printStackTrace(;}return rs;}/**** @Title: exceteSQl* @Description: TODO(执行带参数的sql语句* @param sql* @param obj* @return ResultSet* @throwspublic ResultSet exceteSQl(String sql, Object[] obj{int length = obj.length;try {ps = conn.prepareStatement(sql;preparStateSql(obj, length;rs = ps.executeQuery(;} catch (SQLException e {e.printStackTrace(;}return rs;}/**** @Title: excete* @Description: TODO(此方法适用于不带参数的修改,删除,增加* @param sql* @return int* @throws*/public int excete(String sql{int row =0;try {st = (Statement conn.createStatement(;row = st.executeUpdate(sql;} catch (SQLException e {e.printStackTrace(;}finally{close(;}return row;}/**** @Title: excete* @Description: TODO(此方法适用带参数的修改,删除,增加* @param sql* @param obj* @return int* @throws*/public int excete(String sql, Object[] obj{int row =0;int length = obj.length;try {ps = conn.prepareStatement(sql;preparStateSql(obj, length;row = ps.executeUpdate(;} catch (SQLException e {e.printStackTrace(;}finally{close(;}return row;}/**** @Title: preparStateSql* @Description: TODO(参数赋值* @param obj* @param length* @throws SQLException void* @throws*/private void preparStateSql(Object[] obj, int length throws SQLException { for(int i=0;i{if(obj[i].getClass(==String.class{ps.setString(i+1, obj[i].toString(;}else if(obj[i].getClass(==Integer.class{ps.setInt(i+1, (Integerobj[i];}else if(obj[i].getClass(==Double.class{ps.setDouble(i+1, (Doubleobj[i];}else if(obj[i].getClass(==Date.class//java.sql.Date {ps.setDate(i+1, (Dateobj[i];}}}/**** @Title: close* @Description: TODO(数据库连接关闭 void* @throws*/public void close({if(rs!=null{try {rs.close(;} catch (SQLException e {e.printStackTrace(;}}if(st!=null{try {st.close(;} catch (SQLException e {e.printStackTrace(;}}if(ps!=null{try {ps.close(;} catch (SQLException e {e.printStackTrace(;}}}public static void main(String[] args { DBUtils db = new DBUtils(;String sql = "select * from user "; ResultSet rr = db.exceteSQl(sql;try {while(rr.next({int i =1;System.out.print(rr.getInt(i+++" "; System.out.print(rr.getString(i+++" "; System.out.print(rr.getString(i+++" "; System.out.print(rr.getInt(i+++" "; System.out.print(rr.getString(i+++" "; System.out.print(rr.getString(i+++" "; System.out.println(rr.getString(i++;}} catch (SQLException e {// TODO Auto-generated catch blocke.printStackTrace(;}finally{db.close(;}//String sql = "insert into user (yx,zy,age,dh,qq,sex values(\"软件\",\"测试\",12,\"110\",\"123456789\",\"女\"";/* String sql = "insert into user (yx,zy,age,dh,qq,sexvalues(?,?,?,?,?,?";int row = db.excete(sql, new Object[]{"软件","测试",12,"110","123456789","女"};//int row = db.excete(sql;if(row>0{System.out.println("增加成功";}*//*String sql = "update user set yx=? where id =?";int row = db.excete(sql, new Object[]{"计通",3};if(row>0{System.out.println("修改成功";}*/}}所需要的驱动包:W eb.xml配置:xml version="1.0"encoding="UTF-8"?><web-app version="2.5"xmlns="/xml/ns/javaee"xmlns:xsi="/2001/XMLSchema-instance"xsi:schemaLocation="/xml/ns/javaee/xml/ns/javaee/web-app_2_5.xsd"><display-name> display-name><servlet><servlet-name>UserAction servlet-name><servlet-class>erAction servlet-class>servlet><servlet><servlet-name>InsertOrUpdateAction servlet-name><servlet-class>er.action.InsertOrUpdateAction servlet-class> servlet><servlet><servlet-name>LoginAction servlet-name><servlet-class>er.action.LoginAction servlet-class>servlet><servlet-mapping><servlet-name>UserAction servlet-name><url-pattern>/SelectAllUser url-pattern><url-pattern>/SelectOneUser url-pattern><url-pattern>/DeleteUserById url-pattern>servlet-mapping><servlet-mapping><servlet-name>InsertOrUpdateAction servlet-name><url-pattern>/InsertUserAction url-pattern><url-pattern>/UpdateUserAction url-pattern>servlet-mapping><servlet-mapping><servlet-name>LoginAction servlet-name><url-pattern>/LoginAction url-pattern>servlet-mapping><welcome-file-list><welcome-file>index.jsp welcome-file>welcome-file-list>web-app>J sp:<%@page language="java"import="java.util.*"pageEncoding="UTF-8"%> <%String path = request.getContextPath(;String basePath =request.getScheme(+"://"+request.getServerName(+":"+request.getServerPo rt(+path+"/";%>DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html><head><base href="<%=basePath%>"><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"><style type="text/css">.table1{margin:0 auto;border-collapse: collapse;}.table1td{padding: 0px;height:25px;border:1px solid #6AB6B6;text-align:center;font-family:"微软雅黑";font-size:12px;background-color:#EAFEFE;}.table1td.title{height:28px;color:#fff;background-color:#6AB6B6;font-weight:bold;font-size:20px;text-align: center;}.table1tr.colname{font-size: 14px;font-weight: bold;}* .nobd_table td{border: none;}style>head><body><div align="center"style="padding-top: 30px;" id = "add"> <form action="LoginAction"method="post"><table class="table1"width="50%"><tr><td class="title"colspan="2">欢迎你的登录!td>tr><tr><td>帐号td><td><input type="text"name="name">td>tr><tr><td>密码td><td><input type="password"name="password">td>tr><tr><td colspan="2"><input type="submit"value="登录"><inputtype="reset"value="重置"> td>tr>table>form>div>body>html><%@ page language="java"import="java.util.*,erBean" pageEncoding="utf-8"%><%@ taglib prefix="c"uri="/jsp/jstl/core"%><%String path = request.getContextPath(;String basePath =request.getScheme(+"://"+request.getServerName(+":"+request.getServerPo rt(+path+"/";%>DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html><head><base href="<%=basePath%>"><title>My JSP 'userList.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"><style type="text/css">.table1{margin:0 auto;border-collapse: collapse;}.table1td{padding: 0px;height:25px;border:1px solid #6AB6B6;text-align:center;font-family:"微软雅黑";font-size:12px;background-color:#EAFEFE;}.table1td.title{height:28px;color:#fff;background-color:#6AB6B6;font-weight:bold;font-size:20px;text-align: center;}.table1tr.colname{font-size: 14px;font-weight: bold;* .nobd_table td{border: none;}style><script type="text/javascript">function goback({}script>head><body><div align="center"style="padding-top: 30px;" id="add"><form action="UpdateUserAction"method="post"><table class="table1"width="50%"><tr><td colspan="2"class="title">user信息填写td>tr><tr><td>院系td><td><input type="text"name="yx"id="yx"value="${userBean.yx }"><input type="hidden"name="id"value="${userBean.id }">td>tr><tr><td>专业td><td><input type="text"name="zy"id="zy"value="${userBean.zy }">td> tr><tr><td>年龄td><td><input type="text"name="age"id="age"value="${userBean.age }"> td><tr><td>电话td><td><input type="text"name="dh"id="dh"value="${userBean.dh }">td> tr><tr><td>QQ td><td><input type="text"name="qq"id="qq"value="${userBean.qq }">td> tr><tr><td>行别td><td><c:set value="男"var="sexs"> c:set><c:if test="${userBean.sex eq sexs }"><input type="radio"name="sex"value="男"checked="checked">男<input type="radio"name="sex"value="女">女c:if><c:if test="${userBean.sex ne sexs }"><input type="radio"name="sex"value="男">男<input type="radio"checked="checked"name="sex"value="女">女c:if>td>tr><tr><td colspan="2"><input type="submit"value="提交"><inputtype="reset"value="重置"><input type="button"value="返回"onclick="Javascript:window.history.go(-1;">td>tr>table>form>div>body>html><%@ page language="java"import="java.util.*,erBean" pageEncoding="utf-8"%><%@ taglib prefix="c"uri="/jsp/jstl/core"%><%String path = request.getContextPath(;String basePath =request.getScheme(+"://"+request.getServerName(+":"+request.getServerPo rt(+path+"/";%>DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html><head><base href="<%=basePath%>"><title>My JSP 'userList.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"><style type="text/css">.table1{margin:0 auto;border-collapse: collapse;}.table1td{padding: 0px;height:25px;border:1px solid #6AB6B6;text-align:center;font-family:"微软雅黑";font-size:12px;background-color:#EAFEFE;}.table1td.title{height:28px;color:#fff;background-color:#6AB6B6;font-weight:bold;font-size:20px;text-align: center;}.table1tr.colname{font-size: 14px;font-weight: bold;}* .nobd_table td{border: none;}style><script type="text/javascript">function viewList({document.getElementById('list'.style.display= ''; document.getElementById('add'.style.display= 'none'; }function viewAdd({document.getElementById('list'.style.display= 'none'; document.getElementById('add'.style.display= '';}script>head><body onload="viewList("><div align="center"style="padding-top: 30px;" id="list"><table width="70%"class="table1"><tr><td colspan="8"class="title">user表列表信息<input type="button" value="增加"onclick="viewAdd(">td>tr><tr><td>序号td><td>姓名td><td>院系td><td>专业td><td>年龄td><td>电话td><td>QQ td><td>性别td><td>操作td>tr><c:forEach var="bean"items="${UserList }" ><tr><td>${bean.id }td><td>${ }td><td>${bean.yx }td><td>${bean.zy }td><td>${bean.age }td><td>${bean.dh }td><td>${bean.qq }td><td>${bean.sex }td><td><a href="SelectOneUser?id=${bean.id}">修改a><a href="DeleteUserById?id=${bean.id}">删除a>td>tr>c:forEach>table>div><div align="center"style="padding-top: 30px;" id = "add"> <form action="InsertUserAction"method="post"><table class="table1"width="50%"><tr><td colspan="2"class="title">user信息填写td>tr><td>院系td><td><input type="text"name="yx"id="yx">td>tr><tr><td>姓名td><td><input type="text"name="yx"id="name">td>tr><tr><td>专业td><td><input type="text"name="zy"id="zy">td>tr><tr><td>年龄td><td><input type="text"name="age"id="age">td>tr><tr><td>电话td><td><input type="text"name="dh"id="dh">td>tr><tr><td>QQ td><td><input type="text"name="qq"id="qq">td>tr><tr><td>行别td><td><input type="radio"name="sex"value="男"checked="checked">男<input type="radio"name="sex"value="女">女td>。

JSP+Servlet+Ajax实现用户增删改查的例子

JSP+Servlet+Ajax实现用户增删改查的例子

JSP+Servlet+Ajax实现⽤户增删改查的例⼦⼀、数据库设计⽤户表User已有的测试数据⼆、Java代码编写Java EE的架构⼀般分为以下五层:①.Domain②.DAO③.Service④.Controller⑤.View这⾥的项⽬结构如下:使⽤的环境为:JDK1.8+Servlet3.0+Tomcat8.0前端统⼀使⽤Ajax⽅式和JSON数据格式向后端发送请求及数据,后端统⼀返回JSON数据格式的信息1.Domain层1package domain;23import java.util.Date;45public class User {67public User() {89 }1011private Integer id;1213private String account;1415private String password;1617private String name;1819private String info;2021private Date createTime;2223private Date modifiedTime;2425public Integer getId() {26return id;27 }2829public void setId(Integer id) {30this.id = id;31 }3233public String getAccount() {34return account;35 }3637public void setAccount(String account) {38this.account = account;39 }4041public String getPassword() {42return password;43 }4445public void setPassword(String password) {46this.password = password;47 }4849public String getName() {50return name;51 }5253public void setName(String name) { = name;55 }5657public String getInfo() {58return info;59 }6061public void setInfo(String info) { = info;63 }6465public Date getCreateTime() {66return createTime;67 }6869public void setCreateTime(Date createTime) {70this.createTime = createTime;71 }7273public Date getModifiedTime() {74return modifiedTime;75 }7677public void setModifiedTime(Date modifiedTime) { 78this.modifiedTime = modifiedTime;82public String toString() {83return "User [id=" + id + ", account=" + account + ", password=" + password + ", name=" + name + ", info="84 + info + ", createTime=" + createTime + ", modifiedTime=" + modifiedTime + "]";85 }8687 }User.java2.Dao层1package dao;23import java.util.List;45import er;67public interface UserDao {89/** 显⽰所有⽤户 */10public List<User> listAll();1112/** 添加⼀个⽤户 */13public boolean add(User user);1415/** 根据id删除⼀个⽤户 */16public boolean deleteById(Integer id);1718/** 更新⼀个⽤户 */19public boolean update(User user);2021/** 根据id查找⼀个⽤户 */22public User getById(Integer id);2324 }UserDao.java1package dao.impl;23import java.sql.Connection;4import java.sql.PreparedStatement;5import java.sql.ResultSet;6import java.sql.SQLException;7import java.util.ArrayList;8import java.util.List;910import erDao;11import er;12import util.DBUtil;1314public class UserDaoImpl implements UserDao {1516 @Override17public List<User> listAll() {18 List<User> users = new ArrayList<User>();19 Connection conn = DBUtil.getConnection();20 String sql = "select * from user";21try {22 PreparedStatement pst = conn.prepareStatement(sql);23 ResultSet rst = pst.executeQuery();24while (rst.next()) {25 User user = new User();26 user.setId(rst.getInt("id"));27 user.setAccount(rst.getString("account"));28 user.setPassword(rst.getString("password"));29 user.setName(rst.getString("name"));30 user.setInfo(rst.getString("info"));31 user.setCreateTime(rst.getTimestamp("gmt_create"));32 user.setModifiedTime(rst.getTimestamp("gmt_modified"));33 users.add(user);34 }35 rst.close();36 pst.close();37 } catch (SQLException e) {38 e.printStackTrace();39 }40return users;44public boolean add(User user) {45 Connection conn = DBUtil.getConnection();46 String sql = "insert into user(account, password, name, info) value (?, ?, ?, ?)";47try {48 PreparedStatement pst = conn.prepareStatement(sql);49 pst.setString(1, user.getAccount());50 pst.setString(2, user.getPassword());51 pst.setString(3, user.getName());52 pst.setString(4, user.getInfo());53int count = pst.executeUpdate();54 pst.close();55return count > 0 ? true : false;56 } catch (SQLException e) {57 e.printStackTrace();58 }59return false;60 }6162 @Override63public boolean deleteById(Integer id) {64 Connection conn = DBUtil.getConnection();65 String sql = "delete from user where id = ?";66try {67 PreparedStatement pst = conn.prepareStatement(sql);68 pst.setInt(1, id);69int count = pst.executeUpdate();70 pst.close();71return count > 0 ? true : false;72 } catch (SQLException e) {73 e.printStackTrace();74 }75return false;76 }7778 @Override79public boolean update(User user) {80 Connection conn = DBUtil.getConnection();81 String sql = "update user set account = ?, password = ?, name = ?, info = ? where id = ?"; 82try {83 PreparedStatement pst = conn.prepareStatement(sql);84 pst.setString(1, user.getAccount());85 pst.setString(2, user.getPassword());86 pst.setString(3, user.getName());87 pst.setString(4, user.getInfo());88 pst.setInt(5, user.getId());89int count = pst.executeUpdate();90 pst.close();91return count > 0 ? true : false;92 } catch (SQLException e) {93 e.printStackTrace();94 }95return false;96 }9798 @Override99public User getById(Integer id) {100 User user = new User();101 Connection conn = DBUtil.getConnection();102 String sql = "select * from user where id = ?";103try {104 PreparedStatement pst = conn.prepareStatement(sql);105 pst.setInt(1, id);;106 ResultSet rst = pst.executeQuery();107while (rst.next()) {108 user.setId(rst.getInt("id"));109 user.setAccount(rst.getString("account"));110 user.setPassword(rst.getString("password"));111 user.setName(rst.getString("name"));112 user.setInfo(rst.getString("info"));113 user.setCreateTime(rst.getTimestamp("gmt_create"));114 user.setModifiedTime(rst.getTimestamp("gmt_modified"));115 }116 rst.close();117 pst.close();118 } catch (SQLException e) {119 e.printStackTrace();120 }121return user;122 }123124 }UserDaoImpl.java3.Service层1package service;23import java.util.List;45import er;67public interface UserService {89/** 显⽰所有⽤户 */10public List<User> listAll();1112/** 添加⼀个⽤户 */13public boolean add(User user);1415/** 根据id删除⼀个⽤户 */16public boolean deleteById(Integer id);1718/** 更新⼀个⽤户 */19public boolean update(User user);2021/** 根据id查找⼀个⽤户 */22public User getById(Integer id);2324 }UserService.java1package service.impl;23import java.util.List;45import erDao;6import erDaoImpl;7import er;8import erService;910public class UserServiceImpl implements UserService { 1112 @Override13public List<User> listAll() {14 UserDao userDao = new UserDaoImpl();15return userDao.listAll();16 }1718 @Override19public boolean add(User user) {20 UserDao userDao = new UserDaoImpl();21return userDao.add(user);22 }2324 @Override25public boolean deleteById(Integer id) {26 UserDao userDao = new UserDaoImpl();27return userDao.deleteById(id);28 }2930 @Override31public boolean update(User user) {32 UserDao userDao = new UserDaoImpl();33return userDao.update(user);34 }3536 @Override37public User getById(Integer id) {38 UserDao userDao = new UserDaoImpl();39return userDao.getById(id);40 }4142 }UserServiceImpl.java4.Controller层1package controller;3import java.io.IOException;4import java.util.List;56import javax.servlet.ServletException;7import javax.servlet.annotation.WebServlet;8import javax.servlet.http.HttpServlet;9import javax.servlet.http.HttpServletRequest;10import javax.servlet.http.HttpServletResponse;1112import er;13import net.sf.json.JSONArray;14import net.sf.json.JSONObject;15import erService;16import erServiceImpl;17import util.JSONUtil;1819 @WebServlet("/UserServlet")20public class UserServlet extends HttpServlet {2122private static final long serialVersionUID = 1L;2324public UserServlet() {25super();26 }2728protected void doGet(HttpServletRequest request, HttpServletResponse response) 29throws ServletException, IOException {30// 设置返回编码格式,解决中⽂乱码31 response.setCharacterEncoding("utf-8");3233// 根据action的值来执⾏不同的动作,例如显⽰所有⽤户或显⽰单个⽤户34 String action = request.getParameter("action");3536// 显⽰所有⽤户37if (action.equals("listAll")) {38 UserService userService = new UserServiceImpl();39 List<User> users = userService.listAll();4041// 返回JSON数据格式42 JSONArray jsonArr = JSONArray.fromObject(users);43 JSONObject jsonObjOut = new JSONObject();44 jsonObjOut.put("users", jsonArr);45 JSONUtil.returnJSON(request, response, jsonObjOut);46 }4748// 显⽰单个⽤户49if (action.equals("getById")) {50int id = Integer.parseInt(request.getParameter("id"));51 UserService userService = new UserServiceImpl();52 User user = userService.getById(id);5354// 返回JSON数据格式55 JSONObject jsonObjOut = new JSONObject();56 jsonObjOut.put("user", user);57 JSONUtil.returnJSON(request, response, jsonObjOut);58 }59 }6061protected void doPost(HttpServletRequest request, HttpServletResponse response) 62throws ServletException, IOException {63// 获取JSON数据64 JSONObject jsonObjIn = JSONUtil.getJSON(request, response);6566 User user = new User();67 user.setAccount(jsonObjIn.getString("account"));68 user.setPassword(jsonObjIn.getString("password"));69 user.setName(jsonObjIn.getString("name"));70 user.setInfo(jsonObjIn.getString("info"));7172 UserService userService = new UserServiceImpl();73boolean isSuccess = userService.add(user);7475// 返回JSON数据格式76 JSONObject jsonObjOut = new JSONObject();77 jsonObjOut.put("isSuccess", isSuccess);78 JSONUtil.returnJSON(request, response, jsonObjOut);79 }8081protected void doDelete(HttpServletRequest request, HttpServletResponse response) 82throws ServletException, IOException {83// 获取JSON数据84 JSONObject jsonObjIn = JSONUtil.getJSON(request, response);85int id = jsonObjIn.getInt("id");87 UserService userService = new UserServiceImpl();88boolean isSuccess = userService.deleteById(id);8990// 返回JSON数据格式91 JSONObject jsonObjOut = new JSONObject();92 jsonObjOut.put("isSuccess", isSuccess);93 JSONUtil.returnJSON(request, response, jsonObjOut);9495 }9697protected void doPut(HttpServletRequest request, HttpServletResponse response)98throws ServletException, IOException {99// 获取JSON数据100 JSONObject jsonObjIn = JSONUtil.getJSON(request, response);101102 User user = new User();103 user.setId(jsonObjIn.getInt("id"));104 user.setAccount(jsonObjIn.getString("account"));105 user.setPassword(jsonObjIn.getString("password"));106 user.setName(jsonObjIn.getString("name"));107 user.setInfo(jsonObjIn.getString("info"));108109 UserService userService = new UserServiceImpl();110boolean isSuccess = userService.update(user);111112// 返回JSON数据格式113 JSONObject jsonObjOut = new JSONObject();114 jsonObjOut.put("isSuccess", isSuccess);115 JSONUtil.returnJSON(request, response, jsonObjOut);116 }117118 }UserServlet.java5.View层1 <%@ page language="java" contentType="text/html;charset=UTF-8" pageEncoding="UTF-8"%>2 <% String basePath = request.getScheme() + "://" + request.getServerName() + ":"3 + request.getServerPort() + request.getContextPath() + "/"; %>45<!Doctype html>6<html>7<head>8<base href="<%=basePath%>">9<title>⽤户管理</title>10<meta charset="utf-8">11<link rel="stylesheet" href="static/css/style.css">12<link rel="stylesheet" href="static/js/jquery-ui/jquery-ui.min.css">13<script src="static/js/jquery-3.3.1.min.js"></script>14<script src="static/js/jquery.serializejson.min.js"></script>15<script src="static/js/jquery-ui/jquery-ui.min.js"></script>16</head>17<body>18<!-- ⽤户列表 -->19<div class="tbl-title">⽤户列表</div>20<button onclick="showAddUserModal()">添加新的⽤户</button>21<table id="users" class="tbl-list">22<thead>23<tr>24<th>账户</th>25<th>密码</th>26<th>⽤户名</th>27<th>信息</th>28<th>操作</th>29</tr>30</thead>31<tbody>32</tbody>33</table>3435<!-- 添加⽤户模态框 -->36<div id="add-user-modal" title="添加⽤户" style="display:none;">37<form id="add-user-form">38<table class="modal-tbl">39<tr><td>账户</td><td><input type="text" name="account"></td></tr>40<tr><td>密码</td><td><input type="password" name="password"></td></tr>41<tr><td>姓名</td><td><input type="text" name="name"></td></tr>42<tr><td>信息</td><td><input type="text" name="info"></td></tr>43</table>44</form>45</div>4647<!--删除⽤户对话模态框 -->48<div id="delete-user-modal" title="删除⽤户" style="display:none;">49<p>确定删除该⽤户吗?</p>50</div>5152<!-- 更新⽤户模态框 -->53<div id="update-user-modal" title="更新⽤户" style="display:none;">54<form id="update-user-form">55<table class="modal-tbl">56<tr style="display: none"><td>ID</td><td><input type="text" name="id"></td></tr>57<tr><td>账户</td><td><input type="text" name="account"></td></tr>58<tr><td>密码</td><td><input type="password" name="password"></td></tr>59<tr><td>姓名</td><td><input type="text" name="name"></td></tr>60<tr><td>信息</td><td><input type="text" name="info"></td></tr>61</table>62</form>63</div>6465<!-- 提⽰信息模态框 -->66<div id="msg-modal" title="" style="display:none">67<p></p>68</div>6970<script>71// 开始72 $(function() {73 listAllUser();74 });7576// 显⽰所有⽤户77function listAllUser() {78 $.ajax({79 type: "GET",80 url: "UserServlet?action=listAll",81 dataType: "json",82 success: function(data) {83 $("#users tbody").empty(); // 每次载⼊前先清空显⽰区域,防⽌数据重复显⽰84var users = ers;85for (var i in users) {86var user = users[i];87var userStr = JSON.stringify(user);88 $("#users tbody").append('<tr><td>' + user.account + '</td>'89 + '<td>' + user.password + '</td>'90 + '<td>' + + '</td>'91 + '<td>' + + '</td>'92 + '<td><button onclick=\'showUpdateUserModal(' + userStr + ')\'>更新</button>&nbsp;'93 + '<button onclick="deleteUser(' + user.id + ')">删除</button></td></tr>');94 }95 },96 error: function() {97 console.log("ajax error");98 }99 });100 }101102// 显⽰添加⽤户模态框103function showAddUserModal() {104 $("#add-user-form")[0].reset(); // 每次载⼊前先清空表单,防⽌显⽰之前的信息105 $("#add-user-modal").dialog({106 resizable: false,107 modal: true,108 buttons: {109 "提交": function() {110 addUser();111 },112 "取消": function() {113 $(this).dialog("close");114 },115 },116 });117 }118119// 添加⽤户120function addUser() {121// 获取序列化表单信息122var user = $("#add-user-form").serializeJSON();123var userStr = JSON.stringify(user);124125 $.ajax({126 type: "POST",127 url: "UserServlet",128 data: userStr,129 dataType: "json",130 success: function(data) {131if (data.isSuccess) {132 $("#add-user-modal").dialog("close");133 showMsg('添加成功!');134 listAllUser();135 } else {136 $("#add-user-modal").dialog("close");137 showMsg('添加失败!');138 listAllUser();139 }140 },141 error: function() {142 console.log("ajax error");143 },144 });145 }146147// 删除⽤户148function deleteUser(id) {149// 将id封装为JSON格式数据150var data = {};151 data.id = id;152var dataStr = JSON.stringify(data);153// 显⽰删除⽤户模态框154 $("#delete-user-modal").dialog({155 resizable: false,156 modal: true,157 buttons: {158 "确认": function() {159 $.ajax({160 type: "DELETE",161 url: "UserServlet",162 data: dataStr,163 dataType: "json",164 success: function(data) {165if (data.isSuccess) {166 $("#delete-user-modal").dialog("close");167 showMsg('删除成功!');168 listAllUser();169 } else {170 $("#delete-user-modal").dialog("close");171 showMsg('删除失败!');172 listAllUser();173 }174 },175 error: function() {176 console.log("ajax error");177 },178 });179 },180 "取消": function() {181 $(this).dialog("close");182 },183 },184 });185 }186187//显⽰更新⽤户模态框188function showUpdateUserModal(user) {189 $("#update-user-form")[0].reset(); // 每次载⼊前先清空表单,防⽌显⽰之前的信息190// 表单赋值191 $("#update-user-form input[name='id']").val(user.id);192 $("#update-user-form input[name='account']").val(user.account);193 $("#update-user-form input[name='password']").val(user.password);194 $("#update-user-form input[name='name']").val();195 $("#update-user-form input[name='info']").val();196197 $("#update-user-modal").dialog({198 resizable: false,199 modal: true,200 buttons: {201 "提交": function() {202 updateUser();203 },204 "取消": function() {205 $(this).dialog("close");206 },207 },208 });209 }210211// 更新⽤户212function updateUser() {213// 获取序列化表单信息214var user = $("#update-user-form").serializeJSON();215var userStr = JSON.stringify(user);216217 $.ajax({218 type: "PUT",219 url: "UserServlet",220 data: userStr,221 contentType: 'application/json;charset=utf-8',222 dataType: "json",223 success: function(data) {224if (data.isSuccess) {225 $("#update-user-modal").dialog("close");226 showMsg('更新成功!');227 listAllUser();228 } else {229 $("#update-user-modal").dialog("close");230 showMsg('更新失败!');231 listAllUser();232 }233 },234 error: function() {235 console.log("ajax error");236 },237 });238 }239240//显⽰提⽰信息241function showMsg(text) {242 $("#msg-modal p").text(''); // 每次载⼊前先清空显⽰区域,防⽌显⽰之前的信息243 $("#msg-modal p").text(text);244 $("#msg-modal").dialog({245 modal: true,246 });247// 2s后消失248 setTimeout(function() {249 $("#msg-modal").dialog("close")250 },2000);251 }252</script>253</body>254</html>admin_user.jsp1@charset "utf-8";23.tbl-title {4 margin: 10px 0;5 font-size: 24px;6 }78.tbl-list {9 margin: 10px 0;10 border: 1px solid #000000;11 border-collapse: collapse;12 }1314.tbl-list th, .tbl-list td {15 padding: 5px;16 border: 1px solid #000000;17 }1819.modal-tbl{}style.cssjs相关下载:链接:提取码:ubt06.⼯具类1package util;23import java.sql.Connection;4import java.sql.DriverManager;56public class DBUtil {78private static String Driver = "com.mysql.jdbc.Driver";9private static String url = "jdbc:mysql://localhost:3306/demo?useUnicode=true&characterEncoding=utf8";10private static String user = "root";11private static String psd = "123456";12private static Connection conn = null;1314// 连接数据库15public static Connection getConnection() {16if (conn == null) {17try {18 Class.forName(Driver);19 conn = DriverManager.getConnection(url, user, psd);20 System.out.println("开始数据库连接");21 } catch (Exception e) {22 e.printStackTrace();23 }24 }25return conn;26 }2728// 关闭数据库连接29public static void CloseConnection() {30if (conn != null) {31try {32 conn.close();33 System.out.println("关闭数据库连接");34 } catch (Exception e) {35 e.printStackTrace();36 }37 }38 }39 }DBUtil.java1package util;23import java.io.BufferedReader;4import java.io.IOException;5import java.io.PrintWriter;67import javax.servlet.ServletException;8import javax.servlet.http.HttpServletRequest;9import javax.servlet.http.HttpServletResponse;1011import net.sf.json.JSONObject;1213public class JSONUtil {1415// 从输⼊流中获取JSON数据16public static JSONObject getJSON (HttpServletRequest request, HttpServletResponse response)17throws ServletException, IOException {18// 输⼊流19 StringBuffer sb = new StringBuffer();20 String line = null;21 BufferedReader br = request.getReader();22while ((line = br.readLine()) != null) {23 sb.append(line);24 }25// 返回JSONObject26 String jsonStr = sb.toString();27 JSONObject jsonObj = JSONObject.fromObject(jsonStr);28return jsonObj;29 }3031// 返回JSON格式的数据32public static void returnJSON (HttpServletRequest request, HttpServletResponse response, JSONObject jsonObj) 33throws ServletException, IOException {34// 设置编码格式,解决乱码35 response.setCharacterEncoding("utf-8"); 3637 PrintWriter out = response.getWriter() ;38 out.write(jsonObj.toString());39 out.flush();40 out.close();41 }4243 }JSONUtil.java7.所需要的jar百度云下载地址:提取码:f1gu三、实现效果1.显⽰所有⽤户2.添加⽤户3.修改⽤户4.删除⽤户。

Struts2hibernate实现用户登录和增删改查案例

Struts2hibernate实现用户登录和增删改查案例

Struts2+hibernate 实现用户登录和增删改查案例Struts2+hibernate 实现用户登录和增删改查案例开发工具MyEclipse 10.7.1 创建一个项目web 项目project 。

部署好Struts2 的开发环境:1、引入需要的类库文件jar2、添加struts2 的配置文件struts.xml //src 路径:classespath:3、在web.xml 添加启动struts2 MVC 框架的过滤器4、添加Hibernate 所依赖的jar 文件(注意:如果Hibernate 添加的jar 文件与struts2 添加jar 文件名称完全一致(只需其中之一(版本不一致保留高本版5、同样添加hibernate 的配置文件Classespath: src 路径下面6、需要添加对应数据库操作的驱动文件jar在此基础上对admin 这个类完成增删改查的操作。

在src 下搭建开发框架,如图所示:struts.xml 文件:xml version="1.0" encoding="UTF-8"?>DOCTYPE struts PUBLIC"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN""/dtds/struts-2.3.dtd" ><struts ><include file="struts-admin.xml"/>struts >struts-admin.xml 文件:xml version="1.0" encoding="UTF-8"?>DOCTYPE struts PUBLIC"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN""/dtds/struts-2.3.dtd" ><package name="admin" namespace="/csdn" extends="struts-default"><action name="adminLogin" class="www.csdn.project.action.AdminAction" method="login"><result name="success">/manager/index.jsp result ><result name="login">/index.jsp result >action ><action name="adminlist" class="www.csdn.project.action.AdminAction" method="getAllObjects"><result name="success">/manager/admin/admin_list.jsp result >action ><action name="getAdminById" class="www.csdn.project.action.AdminAction" method="getO bjectById">< result name="success">/manager/admin/admin_sing.jsp result >action ><action name="adminInsert" class="www.csdn.project.action.AdminAction" method="saveO bject"><result type="redirectAction"><param name="actionName">adminlist.action param >result >action ><action name="deleteAdminById" class="www.csdn.project.action.AdminAction" method="de leteObjectById">< result name="success" type="redirectAction">< param name="actionName">adminlist.action param >result > action ><action name="findAdminById" class="www.csdn.project.action.AdminAction" method="findA dminById">< result name="success">/manager/admin/admin_update.jsp result >action ><action name="updateAdmin" class="www.csdn.project.action.AdminAction" method="updat eObject"> < result name="success" type="redirectAction">< param name="actionName">adminlist.action param >result >package >struts >hibernate.cfg.xml 文件:xml version="1.0" encoding="UTF-8"?>DOCTYPE hibernate-configuration PUBLIC"-//Hibernate/Hibernate Configuration DTD 3.0//EN""/dtd/hibernate-configuration-3.0.dtd" > <hibernate-configuration ><session-factory ><property name="myeclipse.connection.profile">localhost property ><property name="connection.url"> jdbc:mysql://localhost:3306/bookstore property ><property name="ername">root property ><property name="connection.password">root property ><property name="connection.driver_class"> com.mysql.jdbc.Driverproperty ><property name="dialect">org.hibernate.dialect.MySQLDialectproperty ><mapping resource="www/csdn/project/domain/Admin.hbm.xml" /> session-factory >hibernate-configuration >web.xml 文件:xml version="1.0" encoding="UTF-8"?><web-app version="2.5"xmlns="/xml/ns/javaee" xmlns:xsi="/2001/XMLSchema-instance" xsi:schemaLocation="/xml/ns/javaee /xml/ns/javaee/web-app_2_5.xsd"><filter >< filter-name >struts2 filter-name >< filter-class >org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter class > filter-<filter-mapping >< filter-name >struts2 filter-name >< url-pattern >/* url-pattern >filter-mapping >< welcome-file-list >< welcome-file >index.jsp welcome-file >welcome-file-list >web-app >首先,domain 层( www.csdn.project.domain )的编写;Admin.java 文件:package www.csdn.project.domain;public class Admin implements java.io.Serializable {*/private static final long serialVersionUID = 1L;private Integer adminId;private String adminName;private String adminPassword;public Admin( {}public Admin(String adminName, String adminPassword { this.adminName = adminName; this.adminPassword = adminPassword;}public Admin(String adminName, String adminPassword, String adminEmail { this.adminName = adminName;this.adminPassword = adminPassword;}public Integer getAdminId( {return this.adminId;}public void setAdminId(Integer adminId {this.adminId = adminId;}public String getAdminName( {return this.adminName;}public void setAdminName(String adminName { this.adminName = adminName;public String getAdminPassword( { return this.adminPassword;}public void setAdminPassword(String adminPassword { this.adminPassword = adminPassword; }@Overridepublic String toString( {return "Admin [adminId=" + adminId+ ", adminName=" + adminName + ", adminPassword="+ adminPassword + "]";}}Admin.hbm.xml 配置文件;xml version="1.0" encoding="utf-8"?>DOCTYP Ehibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "/hibernate-mapping-3.0.dtd" > <hibernate-mapping > < class name="www.csdn.project.domain.Admin" table="admin" catalog="bookstore"> < id name="adminId" type="ng.Integer">< column name="adminId" />< generator class="identity" />id >< property name="adminName" type="ng.String">< column name="adminName" length="20" not-null="true" unique="true" /> property > < property name="adminPassword" type="ng.String">< column name="adminPassword" length="10" not-null="true" />property >class >hibernate-mapping >dao 层( www.csdn.project.dao )的编写;AdminDAO.java 文件:(封装了查看所有用户信息的方法)package www.csdn.project.dao;import java.util.List;import www.csdn.project.domain.Admin;public interface AdminDAO extends BaseDAO {public Admin login(String adminName,String adminPass;public Admin findById(Integer id;public List findAdminPage(int nowPage,int pageSize;}然后,BaseDAO.java 文件:(这里封装了对用户进行增删改查的方法) package www.csdn.project.dao;import java.util.List;public interface BaseDAO {public List getAllObjects(Class entityClass;public T getObjectById(Class entityClass,PK id;public T loadObjectById(Class entityClass,PK id;public void saveObject(T entity;public void deleteObject(T entity;public void deleteObjectById(PK id;public void updateObject(T entity;}下面是实现两个类中的方法的AdminDAOImpl.java 文件:package www.csdn.project.dao;import java.util.List;import www.csdn.project.domain.Admin;import www.csdn.project.util.BaseHibernateDAO;import www.csdn.project.util.HiberSessionFactory;public class AdminDAOImpl extends BaseHibernateDAO implements AdminDAO {public Admin login(String adminName, String adminPass {Admin entity=null;try{entity = (Admin getSession(.createQuery("from Admin a where a.adminName=:adminName and a.adminPassword=:adminPassword" .setParameter("adminName", adminName.setParameter("adminPassword", adminPass.uniqueResult(;}catch (RuntimeException e {HiberSessionFactory.closeSession(;}return entity;}public List findAdminPage(int nowPage, int pageSize {return null;}public Admin findById(Integer id {return null;}@SuppressWarnings("unchecked"public List getAllObjects(Class entityClass {List entities=null;try{entities = getSession(.createCriteria(entityClass.list(;}catch (RuntimeException e {HiberSessionFactory.closeSession(;}return entities;}public Admin getObjectById(Class entityClass, Integer id { Admin entities=null;try{entities=(Admin getSession(.get(entityClass, id;}catch (RuntimeException e {HiberSessionFactory.closeSession(;}return entities;}public Admin loadObjectById(Class entityClass, Integer id { Admin entities=null;try{entities=(Admin getSession(.load(entityClass, id;}catch (RuntimeException e {HiberSessionFactory.closeSession(;}return entities;}public void saveObject(Admin entity { getSession(.save(entity;}public void deleteObject(Admin entity { getSession(.delete(entity;}public void deleteObjectById(Integer id { //this.getSession(.delete(this.getObjectById(Admin.class, id; } public void updateObject(Admin entity { getSession(.update(entity;}}这样dao 层完成了其作用。

servlet和jsp的增、删、改、查(精)

servlet和jsp的增、删、改、查(精)

昆明理工大学信息工程与自动化学院学生实验报告( 2013—2014学年第二学期)课程名称:JAVA EE技术开课实验室:信自楼444 2013 年 10 月 19 日年级、专业、班计科112学号201110405214姓名周英明成绩实验项目名称Servlet与JSP编程指导教师卫守林教师评语教师签名:年月日一、实验目的1、掌握Servlet的请求和响应的编程2、掌握Servlet与JSP的差异3、掌握Servlet与JSP的数据交互4、完成用户管理功能二.实验内容完成用户的增加、删除、修改、列表功能,要求页面展示的部分需要用JSP完成,业务逻辑由Servlet完成。

三、步骤及具体实施(一、视图:1.用户登录页面:2.用户管理页面:3.增加用户:4.修改:(二)javaeebean1.创建数据库表格:/****** Script for SelectTopNRows command from SSMS ******/ SELECT TOP 1000 [id],[name],[password],[sex],[age]FROM[SQLdata].[dbo].[student]order by id2.用javaee.bean封装用户信息:package javaee.bean;/*** @author help*封装一条信息的所有属性*/public class javabean {private int id;private String name;private String password;private String sex;private int age;public int getId( {return id;}public void setId(int id {this.id = id;}public String getName( {return name;}public void setName(String name { = name;}public String getPassword( {return password;}public void setPassword(String password { this.password = password;}public String getSex( {return sex;}public void setSex(String sex { this.sex = sex;}public int getAge( {return age;}public void setAge(int age {this.age = age;}}3.用javaee.bean封装用户信息:package javaee.bean;import java.sql.Connection;import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet;import java.sql.SQLException; import java.util.ArrayList;import java.util.List;/*** @author help*操作数据库的方法*/public class SqlBean {Connection con;PreparedStatement pre;ResultSet rs;public SqlBean({if(rs!=null;{try {Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver";} catch (ClassNotFoundException e {e.printStackTrace(;}try {con=DriverManager.getConnection("jdbc:sqlserver://localhost:14 33;DatabaseName=SQLdata","sa","123581321";} catch (SQLException e {e.printStackTrace(;}}}/*** @author help**插入新的一条记录* @return*/public int getinsertuser(String sql,javabean jBean {int count =0;try {pre = con.prepareStatement(sql;pre.setInt(1,jBean.getId(;pre.setString(2,jBean.getName(;pre.setString(3,jBean.getPassword(;pre.setString(4,jBean.getSex(;pre.setInt(5,jBean.getAge(;count=pre.executeUpdate(;} catch (SQLException e {e.printStackTrace(;}finally{try {pre.close(;con.close(;} catch (SQLException e {// TODO Auto-generated catch blocke.printStackTrace(;}}return count;/*** @author help**删除一条记录* @return*/public int getdeleteuser(String sql,int id {int count =0;try {pre = con.prepareStatement(sql;pre.setInt(1, id;count=pre.executeUpdate(;} catch (SQLException e {e.printStackTrace(;}finally{try {pre.close(;con.close(;} catch (SQLException e {// TODO Auto-generated catch blocke.printStackTrace(;}return count;}/*** @author help**根据ID查询某一条记录* @return*/public javabean getsearchById(String sql,int id {javabean jBean = new javabean(;try {pre = con.prepareStatement(sql;pre.setInt(1, id;rs=pre.executeQuery(;while(rs.next({jBean.setId(rs.getInt("id";jBean.setName(rs.getString("name";jBean.setPassword(rs.getString("password"; jBean.setSex(rs.getString("sex";jBean.setAge(rs.getInt("age";}} catch (SQLException e{e.printStackTrace(;}return jBean;}/*** @author help**更新某一条记录* @return*/public int getupdateuser(String sql,javabean jBean {int count =0;try {pre = con.prepareStatement(sql;pre.setInt(5,jBean.getId(;pre.setString(1,jBean.getName(;pre.setString(2,jBean.getPassword(;pre.setString(3,jBean.getSex(;pre.setInt(4,jBean.getAge(;count = pre.executeUpdate(;} catch (SQLException e {// TODO Auto-generated catch blocke.printStackTrace(;}finally{try {pre.close(;con.close(;} catch (SQLException e {// TODO Auto-generated catch block e.printStackTrace(;}}return count;}/*** @author help**显示所有记录* @return*/public List getuserlist(String sql {List list = new ArrayList >( ;//获取prepareStatement对象try {pre = con.prepareStatement(sql;rs =pre.executeQuery(;while(rs.next({javabean jBean =new javabean(;jBean.setId(rs.getInt("id";jBean.setName(rs.getString("name";jBean.setPassword(rs.getString("password";jBean.setSex(rs.getString("sex";jBean.setAge(rs.getInt("age";list.add(jBean;}} catch (SQLException e {// TODO Auto-generated catch blocke.printStackTrace(;}finally{try {pre.close(;con.close(;} catch (SQLException e {// TODO Auto-generated catch blocke.printStackTrace(;}}return list;}}(三)servlet1. 验证码的生成CheckCodeGet.javapackage javaee;import java.io.IOException;import java.awt.*;import java.awt.image.*;import java.util.*;import javax.servlet.ServletConfig;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import com.sun.image.codec.jpeg.JPEGCodec;import com.sun.image.codec.jpeg.JPEGImageEncoder;//生成验证码@SuppressWarnings("restriction"public class CheckCodeGet extends HttpServlet{private static final long serialVersionUID = 1L;private final int TYPE_NUMBER = 0;private final int TYPE_LETTER = 1;private final int TYPE_MULTIPLE = 2;private int width;private int height;private int count;@SuppressWarnings("unused"private int type;private String validate_code;private Random random;private Font font;private int line;public void doGet(HttpServletRequest request, HttpServletResponse responsethrows ServletException, IOException{response.setHeader("Pragma","No-cache";response.setHeader("Cache-Control","no-cache";response.setDateHeader("Expires", 0;response.setContentType("image/jpeg";String reqCount = request.getParameter("count";String reqWidth = request.getParameter("width";String reqHeight = request.getParameter("height";String reqType = request.getParameter("type";if(reqCount!=null && reqCount!=""this.count = Integer.parseInt(reqCount;if(reqWidth!=null && reqWidth!=""this.width = Integer.parseInt(reqWidth;if(reqHeight!=null && reqHeight!=""this.height = Integer.parseInt(reqHeight;if(reqType!=null && reqType!=""this.type =Integer.parseInt(reqType;font = new Font("Courier New",Font.BOLD,width/count;BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB;Graphics g = image.getGraphics(;g.setColor(getRandColor(200,250;g.fillRect(0, 0, width, height;g.setColor(getRandColor(160,200;for (int i=0;i{int x = random.nextInt(width;int y = random.nextInt(height;int xl = random.nextInt(12;int yl = random.nextInt(12;g.drawLine(x,y,x+xl,y+yl;}g.setFont(font;validate_code = getValidateCode(count,1;request.getSession(.setAttribute("validate_code",valida te_code;for (int i=0;i{//调用函数出来的颜色相同,可能是因为种子太接近,所以只能直接生成g.setColor(newColor(20+random.nextInt(110,20+random.nextInt(110,20+random .nextInt(110;int x = (int(width/count*i;int y = (int((height+font.getSize(/2-5;g.drawString(String.valueOf(validate_code.charAt(i,x,y;}g.dispose(;//ImageIO.write(image, "JPEG",response.getOutputStream(;JPEGImageEncoder encoder =JPEGCodec.createJPEGEncoder(response.getOutputStream(;encoder.encode(image;}public void doPost(HttpServletRequest request, HttpServletResponse responsethrows ServletException, IOException{doGet(request,response;}public void init(ServletConfig config throws ServletException{super.init(config;width = 150;height = 50;count = 4;type = TYPE_NUMBER;random = new Random(;line = 200;}//private Color getRandColor(int from,int to{Random random = new Random(;if(to>255 from=255;if(to>255 to=255;int rang = Math.abs(to - from;int r=from+random.nextInt(rang;int g=from+random.nextInt(rang;int b=from+random.nextInt(rang;return new Color(r,g,b;}//取得验证码字符串private String getValidateCode(int size,int type {StringBuffer validate_code = new StringBuffer(; for(int i = 0; i < size; i++{validate_code.append(getOneChar(type;}return validate_code.toString(;}//根据验证码类型取得实际验证字符private String getOneChar(int type{String result = null;switch(type{case TYPE_NUMBER:result = String.valueOf(random.nextInt(10;break;case TYPE_LETTER:result = String.valueOf((char(random.nextInt(26+65; break;case TYPE_MULTIPLE:if(random.nextBoolean({result = String.valueOf(random.nextInt(10;}else{result = String.valueOf((char(random.nextInt(26+65; }break;default:result=null;break;}if(result==null{throw new NullPointerException("获取验证码出错";}return result;}}2. 删除用户deleteuser.javapackage javaee;import java.io.IOException;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import javaee.bean.SqlBean;public class deleteuser extends HttpServlet {private static final long serialVersionUID = 1L;public void doGet(HttpServletRequest request, HttpServletResponse responsethrows ServletException, IOException {response.setContentType("text/html";doPost(request,response;}public void doPost(HttpServletRequest request, HttpServletResponse responsethrows ServletException, IOException {response.setContentType("text/html";//获取超链接传来的数据String sId = request.getParameter("id";int id =Integer.parseInt(sId;System.out.println(id;//调用模型层删除方法String sql = "delete from student where id=?";SqlBean sBean = new SqlBean(;int count =sBean.getdeleteuser(sql, id;String url="";//System.out.println(count;if(count>0{url="userlist.jsp";}else{url ="error.jsp";request.setAttribute("error", "删除";}//转发request.getRequestDispatcher(url.forward(request, response;}}3. 增加用户insertuser.javapackage javaee;import java.io.IOException;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import javaee.bean.SqlBean;import javaee.bean.javabean;public class insertuser extends HttpServlet {private static final long serialVersionUID = 1L;public void doGet(HttpServletRequest request, HttpServletResponse responsethrows ServletException, IOException {response.setContentType("text/html";doPost(request,response;}public void doPost(HttpServletRequest request, HttpServletResponse responsethrows ServletException, IOException {response.setContentType("text/html";request.setCharacterEncoding("utf-8";response.setCharacterEncoding("utf-8";//获取前台页面数据String sid = request.getParameter("id";String name =request.getParameter("name";String password =request.getParameter("password";String sex =request.getParameter("sex";String sage = request.getParameter("age";int age =Integer.parseInt(sage;int id =Integer.parseInt(sid;//封装到JavaBean对象中去javabean jBean = new javabean(;jBean.setId(id;jBean.setName(name;jBean.setPassword(password;jBean.setSex(sex;jBean.setAge(age;//调用模型层String sql = "insert intostudent(id,name,password,sex,age values(?,?,?,?,?";SqlBean sBean = new SqlBean(;int count =sBean.getinsertuser(sql,jBean;@SuppressWarnings("unused"String url="";if(count>0{url="userlist.jsp";}else{url ="error.jsp";request.setAttribute("error", "";}//转发request.getRequestDispatcher("userlist.jsp".forward(req uest, response;}}4. 用户登录LoginActionsql.javapackage javaee;import java.io.IOException;import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.ResultSet;import javax.servlet.ServletConfig;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import javax.servlet.http.HttpSession;@SuppressWarnings("serial"public class LoginActionsql extends HttpServlet {/*** Constructor of the object.*/String driverName=null;String url=null;String user=null;String pass=null;public LoginActionsql( {super(;}/*** Destruction of the servlet. <br>*/public void destroy( {super.destroy(; // Just puts "destroy" string in log // Put your code here}public void doGet(HttpServletRequest request, HttpServletResponse responsethrows ServletException, IOException {doPost(request,response;}public void doPost(HttpServletRequest request, HttpServletResponse responsethrows ServletException, IOException {String id=request.getParameter("id";String password=request.getParameter("password"; String checkCode=request.getParameter("checkcode"; if(id!=null &&id.trim(.length(!=0&&password.trim(.length(!=0 {String sql="select * from student where id=? and password=?";Connection cn=null;boolean check=false;try{Class.forName(driverName;cn=DriverManager.getConnection(url, user, pass; PreparedStatement ps=cn.prepareStatement(sql;ps.setString(1,id;ps.setString(2,password;ResultSet rs=ps.executeQuery(;if(rs.next({System.out.println(id+password+checkCode;check=true;}rs.close(;ps.close(;}catch (Exception e{response.sendRedirect("login.jsp";return;}finally{try{cn.close(;}catch(Exception e{}}if (check{HttpSession session=request.getSession(true; session.setAttribute("name",id;session.setAttribute("password",password; response.sendRedirect("userlist.jsp"; System.out.println(id;return;}else{response.sendRedirect("login.jsp";return;}}}public void init(ServletConfig config throwsServletException {// Put your code heresuper.init(config;driverName=config.getInitParameter("driverName";url=config.getInitParameter("url";user=config.getInitParameter("user";pass=config.getInitParameter("pass";}}5、用户查询searchById.javapackage javaee;import java.io.IOException;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import javaee.bean.javabean;import javaee.bean.SqlBean;public class searchById extends HttpServlet {private static final long serialVersionUID = 1L;public void doGet(HttpServletRequest request,HttpServletResponse responsethrows ServletException, IOException {doPost(request,response;public void doPost(HttpServletRequest request, HttpServletResponse responsethrows ServletException, IOException {response.setContentType("text/html";request.setCharacterEncoding("utf-8";response.setCharacterEncoding("utf-8";//获取用户IDString sid = request.getParameter("id";int id =Integer.parseInt(sid;//System.out.println(id;String sql ="select * from student where id=?"; SqlBean sBean = new SqlBean(;javabean jBean = sBean.getsearchById(sql, id;//用户IDrequest.setAttribute("id",jBean.getId(;//用户姓名request.setAttribute("name",jBean.getName(;//用户密码request.setAttribute("password",jBean.getPassword(; //用户性别String sex="";String man="";String woman="";if(jBean.getSex(!=nullsex=jBean.getSex(.trim(;if(sex.equals("男"{man ="checked";}else{woman ="checked";}}request.setAttribute("man",man;request.setAttribute("woman",woman;//用户年龄request.setAttribute("age",jBean.getAge(;//转发request.getRequestDispatcher("updateuser.jsp".forward(reque st, response;}}6、用户修改updateuser.javapackage javaee;import java.io.IOException;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javaee.bean.javabean;import javaee.bean.SqlBean;public class updateuser extends HttpServlet { private static final long serialVersionUID = 1L; public void doGet(HttpServletRequest request, HttpServletResponse responsethrows ServletException, IOException {doPost(request,response;}public void doPost(HttpServletRequest request, HttpServletResponse responsethrows ServletException, IOException { response.setContentType("text/html";request.setCharacterEncoding("utf-8";response.setCharacterEncoding("utf-8";//获得前台表单信息String sid = request.getParameter("id";int id =Integer.parseInt(sid;System.out.println(id;String name =request.getParameter("name";String password =request.getParameter("password"; String sex =request.getParameter("sex";String sage = request.getParameter("age";int age =Integer.parseInt(sage;//封装到JavaBean对象中去javabean jBean = new javabean(;jBean.setId(id;jBean.setName(name;jBean.setPassword(password;jBean.setSex(sex;jBean.setAge(age;String sql ="update student setname=?,password=?,sex=?,age=? where id=?";SqlBean sBean = new SqlBean(;int count =sBean.getupdateuser(sql,jBean;@SuppressWarnings("unused"String url="";if(count>0{url="userlist.jsp";}else{url ="error.jsp";request.setAttribute("error", "更新";}request.getRequestDispatcher("userlist.jsp".forward(request, response;}}(四)、jsp1、错误页面:error.jsp<%@page language="java"import="java.util.*"pageEncoding="UTF-8"%><%String path = request.getContextPath(;String basePath =request.getScheme(+"://"+request.getServerName(+":"+request.getSe rverPort(+path+"/";%>DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>出错啦!!!title>head><body>对不起!您<%=request.getAttribute("error"%>失败body>html>2、登录页面:login.jsp<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>String path = request.getContextPath(;String basePath =request.getScheme(+"://"+request.getServerName(+":"+request.getSe rverPort(+path+"/";%>DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html><head><base href="<%=basePath%>"><title>用户登录页面title><script type="text/javascript">function reImg({var img = document.getElementById("CheckCodeGet";img.src = "CheckCodeGet?rnd=" + Math.random(;}script>head><body><FONT SIZE="5"COLOR="#006699">用户登录FONT><form action="LoginActionsql.do"method="post"><table><tr><td>用户名:td><td><input type="text"name="id"/> td>tr><td>密码:td><td><input type="password"name="password"/> td>tr><tr><td>验证码:td><td><input type="text"name="checkcode"/> td><td><img id="guestbookCaptcha"onclick="this.src='CheckCodeGet?d='+new Date("alt=""src="CheckCodeGet?"width="70"/><a style="text-decoration: none;"onclick="document.getElementById('guestbookCaptcha'.src= 'CheckCodeGet?d='+new Date(" href="#">看不清?a>td>tr><tr><td colspan="2"><center><input type="submit"value="提交">center>td>tr>table>body>html>3、用户主页面:userlist.jsp<%@page language="java"import="java.util.*"pageEncoding="UTF-8"%><%String path = request.getContextPath(;String basePath =request.getScheme(+"://"+request.getServerName(+":"+request.getSe rverPort(+path+"/";%>DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html><head><meta http-equiv="Content-Type"content="text/html; charset=UTF-8"><title>显示用户记录title>head><body><STYLE type="text/css">STYLE><%String name=(Stringsession.getAttribute("name";out.println(name;%><FONT SIZE="5"COLOR="#006699">恭喜您登录成功!FONT<hr/><center><font color="#006699"size=5>用户信息如下:font><hr><table border=1bgColor="#ffffff"width="500px"height="100px"> <tr><td>ID td><td>姓名td><td>密码td><td>性别td><td>年龄td><td><center>操作center> td>tr><jsp:useBean id="sBean"class="javaee.bean.SqlBean"/><jsp:useBean id="jBean"class="javaee.bean.javabean"/><%String sql ="select * from student order by id";java.util.List list =sBean.getuserlist(sql;for(java.util.Iterator it =list.iterator(;it.hasNext(;{//获取一个JavaBean对象jBean =(javaee.bean.javabeanit.next(;%><tr><td><%=jBean.getId( %>td><td><%=jBean.getName( %>td><td><%=jBean.getPassword( %>td><td><%=jBean.getSex( %>td><td><%=jBean.getAge( %>td><td><a href="insertuser.jsp">增加a><a href="deleteuser?id=<%=jBean.getId(%>">删除a><a href="searchById?id=<%=jBean.getId(%>">更新a>td>tr><% }%>table>center>body>html>4、增加用户:insertuser.jsp<%@page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%String path = request.getContextPath(;String basePath = request.getScheme(+"://"+request.getServerName(+":"+request.getServerPort(+path+"/"%>考研复试:英语口语听力全攻略 HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html><head><meta http-equiv="Content-Type" 数学专业的,或者理科物理的,他问专业术语,你很可能这个词都不认识,这怎么办呢?这里希望考生注意一点。

SpringMVC之简单的增删改查示例(SSM整合)

SpringMVC之简单的增删改查示例(SSM整合)

SpringMVC之简单的增删改查⽰例(SSM整合)虽然已经在做关于SpringMVC的项⽬。

但是还没有写⼀些⽐较系统的博客。

今天就先来说⼀说最简单的增删改查吧。

这个例⼦是基于SpringMVC+Spring+Mybatis实现的。

环境配置主要是⼏项配置:springmvc的配置,spring的配置,MyBatis的配置,jdbc的配置,和web.xml配置springmvc.xml<?xml version="1.0" encoding="UTF-8"?><beans xmlns="/schema/beans"xmlns:xsi="/2001/XMLSchema-instance" xmlns:mvc="/schema/mvc"xmlns:context="/schema/context"xmlns:aop="/schema/aop" xmlns:tx="/schema/tx"xsi:schemaLocation="/schema/beans/schema/beans/spring-beans-3.2.xsd/schema/mvc/schema/mvc/spring-mvc-3.2.xsd/schema/context/schema/context/spring-context-3.2.xsd/schema/aop/schema/aop/spring-aop-3.2.xsd/schema/tx/schema/tx/spring-tx-3.2.xsd"><!-- ⽂件扫描 --><context:component-scan base-package="com.zhao"></context:component-scan><!-- annotation-driven:默认创建了多个对象:RequestMappingHandlerMapping,RequestMappingHandlerAdapter也就提供对json格式⽀持--><mvc:annotation-driven/><!-- 视图解析器 --><bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"><property name="prefix" value="/WEB-INF/jsp/" /><property name="suffix" value=".jsp" /></bean></beans>beans.xml(Spring的配置)<?xml version="1.0" encoding="UTF-8"?><beans xmlns="/schema/beans"xmlns:xsi="/2001/XMLSchema-instance" xmlns:mvc="/schema/mvc"xmlns:context="/schema/context"xmlns:aop="/schema/aop" xmlns:tx="/schema/tx"xsi:schemaLocation="/schema/beans/schema/beans/spring-beans-3.2.xsd/schema/mvc/schema/mvc/spring-mvc-3.2.xsd/schema/context/schema/context/spring-context-3.2.xsd/schema/aop/schema/aop/spring-aop-3.2.xsd/schema/tx/schema/tx/spring-tx-3.2.xsd"><context:component-scan base-package="com.zhao"></context:component-scan><!-- 第⼀步:配置数据源 --><context:property-placeholder location="classpath:jdbc.properties" /><bean id="dataSource" class="boPooledDataSource"><property name="jdbcUrl" value="${jdbc.url}"></property><property name="driverClass" value="${jdbc.driver}"></property><property name="user" value="${ername}"></property><property name="password" value="${jdbc.password}"></property></bean><!-- 第⼆步:创建sqlSessionFactory。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
return;
}
String name = request.getParameter("user");
// String name=new String(name1.getBytes(("GBK")));//"ISO-8859-1",
int userage = Integer.parseInt(request.getParameter("age"));
//必须为post方式才行的
//获取所提交表单的值
String id = request.getParameter("id");
//严谨的编码:
if ("".equals(id) || id == null) {
response.sendRedirect("./Main.html");
// System.out.println("zzz");
IPersonDao person = new PersonDaoImpl();
//使用for循环进行删除操作
for (int i = 0; i < s.length; i++) {
// System.out.println(s[i]);
int id = Integer.parseInt(s[i]);
Add
public class Add extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//获取多个box的值的方法
String[] s = request.getParameterValues("like");// ?
//RequestDispatcher dp=request.getRequestDispatcher("/Add/selectAll");//转发方式
//dp.forward(request, response);
}
}
public class DelAll extends HttpServlet {
String addr = request.getParameter("address");
int userid = Integer.parseInt(id);
//调用dao层的方法进行添加到数据库的操作
Person p = new Person();
p.setId(userid);
p.setName(name);
throws ServletException, IOException {
doGet(request, response);
}
}
Update
public class UpdateHtml extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
}
// Post方法处理post的请求
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
//循环删除操作
person.delPersonById(id);
}
response.sendRedirect("/Add/selectAll");//跳到查询全部页面
}
// Post方法处理post的请求
public void doPost(HttpServletRequest request, HttpServletResponse response)
//编码问题
response.setContentType("text/html;charset=GBK");//浏览器显示的编码,默认的是iso
response.setCharacterEncoding("GBK");//浏览器到数据库取数据时候使用的编码
request.setCharacterEncoding("GBK");//浏览器到数据库存入数据时候所使用的编码方式
}
}
Delete
public class Delete extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
IPersonDao person=new PersonDaoImpl();
int id=Integer.parseInt(request.getParameter("id").trim());
person.delPersonById(id);
response.sendRedirect("/Jsp/selectAll");//重定向查询全部页面
throws Servቤተ መጻሕፍቲ ባይዱetException, IOException {
//编码问题
response.setContentType("text/html;charset=GBK");//浏览器显示的编码,默认的是iso
response.setCharacterEncoding("GBK");//浏览器到数据库取数据时候使用的编码
p.setAge(userage);
p.setAddress(addr);
IPersonDao person = new PersonDaoImpl();
person.addPerson(p);
//添加过后则重定向,跳向查询全部的页面
response.sendRedirect("/Jsp/selectAll");
相关文档
最新文档