码迷,mamicode.com
首页 > Web开发 > 详细

JSP的一个增删改查例子和总结

时间:2016-08-01 20:55:42      阅读:868      评论:0      收藏:0      [点我收藏+]

标签:

 

 总结的几点:

  1、在jsp中注意<%! %>声明代码块中的变量只会在项目开始的时候第一次运行jsp的时候执行一遍,有点类似于java类中的static代码块,所以如果是会改变的值不应该声明在这里面。而是卸载<%%>代码块中

  2、使用js中的location.href有时候就是无法生效,也就是无法跳转到你想要的页面。你可以在location.href语句后面加上 event.returnValue=false即可

  3、进行编辑一条信息或者删除信息的时候id字段可以使用隐藏域或者直接使用el传递。这样就不需要通过js找到id列或者其他了

  4、在增加的时候注意在servlet或者对应的jsp进行对象的补全

  5、在修改的时候如果有那种类似于下拉列表或者单选按钮的东西,可以使用jstl中的<c:if>实现选择。

例子:

技术分享
CREATE TABLE profile(
 id NUMBER PRIMARY KEY,
 name VARCHAR2(20),
 birthday DATE,
 gender VARCHAR2(10),
 career VARCHAR2(20),
 address VARCHAR2(50),
 mobile VARCHAR2(11)
);

CREATE SEQUENCE seq_profile;

package com.dao;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

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

import com.domain.Profile;
import com.jdbc.JdbcUtils;

public class ProfileDao {
    /**
     * zeng
     * @param p
     * @throws SQLException
     */
    public void addProfile(Profile p) throws SQLException{
        String sql="INSERT INTO profile VALUES (seq_profile.NEXTVAL,?,?,?,?,?,?)";
        QueryRunner qr=new QueryRunner();
        Connection con=JdbcUtils.getConnection();
        Object[] params={p.getName(),p.getBirthday(),p.getGender(),p.getCareer(),p.getAddress(),p.getMobile()};
        qr.update(con, sql,params);
        JdbcUtils.releaseConnection(con);
    }
    
    public void deleteById(int id) throws SQLException{
        String sql="DELETE FROM profile WHERE id=?";
        QueryRunner qr=new QueryRunner();
        Connection con=JdbcUtils.getConnection();
        Object[] params={id};
        qr.update(con,sql, params);
        JdbcUtils.releaseConnection(con);
    }
    
    public void update(Profile p) throws SQLException{
        String sql="UPDATE profile SET name=?,birthday=?,gender=?,career=?,address=?,mobile=? WHERE id=?";
        QueryRunner qr=new QueryRunner();
        Connection con=JdbcUtils.getConnection();
        Object[] params={p.getName(),p.getBirthday(),p.getGender(),p.getCareer(),p.getAddress(),p.getMobile(),p.getId()};
    //    System.out.println(Arrays.toString(params));
        qr.update(con,sql, params);
        JdbcUtils.releaseConnection(con);
    }
    
    public ArrayList<Profile> findAll() throws SQLException{
        String sql="SELECT * FROM profile";
        QueryRunner qr=new QueryRunner();
        Connection con=JdbcUtils.getConnection();
        ResultSetHandler<List<Profile>> rsh=new BeanListHandler<Profile>(Profile.class);
        ArrayList<Profile> profiles=(ArrayList<Profile>) qr.query(con, sql, rsh);
        JdbcUtils.releaseConnection(con);
        return profiles;
    }
    
    public Profile load(int id) throws SQLException{
        String sql="SELECT * FROM profile WHERE id=?";
        QueryRunner qr=new QueryRunner();
        Object[] params={id};
        Connection con=JdbcUtils.getConnection();
        ResultSetHandler<Profile> rsh=new BeanHandler<Profile>(Profile.class);
        Profile profile= (Profile) qr.query(con, sql, rsh,params);
        JdbcUtils.releaseConnection(con);
        return profile;
    }

}

package com.domain;

import java.io.Serializable;
import java.sql.Date;


public class Profile implements Serializable{
    
    private static final long serialVersionUID = 1L;
    private int id;
    private String name;
    private Date birthday;
    private String gender;
    private String career;
    private String address;
    private String mobile;
    @Override
    public String toString() {
        return "Profile [id=" + id + ", name=" + name + ", birthday="
                + birthday + ", gender=" + gender + ", career=" + career
                + ", address=" + address + ", mobile=" + mobile + "]";
    }
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public Date getBirthday() {
        return birthday;
    }
    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }
    public String getGender() {
        return gender;
    }
    public void setGender(String gender) {
        this.gender = gender;
    }
    public String getCareer() {
        return career;
    }
    public void setCareer(String career) {
        this.career = career;
    }
    public String getAddress() {
        return address;
    }
    public void setAddress(String address) {
        this.address = address;
    }
    public String getMobile() {
        return mobile;
    }
    public void setMobile(String mobile) {
        this.mobile = mobile;
    }
    public Profile() {
        super();
        // TODO Auto-generated constructor stub
    }
    public Profile(int id, String name, Date birthday, String gender,
            String career, String address, String mobile) {
        super();
        this.id = id;
        this.name = name;
        this.birthday = birthday;
        this.gender = gender;
        this.career = career;
        this.address = address;
        this.mobile = mobile;
    }
    
}

