JSP实现添加图书、修改图书以及删除图书

所用软件:
1 myeclipse
2 mysql数据库
3 dbutils连接数据库
4 bootstrap前段框架
5 EL表达式+JSTL标签库
6 c3p0连接池


过滤器(filter)解决全站的字符乱码问题


添加书籍入页面:
JSP实现添加图书、修改图书以及删除图书_第1张图片


查询书籍页面:
JSP实现添加图书、修改图书以及删除图书_第2张图片


修改书籍界面:(注意要回显所要修改图书的数据)
JSP实现添加图书、修改图书以及删除图书_第3张图片


工程目录:
JSP实现添加图书、修改图书以及删除图书_第4张图片


JSP实现添加图书、修改图书以及删除图书_第5张图片


bookServlet如下:

package com.hai.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.hai.dao.bookDao;
import com.hai.domain.book;
import com.hai.utils.WebUtils;

public class bookServlet extends HttpServlet {

    public bookServlet() {
        super();
    }

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        String type = request.getParameter("type");
        if (type.equalsIgnoreCase("charu")) {
            charu(request, response);
        } else if (type.equalsIgnoreCase("chaxun")) {
            chaxun(request, response);
        } else if (type.equalsIgnoreCase("shan")) {
            shanchu(request, response);
        } else if (type.equalsIgnoreCase("xiu01")) {
            xiugai01(request, response);
        } else if (type.equalsIgnoreCase("xiu02")) {
            xiugai02(request, response);
        }
    }

    private void xiugai02(HttpServletRequest request,   //修改图书
            HttpServletResponse response) {
        String id = request.getParameter("id");
        String bookname = request.getParameter("bookname");
        String author = request.getParameter("author");
        String age = request.getParameter("age");
        book shu = new book();
        shu.setId(id);
        shu.setBooknamee(bookname);
        shu.setAuthorr(author);
        shu.setAgee(Integer.parseInt(age));
        bookDao mm=new bookDao();
        mm.xiugai(shu);
        try {
            response.getWriter().write("修改完毕!!!");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void xiugai01(HttpServletRequest request,  //用于回显该图书的数据
            HttpServletResponse response) {
        String id = request.getParameter("id");
        bookDao mmBookDao = new bookDao();
        book shu = mmBookDao.chaxun(id);
        request.setAttribute("book", shu);
        try {
            request.getRequestDispatcher("/WEB-INF/xiugai.jsp").forward(
                    request, response);
        } catch (ServletException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    private void shanchu(HttpServletRequest request,  //删除图书
            HttpServletResponse response) {
        String id = request.getParameter("id");
        bookDao mm = new bookDao();
        mm.shanchu(id);
        List listt = mm.chaxun();
        request.setAttribute("listt", listt);
        try {
            request.getRequestDispatcher("/chaxun.jsp").forward(request,
                    response);
        } catch (ServletException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    private void chaxun(HttpServletRequest request, HttpServletResponse response) {  //图书查询
        bookDao mm = new bookDao();
        List listt = mm.chaxun();
        request.setAttribute("listt", listt);
        try {
            request.getRequestDispatcher("/chaxun.jsp").forward(request,
                    response);
        } catch (ServletException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    private void charu(HttpServletRequest request, HttpServletResponse response) {  //添加图书
        String bookname = request.getParameter("bookname");
        String author = request.getParameter("author");
        String age = request.getParameter("age");
        book shu = new book();
        shu.setId(WebUtils.makeID());
        shu.setBooknamee(bookname);
        shu.setAuthorr(author);
        shu.setAgee(Integer.parseInt(age));
        bookDao mm = new bookDao();
        mm.charu(shu);
        try {
            response.getWriter().write("cha ru wan bi");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        doGet(request, response);
    }

}


dao对象:

package com.hai.dao;

import java.awt.print.Book;
import java.util.List;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import com.hai.domain.book;
import com.hai.utils.JdbcUtils;

public class bookDao {

      public void charu(book book){  //添加一本书
            try{
                QueryRunner runner = new QueryRunner(JdbcUtils.getDataSource());
                String sql = "insert into book(id,booknamee,authorr,agee) values(?,?,?,?)";
                Object params[] = {book.getId(),book.getBooknamee(),book.getAuthorr(),book.getAgee()};
                runner.update(sql, params);
            }catch (Exception e) {
                throw new RuntimeException(e);
            }
        }


      public void xiugai(book book){//修改某本书  
            try{
                QueryRunner runner = new QueryRunner(JdbcUtils.getDataSource());
                String sql = "update book set booknamee=?,authorr=?,agee=? where id=? ";
                Object params[] = {book.getBooknamee(),book.getAuthorr(),book.getAgee(),book.getId()};
                runner.update(sql, params);
            }catch (Exception e) {
                throw new RuntimeException(e);
            }
        }

      public void shanchu(String id){ //删除具体ID所对应的图书
            try{
                QueryRunner runner = new QueryRunner(JdbcUtils.getDataSource());
                String sql = "delete from book where id=?";          
                runner.update(sql, id);
            }catch (Exception e) {
                throw new RuntimeException(e);
            }
        }

      public List chaxun(){  //查询所有图书
            try{
                QueryRunner runner = new QueryRunner(JdbcUtils.getDataSource());
                String sql = "select * from book";

              List listt=  (List) runner.query(sql, new BeanListHandler(book.class));
              return listt;
            }catch (Exception e) {
                throw new RuntimeException(e);
            }
        }

      public book chaxun(String id){  //查询具体ID所对应的书
            try{
                QueryRunner runner = new QueryRunner(JdbcUtils.getDataSource());
                String sql = "select * from book where id=?";

              book shu= (book) runner.query(sql,id,new BeanHandler(book.class));
              return shu;
            }catch (Exception e) {
                throw new RuntimeException(e);
            }
        }     
}


封装book的数据实体(domain):

package com.hai.domain;

public class book {
    private String id;
private String  booknamee;
private String  authorr;
private int agee;
public String getBooknamee() {
    return booknamee;
}
public void setBooknamee(String booknamee) {
    this.booknamee = booknamee;
}
public String getId() {
    return id;
}
public void setId(String id) {
    this.id = id;
}
public String getAuthorr() {
    return authorr;
}
public void setAuthorr(String authorr) {
    this.authorr = authorr;
}
public int getAgee() {
    return agee;
}
public void setAgee(int agee) {
    this.agee = agee;
}

}

解决全站字符编码的过滤器:

package com.hai.filters;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.Principal;
import java.util.Enumeration;
import java.util.Locale;
import java.util.Map;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

//为解决全站乱码
public class character implements Filter {

    public void destroy() {
        // TODO Auto-generated method stub

    }

    public void doFilter(ServletRequest req, ServletResponse resp,
            FilterChain chain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");

        MyCharacterEncodingRequest requestWrapper = new MyCharacterEncodingRequest(
                request);
        chain.doFilter(requestWrapper, response);

    }

    public void init(FilterConfig filterConfig) throws ServletException {
        // TODO Auto-generated method stub

    }
}

/*
 * 1.实现与被增强对象相同的接口 2、定义一个变量记住被增强对象 3、定义一个构造器,接收被增强对象 4、覆盖需要增强的方法
 * 5、对于不想增强的方法,直接调用被增强对象(目标对象)的方法
 */

class MyCharacterEncodingRequest extends HttpServletRequestWrapper {

    private HttpServletRequest request;

    public MyCharacterEncodingRequest(HttpServletRequest request) {
        super(request);
        this.request = request;
    }

    @Override
    public String getParameter(String name) {

        try {
            String value = this.request.getParameter(name);
            if (value == null) {
                return null;
            }

            if (!this.request.getMethod().equalsIgnoreCase("get")) {
                return value;
            }

            value = new String(value.getBytes("ISO8859-1"),
                    this.request.getCharacterEncoding());
            return value;

        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}

web.xml


<web-app version="3.0" 
    xmlns="http://java.sun.com/xml/ns/javaee" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
    http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
  <display-name>display-name>
  <filter>
  <filter-name>haitaofilter-name>
  <filter-class>com.hai.filters.characterfilter-class>
  filter>
  <filter-mapping>
  <filter-name>haitaofilter-name>
  <url-pattern>/*url-pattern>
  filter-mapping>
  <servlet>
    <description>This is the description of my J2EE componentdescription>
    <display-name>This is the display name of my J2EE componentdisplay-name>
    <servlet-name>bookServletservlet-name>
    <servlet-class>com.hai.servlet.bookServletservlet-class>
  servlet>

  <servlet-mapping>
    <servlet-name>bookServletservlet-name>
    <url-pattern>/servlet/bookServleturl-pattern>
  servlet-mapping>    
  <welcome-file-list>
    <welcome-file>index.jspwelcome-file>
  welcome-file-list>
web-app>


提供连接池的工具类:

package com.hai.utils;

import java.sql.Connection;
import java.sql.SQLException;

import javax.sql.DataSource;

import com.mchange.v2.c3p0.ComboPooledDataSource;

public class JdbcUtils {
    private static DataSource ds = null;
    static{
        ds = new ComboPooledDataSource();
    }

    public static DataSource getDataSource(){
        return ds;
    }

    public static Connection getConnection() throws SQLException{
        return ds.getConnection();
    }
}


UUID字符串类:

package com.hai.utils;

import java.util.UUID;

public class WebUtils {

    public static String makeID(){
        return UUID.randomUUID().toString();
    }
}


c3p0-config.xml 如下:




<c3p0-config>
    <default-config>
        <property name="driverClass">com.mysql.jdbc.Driverproperty>
        <property name="jdbcUrl">jdbc:mysql://localhost:3306/xuhaitaoproperty>
        <property name="user">rootproperty>
        <property name="password">rootproperty>

        <property name="acquireIncrement">5property>
        <property name="initialPoolSize">10property>
        <property name="minPoolSize">5property>
        <property name="maxPoolSize">20property>


    default-config>

    <named-config name="flx">
        <property name="driverClass">com.mysql.jdbc.Driverproperty>
        <property name="jdbcUrl">jdbc:mysql://localhost:3306/day16property>
        <property name="user">rootproperty>
        <property name="password">rootproperty>
        <property name="acquireIncrement">50property>
        <property name="initialPoolSize">100property>
        <property name="minPoolSize">50property>
        <property name="maxPoolSize">1000property>
    named-config>

c3p0-config>

charu.jsp

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>


<html>
<head>


<title>My JSP 'charu.jsp' starting pagetitle>

<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="css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="css/style.min.css">
<script type="text/javascript" src="js/jquery-2.1.1.js">script>
<script type="text/javascript" src="js/bootstrap.min.js">script>
head>

<body class="container">
    <form method="post"
        action="${pageContext.request.contextPath}/servlet/bookServlet?type=charu">
        <div class="form-group">
            <label class="control-label">书名:label> <input type="text"
                class="form-control" name="bookname" />
        div>
        <div class="form-group">
            <label class="control-label">作者:label> <input type="text"
                class="form-control" name="author" />
        div>
        <div class="form-group">
            <label class="control-label">年龄:label> <input type="text"
                class="form-control" name="age" />
        div>
        <div class="form-group">
            <input type="submit" value="提交" class="btn btn-primary" />
        div>
    form>
body>
html>


chaxun.jsp


<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>


<html>
<head>
<title>My JSP 'chaxun.jsp' starting pagetitle>
<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"
    href="http://cdn.static.runoob.com/libs/bootstrap/3.3.7/css/bootstrap.min.css">
<script
    src="http://cdn.static.runoob.com/libs/jquery/2.1.1/jquery.min.js">script>
<script
    src="http://cdn.static.runoob.com/libs/bootstrap/3.3.7/js/bootstrap.min.js">script>

<style type="text/css">
td{
  vertical-align: middle !important;
}
style>
head>

<body class="container">
    <table class="table">
        <tr>
            <td style="padding:30px;">书名td>
            <td style="padding:30px;">作者td>
            <td style="padding:30px;">年龄td>
            <td style="padding:30px;" align="left">操作td>
        tr>
        <c:forEach var="mm" items="${listt }">
            <tr>
                <td style="padding:30px;">${mm.booknamee }td>
                <td style="padding:30px;">${mm.authorr}td>
                <td style="padding:30px;">${mm.agee }td>
                <td align="left" style="padding-left:25px;"><a class="btn btn-primary btn-sm" href="${pageContext.request.contextPath}/servlet/bookServlet?type=shan&id=${mm.id}">删除a><br>
                <a style="margin-top:5px;" class="btn btn-primary btn-sm" href="${pageContext.request.contextPath}/servlet/bookServlet?type=xiu01&id=${mm.id}"">修改
                
            
        
    




xiugai.jsp如下:

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>


<html>
  <head>


    <title>My JSP 'xiugai.jsp' starting pagetitle>

    <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"
    href="http://cdn.static.runoob.com/libs/bootstrap/3.3.7/css/bootstrap.min.css">
<script
    src="http://cdn.static.runoob.com/libs/jquery/2.1.1/jquery.min.js">script>
<script
    src="http://cdn.static.runoob.com/libs/bootstrap/3.3.7/js/bootstrap.min.js">script>
  head>

  <body class="container">
 <form method="post"
        action="${pageContext.request.contextPath}/servlet/bookServlet?type=xiu02&id=${book.id}">
        <div class="form-group">
            <label class="control-label">书名:label> <input type="text"
                class="form-control" name="bookname"  value="${book.booknamee }"/>
        div>
        <div class="form-group">
            <label class="control-label">作者:label> <input type="text"
                class="form-control" name="author" value="${book.authorr }" />
        div>
        <div class="form-group">
            <label class="control-label">年龄:label> <input type="text"
                class="form-control" name="age" value="${book.agee }"/>
        div>
        <div class="form-group">
            <input type="submit" value="提交" class="btn btn-primary" />
        div>
    form>
  body>
html>

FR:海涛高软(QQ技术交流群:386476712)

你可能感兴趣的:(Java-Web)