package com.jdbc;

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

import javax.sql.DataSource;

import com.mchange.v2.c3p0.ComboPooledDataSource;

public class JdbcUtils {
    /*
     * 配置文件的恶魔人配置!要求你必须给出c3p0-config。xnl!
     */
    private static ComboPooledDataSource dataSource=new ComboPooledDataSource("oracle-config");
    /**
     * 它是事务专用连接
     */
    private static Connection con=null;
    /**
     * 使用连接池返回一个连接对象
     * @return
     * @throws SQLException
     */
    public static Connection getConnection() throws SQLException{
        //当con!=null,表示已经调用过beginTransaction方法了
        if(con!=null) return con;
        return dataSource.getConnection();
    }
    
    /**
     * 返回连接池对象
     * @return
     */
    public static DataSource getDataSource(){
        return dataSource;
    }
    /**
     * 1、开启一个Connection,设置它的setAutoCommit(false)
     * 2、还要保证dao中使用的连接是我们刚刚创建的
     * ------------------------
     * 1、创建一个Connection,设置为手动提交
     * 2、把这个Connection给dao用
     * 3、还要让commitTransaction或rollbackTransaction可以获取到
     * @throws SQLException 
     */
    public static void beignTransaction() throws SQLException{
        if(con!=null) throw new SQLException("已经开始了事务,就不要继续开启事务了!");
        con=getConnection();
        con.setAutoCommit(false);
    }
    /**
     * 提交事务
     * 获取之前开启的Connection,兵提交
     * @throws SQLException 
     */
    public static void commitTransaction() throws SQLException{
        if(con==null) throw new SQLException("还没有开启事务,不能提交!");
        con.commit();
        con.close();
        con=null;//因为前面的close()不会销毁连接而是放回连接池
    }
    /**
     * 回滚事务
     * 获取之前开启的Connection,兵回滚
     * @throws SQLException 
     */
    public static void rollbackTransaction() throws SQLException{
        if(con==null) throw new SQLException("还没有开启事务,不能提交!");
        con.rollback();
        con.close();
        con=null;//因为前面的close()不会销毁连接而是放回连接池
    }
    
    public static void releaseConnection(Connection connection) throws SQLException{
        /*
         *判斷它是不是中事務專用,如果是就不關閉
         *如果不是就要關閉
         */
        //如果con==null,說明沒有事務,那麼connection一定不是事務專用的
        if(con==null)    connection.close();
        if(con!=connection) connection.close();
        
    }
}

package com.service;

import java.sql.SQLException;
import java.util.ArrayList;

import com.dao.ProfileDao;
import com.domain.Profile;

public class ProfileService {
    
    private ProfileDao profileDao=new ProfileDao();
    
    public void addProfile(Profile p){
        try {
            profileDao.addProfile(p);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    
    public void deleteProfile(int id){
        try {
            profileDao.deleteById(id);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    
    public void updateProfile(Profile p){
        try {
            profileDao.update(p);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    
    public ArrayList<Profile> findAll(){
        try {
            return profileDao.findAll();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
    
    public Profile findById(int id){
        try {
            return profileDao.load(id);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}

package com.test;

import java.sql.Date;
import java.text.ParseException;
import java.text.SimpleDateFormat;

import org.junit.Test;

import com.domain.Profile;
import com.service.ProfileService;

public class Test01 {
    
    @Test
    public void fun1() throws ParseException{
        ProfileService ps=new ProfileService();
        Profile p=new Profile();
        p.setName("liu");
        
        p.setBirthday(geDate("1994-10-12"));
        p.setAddress("江西");
        p.setGender("女");
        p.setMobile("8482973");
        p.setCareer("学生");
        ps.addProfile(p);
//        p.setCareer("工人");
//        p.setId(1);
//        ps.updateProfile(p);
//        System.out.println(ps.findAll());
//        System.out.println(ps.findById(1));
    }
    
    public Date geDate(String date) throws ParseException{
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        return new Date(sdf.parse(date).getTime());
    }
}

<?xml version="1.0" encoding="UTF-8" ?>
<c3p0-config>
    <!-- 默认连接配置 -->
    <default-config> 
        <!-- 连接四大参数配置  -->
        <property name="jdbcUrl">jdbc:mysql://127.0.0.1:3306/demo</property>
        <property name="driverClass">com.mysql.jdbc.Driver</property>
        <property name="user">guodaxia</property>
        <property name="password">961012gz</property>
            <!-- 池参数配置 -->
        <property name="acquireIncrement">3</property>
        <property name="initialPoolSize">10</property>
        <property name="minPoolSize">2</property>
        <property name="maxPoolSize">10</property>
    </default-config>
    
    <named-config name="oracle-config">
        <!-- 连接四大参数配置  -->
        <property name="jdbcUrl">jdbc:oracle:thin:@localhost:1521:db</property>
        <property name="driverClass">oracle.jdbc.driver.OracleDriver</property>
        <property name="user">scott</property>
        <property name="password">961012gz</property>        
        <property name="acquireIncrement">3</property>
        <property name="initialPoolSize">10</property>
        <property name="minPoolSize">2</property>
        <property name="maxPoolSize">10</property>
    </named-config>
    
</c3p0-config>

$(function(){
    
    $("button[name=‘show‘]").click(function(){
        var id=$($(this).parents("tr").find("td")[0]).text();
        //alert(id);
        window.location.href="detail.jsp?id="+id;
    });
    
    $("button[name=‘alert‘]").click(function(){
        var id=$($(this).parents("tr").find("td")[0]).text();
        //alert(id);
        window.location.href="update.jsp?id="+id;
    });

    $("button[name=‘delete‘]").click(function(){
        var id=$($(this).parents("tr").find("td")[0]).text();
        //alert(id);
        window.location.href="delete.jsp?id="+id;
    });
    
});

$(function(){
    
    
    $("option").each(function(){
        var v1=$("#hhh").val();
        var v2=$(this).val();
        //alert($("#hhh").val()+"   "+$(this).val());
        if(v1==v2){
            $(this).attr("selected",true);
        }
    });
    
    $("button[name=‘back‘").click(function(){
        //alert(1);
        window.location.href="list.jsp?date="+new Date().getTime();
        event.returnValue=false;
    });
    
});

<%@ 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>
    <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">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->
  </head>
  
  <body>
    <% 
        response.sendRedirect(path+"/list.jsp");
    %>
  </body>
</html>

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ page import="com.domain.Profile,java.sql.Date,com.service.ProfileService,java.text.SimpleDateFormat" %>

<%
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>
    <base href="<%=basePath%>">
    
    <title>My JSP ‘list.jsp‘ starting page</title>
    
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->
    <style type="text/css">
        td{
        /* width:80px; */
         border:1px solid;
        }
        table{
         border:1px solid;
        }
        #tr1{
        background-color: yellow;
        }
    </style>
    <script type="text/javascript" src="js/jquery1.8.3.js"></script>
    <script type="text/javascript" src="js/list.js"></script>
  </head>
  <% 
          ProfileService ps=new ProfileService();
          ArrayList<Profile> profiles=ps.findAll();
  %>
      <%!
          
          String date2Str(Date d){
              SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
              return sdf.format(d);
          }
      %>
  <body>
    <table>
        <tr id="tr1">
            <td>编号</td>
            <td>姓名</td>
            <td>生日</td>
            <td>性别</td>
            <td>职业</td>
            <td>住所</td>
            <td>电话</td>
            <td>操作</td>
        </tr>
        <%for(Profile p:profiles){%>
        <tr>
            <td><%=p.getId() %></td>
            <td><%=p.getName() %></td>
            <td><%=date2Str(p.getBirthday()) %></td>
            <td><%=p.getGender() %></td>
            <td><%=p.getCareer() %></td>
            <td><%=p.getAddress() %></td>
            <td><%=p.getMobile() %></td>
            <td>
                <button name="show" >明细</button>
                <button  name="alert" >修改</button>
                <button name="delete" >删除</button>
            </td>
        </tr>
        <%
        }
        %>
        
    </table>
  </body>
</html>

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ page import="com.domain.Profile,java.sql.Date,com.service.ProfileService,java.text.SimpleDateFormat" %>
<%
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>
    <base href="<%=basePath%>">
    
    <title>My JSP ‘update.jsp‘ starting page</title>
    
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->
    
    <style type="text/css">
        table{
            border:1px solid;
        }
        td{
            border:1px solid;
        }
    </style>
    <script type="text/javascript" src="js/jquery1.8.3.js"></script>
    <script type="text/javascript" src="js/update.js"></script>
  </head>
  
  <body>
    <%!
           Profile p=null;
          String date2Str(Date d){
              SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
              return sdf.format(d);
          }
      %>
      <%
          Integer i=Integer.valueOf(request.getParameter("id"));
          ProfileService ps=new ProfileService();
          p=ps.findById(i);
      %>
      <form action="utu.jsp" method="post">
       <table>
        <tr>
            <td>编号</td>
            <td><input name="id" type="text" value="<%=p.getId() %>" readonly></td>
        </tr>
        <tr>
            <td>姓名</td>
            <td><input name="name" type="text" value="<%=p.getName() %>" ></td>
        </tr>
        <tr>
            <td>生日</td>
            <td><input name="birthday" type="text" value="<%=p.getBirthday() %>" ></td>
        </tr>
        <tr>
            <td>性别</td>
            <td>
                <select name="gender">
                    <option value="女">女</option>
                    <option value="男">男</option>
                </select>
                <input id="hhh" type="hidden" value="<%=p.getGender() %>">
            </td>
        </tr>
        <tr>
            <td>职业</td>
            <td><input name="career" type="text" value="<%=p.getCareer() %>" ></td>
        </tr>
        <tr>
            <td>住所</td>
            <td><input name="address" type="text" value="<%=p.getAddress() %>" ></td>
        </tr>
        <tr>
            <td>电话</td>
            <td><input name="mobile" type="text" value="<%=p.getMobile() %>" ></td>
        </tr>
    </table>
    <input type="submit" value="修改">
    <button name="back">返回</button>
    </form>
  </body>
</html>

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ page import="com.domain.Profile,java.sql.Date,com.service.ProfileService,java.text.SimpleDateFormat,java.text.ParseException" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<%!
    Date str2Date(String str)throws  ParseException{
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        return new Date(sdf.parse(str).getTime());
    }
%>

<%
    request.setCharacterEncoding("utf-8");
    response.setCharacterEncoding("utf-8");
    
    int id=Integer.parseInt(request.getParameter("id"));
    String name=request.getParameter("name");
    Date birthday=str2Date(request.getParameter("birthday"));
    String gender=request.getParameter("gender");
    String career=request.getParameter("career");
    String address=request.getParameter("address");
    String mobile=request.getParameter("mobile");
    
    System.out.println(id+"---"+name+"--"+birthday+"--"+gender+"--"+career+"--"+address+"--"+mobile);
    Profile p=new Profile();
    p.setId(id);
    p.setName(name);
    p.setBirthday(birthday);
    p.setGender(gender);
    p.setCareer(career);
    p.setAddress(address);
    p.setMobile(mobile);
    
    ProfileService ps=new ProfileService();
    ps.updateProfile(p);
    
    response.sendRedirect(path+"/update.jsp?id="+id);
    
%>

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ page import="com.domain.Profile,java.sql.Date,com.service.ProfileService,java.text.SimpleDateFormat" %>
<%
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>
    <base href="<%=basePath%>">
    
    <title>My JSP ‘detail.jsp‘ starting page</title>
    
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->
    <style type="text/css">
        table{
            border:1px solid;
        }
        td{
            border:1px solid;
        }
    </style>
  </head>
   <%!
           Profile p=null;
          String date2Str(Date d){
              SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
              return sdf.format(d);
          }
      %>
      <%
          Integer i=Integer.valueOf(request.getParameter("id"));
          ProfileService ps=new ProfileService();
          p=ps.findById(i);
      %>
 
  
  <body>
    <table>
        <tr>
            <td>编号</td>
            <td><%=p.getId() %></td>
        </tr>
        <tr>
            <td>姓名</td>
            <td><%=p.getName() %></td>
        </tr>
        <tr>
            <td>生日</td>
            <td><%=p.getBirthday() %></td>
        </tr>
        <tr>
            <td>性别</td>
            <td><%=p.getGender() %></td>
        </tr>
        <tr>
            <td>职业</td>
            <td><%=p.getCareer() %></td>
        </tr>
        <tr>
            <td>住所</td>
            <td><%=p.getAddress() %></td>
        </tr>
        <tr>
            <td>电话</td>
            <td><%=p.getMobile() %></td>
        </tr>
    </table>
    <button onclick="javascript:history.go(-1)">返回</button>
  </body>
</html>

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ page import="com.domain.Profile,java.sql.Date,com.service.ProfileService,java.text.SimpleDateFormat" %>
<% 
    int id=Integer.parseInt(request.getParameter("id"));
    ProfileService ps=new ProfileService();
    ps.deleteProfile(id);
    response.sendRedirect(request.getContextPath()+"/list.jsp?date="+System.currentTimeMillis());
%>
View Code

jar:

  技术分享

 

JSP的一个增删改查例子和总结

标签:

原文地址:http://www.cnblogs.com/aigeileshei/p/5727041.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!