简单MVC实现增删改查

反射工具类RelfectionUtils

  1 package Utils;
  2
  3 import java.lang.reflect.Field;
  4 import java.lang.reflect.InvocationTargetException;
  5 import java.lang.reflect.Method;
  6 import java.lang.reflect.Modifier;
  7 import java.lang.reflect.ParameterizedType;
  8 import java.lang.reflect.Type;
  9
 10 /**
 11  * 反射的 Utils 函数集合
 12  * 提供访问私有变量, 获取泛型类型 Class, 提取集合中元素属性等 Utils 函数
 13  * @author Administrator
 14  *
 15  */
 16 public class ReflectionUtils {
 17
 18
 19     /**
 20      * 通过反射, 获得定义 Class 时声明的父类的泛型参数的类型
 21      * 如: public EmployeeDao extends BaseDao<Employee, String>
 22      * @param clazz
 23      * @param index
 24      * @return
 25      */
 26     @SuppressWarnings("unchecked")
 27     public static Class getSuperClassGenricType(Class clazz, int index){
 28         Type genType = clazz.getGenericSuperclass();
 29
 30         if(!(genType instanceof ParameterizedType)){
 31             return Object.class;
 32         }
 33
 34         Type [] params = ((ParameterizedType)genType).getActualTypeArguments();
 35
 36         if(index >= params.length || index < 0){
 37             return Object.class;
 38         }
 39
 40         if(!(params[index] instanceof Class)){
 41             return Object.class;
 42         }
 43
 44         return (Class) params[index];
 45     }
 46
 47     /**
 48      * 通过反射, 获得 Class 定义中声明的父类的泛型参数类型
 49      * 如: public EmployeeDao extends BaseDao<Employee, String>
 50      * @param <T>
 51      * @param clazz
 52      * @return
 53      */
 54     @SuppressWarnings("unchecked")
 55     public static<T> Class<T> getSuperGenericType(Class clazz){
 56         return getSuperClassGenricType(clazz, 0);
 57     }
 58
 59     /**
 60      * 循环向上转型, 获取对象的 DeclaredMethod
 61      * @param object
 62      * @param methodName
 63      * @param parameterTypes
 64      * @return
 65      */
 66     public static Method getDeclaredMethod(Object object, String methodName, Class<?>[] parameterTypes){
 67
 68         for(Class<?> superClass = object.getClass(); superClass != Object.class; superClass = superClass.getSuperclass()){
 69             try {
 70                 //superClass.getMethod(methodName, parameterTypes);
 71                 return superClass.getDeclaredMethod(methodName, parameterTypes);
 72             } catch (NoSuchMethodException e) {
 73                 //Method 不在当前类定义, 继续向上转型
 74             }
 75             //..
 76         }
 77
 78         return null;
 79     }
 80
 81     /**
 82      * 使 filed 变为可访问
 83      * @param field
 84      */
 85     public static void makeAccessible(Field field){
 86         if(!Modifier.isPublic(field.getModifiers())){
 87             field.setAccessible(true);
 88         }
 89     }
 90
 91     /**
 92      * 循环向上转型, 获取对象的 DeclaredField
 93      * @param object
 94      * @param filedName
 95      * @return
 96      */
 97     public static Field getDeclaredField(Object object, String filedName){
 98
 99         for(Class<?> superClass = object.getClass(); superClass != Object.class; superClass = superClass.getSuperclass()){
100             try {
101                 return superClass.getDeclaredField(filedName);
102             } catch (NoSuchFieldException e) {
103                 //Field 不在当前类定义, 继续向上转型
104             }
105         }
106         return null;
107     }
108
109     /**
110      * 直接调用对象方法, 而忽略修饰符(private, protected)
111      * @param object
112      * @param methodName
113      * @param parameterTypes
114      * @param parameters
115      * @return
116      * @throws InvocationTargetException
117      * @throws IllegalArgumentException
118      */
119     public static Object invokeMethod(Object object, String methodName, Class<?> [] parameterTypes,
120             Object [] parameters) throws InvocationTargetException{
121
122         Method method = getDeclaredMethod(object, methodName, parameterTypes);
123
124         if(method == null){
125             throw new IllegalArgumentException("Could not find method [" + methodName + "] on target [" + object + "]");
126         }
127
128         method.setAccessible(true);
129
130         try {
131             return method.invoke(object, parameters);
132         } catch(IllegalAccessException e) {
133             System.out.println("不可能抛出的异常");
134         }
135
136         return null;
137     }
138
139     /**
140      * 直接设置对象属性值, 忽略 private/protected 修饰符, 也不经过 setter
141      * @param object
142      * @param fieldName
143      * @param value
144      */
145     public static void setFieldValue(Object object, String fieldName, Object value){
146         Field field = getDeclaredField(object, fieldName);
147
148         if (field == null)
149             throw new IllegalArgumentException("Could not find field [" + fieldName + "] on target [" + object + "]");
150
151         makeAccessible(field);
152
153         try {
154             field.set(object, value);
155         } catch (IllegalAccessException e) {
156             System.out.println("不可能抛出的异常");
157         }
158     }
159
160     /**
161      * 直接读取对象的属性值, 忽略 private/protected 修饰符, 也不经过 getter
162      * @param object
163      * @param fieldName
164      * @return
165      */
166     public static Object getFieldValue(Object object, String fieldName){
167         Field field = getDeclaredField(object, fieldName);
168
169         if (field == null)
170             throw new IllegalArgumentException("Could not find field [" + fieldName + "] on target [" + object + "]");
171
172         makeAccessible(field);
173
174         Object result = null;
175
176         try {
177             result = field.get(object);
178         } catch (IllegalAccessException e) {
179             System.out.println("不可能抛出的异常");
180         }
181
182         return result;
183     }
184 }

jdbcutils

 1 package Utils;
 2
 3 import java.sql.Connection;
 4 import java.sql.SQLException;
 5
 6 import javax.sql.DataSource;
 7
 8 import com.mchange.v2.c3p0.ComboPooledDataSource;
 9
10 public class JdbcUtil {
11
12     public static void reaseConnection(Connection connection) {
13         try {
14             if(connection!=null){
15                 connection.close();
16             }
17         } catch (SQLException e) {
18             // TODO Auto-generated catch block
19             e.printStackTrace();
20         }
21     }
22     private static DataSource dataSource = null;
23     static{
24         dataSource = new ComboPooledDataSource("mvc");
25     }
26
27     public static DataSource getDataSource(){
28         return dataSource;
29     }
30
31     public static Connection getConnection(){
32         try {
33             return dataSource.getConnection();
34         } catch (SQLException e) {
35             // TODO Auto-generated catch block
36             //e.printStackTrace();
37             System.out.println("连接失败");
38         }
39         return null;
40
41     }
42 }

DAO操作类 依靠c3p0,dbutil

 1 package com.mvc.dao;
 2
 3 import java.lang.reflect.ParameterizedType;
 4 import java.lang.reflect.Type;
 5 import java.sql.Connection;
 6 import java.sql.PreparedStatement;
 7 import java.sql.SQLException;
 8 import java.util.ArrayList;
 9 import java.util.List;
10
11 import org.apache.commons.dbutils.QueryRunner;
12 import org.apache.commons.dbutils.handlers.BeanHandler;
13 import org.apache.commons.dbutils.handlers.BeanListHandler;
14 import org.apache.commons.dbutils.handlers.ScalarHandler;
15 import org.apache.el.util.ReflectionUtil;
16
17 import com.sun.org.apache.bcel.internal.generic.NEW;
18
19 import Utils.JdbcUtil;
20 import Utils.ReflectionUtils;
21
22 public class Dao<T> {
23     private Class<T> clazz;
24     private QueryRunner queryRunner= new QueryRunner(JdbcUtil.getDataSource());
25     public Dao() {
26         clazz = ReflectionUtils.getSuperGenericType(this.getClass());
27     }
28     public <E> E getForValue(String sql,Object ...arg){
29         try {
30             return (E) queryRunner.query(sql,new ScalarHandler(),arg);
31         } catch (SQLException e) {
32             // TODO Auto-generated catch block
33             e.printStackTrace();
34             System.out.println("getForValue error");
35         }
36         return null;
37
38     }
39     public List<T> getForList(String sql,Object ...args){
40         try {
41             return queryRunner.query(sql, new BeanListHandler<>(clazz),args);
42         } catch (SQLException e) {
43             System.out.println("getForList error");
44         }
45         return null;
46
47
48     }
49     public T get(String sql,Object ...args){
50         try {
51             return queryRunner.query(sql,new BeanHandler<>(clazz),args);
52         } catch (SQLException e) {
53             // TODO Auto-generated catch block
54             //e.printStackTrace();
55             System.out.println("get error");
56         }
57         return null;
58     }
59
60     public void updata(String sql,Object ...args){
61         try {
62             queryRunner.update(sql,args);
63         } catch (SQLException e) {
64             // TODO Auto-generated catch block
65             //e.printStackTrace();
66             System.out.println("updata error");
67         }
68     }
69 }

Customer类

package com.mvc.domain;

public class Customer {
    private String id;
    private String name;
    private String address;
    private String phone;
    private int count;

    public Customer() {
        super();
    }
    public Customer(String id, String name, String address, String phone) {
        super();
        this.id = id;
        this.name = name;
        this.address = address;
        this.phone = phone;
        this.count = 0;
    }

    public int getCount() {
        return count;
    }
    public void setCount(int count) {
        this.count = count;
    }
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getAddress() {
        return address;
    }
    public void setAddress(String address) {
        this.address = address;
    }
    public String getPhone() {
        return phone;
    }
    public void setPhone(String phone) {
        this.phone = phone;
    }
    @Override
    public String toString() {
        return "Customer [id=" + id + ", name=" + name + ", address=" + address + ", phone=" + phone + "]";
    }

}

CustomerDao接口

 1 package com.mvc.dao;
 2
 3 import java.util.List;
 4
 5 import com.mvc.domain.CriteriaCustomer;
 6 import com.mvc.domain.Customer;
 7
 8 public interface CustomerDao {
 9     public List<Customer> getAll();
10     public void save(Customer customer);
11     public void upCount(Customer customer);
12     public void upAll(Customer customer);
13     public Customer getForIdName(String id,String name);
14     public Customer getForId(String id);
15     public void delete(String id);
16     public long getCountWithName(String name);
17     public long getCountWithId(String id);
18     public List<Customer> getCriteriaCustomers(CriteriaCustomer cc);
19 }

操作类

 1 package com.mvc.jdbc;
 2
 3 import java.sql.SQLException;
 4 import java.util.List;
 5
 6 import com.mvc.dao.CustomerDao;
 7 import com.mvc.dao.Dao;
 8 import com.mvc.domain.CriteriaCustomer;
 9 import com.mvc.domain.Customer;
10
11 public class CustomerDaoJdbc extends Dao<Customer> implements CustomerDao{
12
13     @Override
14     public List<Customer> getAll(){
15         // TODO Auto-generated method stub
16         String sql = "SELECT * FROM customer";
17         return getForList(sql);
18     }
19
20     @Override
21     public void save(Customer customer) {
22         // TODO Auto-generated method stub
23         String sql = "insert into customer(id,name,address,phone,count) value(?,?,?,?,?)";
24         updata(sql,customer.getId(),customer.getName(),customer.getAddress(),customer.getPhone(),customer.getCount());
25
26     }
27
28     @Override
29     public void upAll(Customer customer) {
30         // TODO Auto-generated method stub
31         String sql = "UPDATE customer SET NAME=?,ADDRESS=?,PHONE=?  WHERE ID=?";
32         updata(sql,customer.getName(),customer.getAddress(),customer.getPhone(),customer.getId());
33
34     }
35
36     @Override
37     public void upCount(Customer customer) {
38         // TODO Auto-generated method stub
39         String sql = "UPDATE customer SET COUNT=? WHERE ID=?";
40         updata(sql,customer.getCount(),customer.getId());
41     }
42
43     @Override
44     public Customer getForIdName(String id,String name) {
45         // TODO Auto-generated method stub
46         String sql = "SELECT id,name,address,phone,count FROM customer where id = ? and name = ?";
47         return get(sql,id,name);
48     }
49     @Override
50     public Customer getForId(String id) {
51         // TODO Auto-generated method stub
52         String sql = "SELECT id,name,address,phone,count FROM customer where id = ?";
53         return get(sql,id);
54     }
55     @Override
56     public void delete(String id) {
57         // TODO Auto-generated method stub
58         String sql = "delete from customer where ID = ? ";
59         updata(sql,id);
60
61     }
62
63     @Override
64     public long getCountWithName(String name) {
65         // TODO Auto-generated method stub
66         String sql = "select count(id) from customer where name = ?";
67         return (long)getForValue(sql, name);
68     }
69
70     @Override
71     public List<Customer> getCriteriaCustomers(CriteriaCustomer cc) {
72         // TODO Auto-generated method stub
73         String sql = "SELECT * FROM customer WHERE NAME LIKE ? AND address LIKE ? AND phone LIKE ?";
74         System.out.println(cc.getName()+cc.getAddress()+cc.getPhone());
75         return getForList(sql,cc.getName(),cc.getAddress(),cc.getPhone());
76     }
77
78     @Override
79     public long getCountWithId(String id) {
80         // TODO Auto-generated method stub
81                 String sql = "select count(id) from customer where id= ?";
82                 return (long)getForValue(sql, id);
83     }
84
85
86
87
88
89
90
91
92
93 }

servlet

  1 package com.mvc.servlet;
  2
  3 import java.io.IOException;
  4 import java.lang.reflect.Method;
  5 import java.util.ArrayList;
  6 import java.util.List;
  7
  8 import javax.servlet.ServletException;
  9 import javax.servlet.annotation.WebServlet;
 10 import javax.servlet.http.HttpServlet;
 11 import javax.servlet.http.HttpServletRequest;
 12 import javax.servlet.http.HttpServletResponse;
 13
 14 import com.mvc.dao.CustomerDao;
 15 import com.mvc.domain.CriteriaCustomer;
 16 import com.mvc.domain.Customer;
 17 import com.mvc.jdbc.CustomerDaoJdbc;
 18 import com.sun.corba.se.impl.protocol.giopmsgheaders.Message;
 19
 20 import jdk.nashorn.internal.ir.RuntimeNode.Request;
 21
 22 /**
 23  * Servlet implementation class SqlServlet
 24  */
 25 @WebServlet("/SqlServlet")
 26 public class SqlServlet extends HttpServlet {
 27     private static final long serialVersionUID = 1L;
 28
 29     /**
 30      * @see HttpServlet#HttpServlet()
 31      */
 32     CustomerDao customerDao = null;
 33
 34     public SqlServlet() {
 35         super();
 36         // TODO Auto-generated constructor stub
 37         customerDao = new CustomerDaoJdbc();
 38     }
 39
 40     /**
 41      * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
 42      *      response)
 43      */
 44     protected void doGet(HttpServletRequest request,
 45             HttpServletResponse response) throws ServletException, IOException {
 46         // TODO Auto-generated method stub
 47         doPost(request, response);
 48     }
 49
 50     /**
 51      * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
 52      *      response)
 53      */
 54     protected void doPost(HttpServletRequest request,
 55             HttpServletResponse response) throws ServletException, IOException {
 56         // TODO Auto-generated method stub
 57         request.setCharacterEncoding("utf-8");
 58         String servletPath = request.getServletPath();
 59         // System.out.println(servletPath);
 60         servletPath = servletPath.substring(1, servletPath.length() - 3);
 61         try {
 62             Method method = getClass().getDeclaredMethod(servletPath,
 63                     HttpServletRequest.class, HttpServletResponse.class);
 64             method.invoke(this, request, response);
 65         } catch (Exception e) {
 66             // TODO Auto-generated catch block
 67             e.printStackTrace();
 68         }
 69
 70     }
 71
 72     @SuppressWarnings("unused")
 73     private void edit(HttpServletRequest request, HttpServletResponse response)
 74             throws ServletException, IOException {
 75         System.out.println("edit");
 76         String id = request.getParameter("id");
 77         System.out.println(id);
 78         Customer customer = customerDao.getForId(id);
 79         System.out.println(customer);
 80         request.setAttribute("customer", customer);
 81         request.getRequestDispatcher("/updata.jsp").forward(request, response);
 82     }
 83
 84     @SuppressWarnings("unused")
 85     private void updata(HttpServletRequest request, HttpServletResponse response)
 86             throws ServletException, IOException {
 87         System.out.println("updata");
 88         String id = request.getParameter("id");
 89         String name = request.getParameter("name");
 90         String address = request.getParameter("address");
 91         String phone = request.getParameter("phone");
 92         Customer customer = new Customer(id, name, address, phone);
 93         String massage;
 94         massage = "修改成功";
 95         customerDao.upAll(customer);
 96         request.setAttribute("massage", massage);
 97         request.setAttribute("customer", customer);
 98         request.getRequestDispatcher("/updata.jsp").forward(request, response);
 99
100     }
101
102     @SuppressWarnings("unused")
103     private void add(HttpServletRequest request, HttpServletResponse response)
104             throws ServletException, IOException {
105         System.out.println("add");
106         String id = request.getParameter("id");
107         String name = request.getParameter("name");
108         String address = request.getParameter("address");
109         String phone = request.getParameter("phone");
110         Customer customer = new Customer(id, name, address, phone);
111         System.out.println(customer);
112         long count = customerDao.getCountWithName(name);
113         long count1 = customerDao.getCountWithId(id);
114         System.out.println("count:" + count);
115         request.setAttribute("id", id);
116         request.setAttribute("name", name);
117         request.setAttribute("address", address);
118         request.setAttribute("phone", phone);
119         if (count1 > 0) {
120             request.setAttribute("massage", "学号已存在,报名失败");
121             request.getRequestDispatcher("/newcustomer.jsp").forward(request,
122                     response);
123         } else {
124             request.setAttribute("massage", "报名成功");
125             customerDao.save(customer);
126             request.getRequestDispatcher("/newcustomer.jsp").forward(request,
127                     response);
128         }
129     }
130
131     @SuppressWarnings("unused")
132     private void delete(HttpServletRequest request, HttpServletResponse response)
133             throws IOException {
134         System.out.println("delete");
135         String id = request.getParameter("id");
136         System.out.println(id);
137         //customerDao.delete(id);
138
139         //response.sendRedirect("query.do");
140     }
141
142     @SuppressWarnings("unused")
143     private void query(HttpServletRequest request, HttpServletResponse response) {
144         String name = request.getParameter("name");
145         String address = request.getParameter("address");
146         String phone = request.getParameter("phone");
147         System.out.println(name + address + phone);
148         System.out.println("query");
149         CriteriaCustomer cc = new CriteriaCustomer(name, address, phone);
150         List<Customer> customers = customerDao.getCriteriaCustomers(cc);
151         request.setAttribute("customers", customers);
152         try {
153             request.getRequestDispatcher("/ypacm507.jsp").forward(request,
154                     response);
155         } catch (ServletException | IOException e) {
156             // TODO Auto-generated catch block
157             e.printStackTrace();
158         }
159     }
160
161     @SuppressWarnings("unused")
162     private void come(HttpServletRequest request, HttpServletResponse response) {
163         String name = request.getParameter("name");
164         String id = request.getParameter("id");
165         Customer customer = customerDao.getForIdName(id, name);
166         System.out.println(customer);
167         if (customer != null) {
168             request.setAttribute("massage", "");
169             customer.setCount(customer.getCount() + 1);
170             customerDao.upCount(customer);
171                 //response.sendRedirect("NewFile_1.jsp");
172                 try {
173                     request.getRequestDispatcher("/NewFile_1.jsp").forward(request,
174                             response);
175                 } catch (ServletException | IOException e) {
176                     // TODO Auto-generated catch block
177                     e.printStackTrace();
178                 }
179
180         } else {
181             try {
182                 String massage = "名字或学号错误";
183                 request.setAttribute("massage", massage);
184                 request.setAttribute("id", id);
185                 request.setAttribute("name", name);
186                 request.getRequestDispatcher("/come.jsp").forward(request,
187                         response);
188             } catch (ServletException | IOException e) {
189                 // TODO Auto-generated catch block
190                 e.printStackTrace();
191             }
192         }
193     }
194 }

以下jsp代码 css样式等为网上找的素材

1.增加用户的jsp

 1 <%@ page language="java" contentType="text/html; charset=utf-8"
 2     pageEncoding="utf-8"%>
 3 <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
 4 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
 5 <html>
 6 <head>
 7 <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
 8 <!--[if IE]><meta http-equiv="x-ua-compatible" content="IE=9" /><![endif]-->
 9 <meta name="viewport" content="width=device-width, initial-scale=1">
10  <meta name="description" content="Your Description Here">
11  <meta name="keywords"
12     content="bootstrap themes, portfolio, responsive theme">
13 <meta name="author" content="ThemeForces.Com">
14
15 <!-- Favicons
16     ================================================== -->
17   <!-- <link rel="shortcut-icon" href="img/favicon.ico" type="image/x-icon"> -->
18  <!-- <link rel="apple-touch-icon" href="img/apple-touch-icon.png">  -->
19    <link rel="apple-touch-icon" sizes="72x72"
20     href="img/apple-touch-icon-72x72.png">
21  <link rel="apple-touch-icon" sizes="114x114"
22     href="img/apple-touch-icon-114x114.png">
23
24 <!-- Bootstrap -->
25   <link rel="stylesheet" type="text/css" href="css/bootstrap.css">
26 <!-- <link rel="stylesheet" type="text/css"
27     href="fonts/font-awesome/css/font-awesome.css"> -->
28
29 <!-- Stylesheet
30     ================================================== -->
31   <link rel="stylesheet" type="text/css" href="css/style.css">
32    <!--  <link rel="stylesheet" type="text/css" href="css/responsive.css"> -->
33
34 <!-- <script type="text/javascript" src="js/modernizr.custom.js"></script> -->
35
36
37 <title></title>
38 </head>
39 <body>
40     <h3 style="text-align: center;"><font color="red"><c:out value="${massage}"></c:out></font></h3>
41     <div id="tf-contact">
42         <div class="container">
43             <div class="section-title">
46                 <hr>
47             </div>
48
49             <div class="space"></div>
50
51             <div class="row">
52                 <div class="col-md-6 col-md-offset-3">
53                     <form id="contact" action="add.do" method="post">
54                         <div class="form-group">
55                             <input class="form-control" id="exampleInputEmail1" type="text"
56                                 name="id" value="${id}" placeholder="长学号" />
57                         </div>
58
59                         <div class="form-group">
60                             <input class="form-control" type="text" name="name"
61                                 value="${name}" placeholder="姓名" />
62                         </div>
63
64
65                         <div class="form-group">
66                             <input class="form-control" type="text" name="address"
67                                 value="${address}" placeholder="班级" />
68                         </div>
69
70                         <td><div class="form-group">
71                                 <input class="form-control" type="text" name="phone"
72                                     value="${phone}" placeholder="手机" />
73                             </div>
74                             <input class="btn btn-primary my-btn dark" type="submit"
75                             value="--报名--" />
76                     </form>
77                 </div>
78             </div>
79         </div>
80     </div>
81     <!--  <script type="text/javascript" src="js/jquery.1.11.1.js"></script>-->
82     <!-- Include all compiled plugins (below), or include individual files as needed -->
83     <!--  <script type="text/javascript" src="js/bootstrap.js"></script> -->
84
85     <!-- Javascripts
86     ================================================== -->
87      <!--  <script type="text/javascript" src="js/main.js"></script>-->
88 </body>
89 </html>

2.查询

 1 <%@ page language="java" contentType="text/html; charset=UTF-8"
 2     pageEncoding="UTF-8"%>
 3 <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
 4
 5 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
 6 <html>
 7 <head>
 8 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
 9 <title>Insert title here</title>
10 <script type="text/javascript" src="scripts/jquery-1.7.2.js"></script>
11 <script type="text/javascript">
21 </script>
22 </head>
23 <body>
24
25     <form action="query.do" method="post">
26         <table>
27             <tr>
28                 <td>CustomerName:</td>
29                 <td><input type="text" name="name"/></td>
30             </tr>
31             <tr>
32                 <td>Address:</td>
33                 <td><input type="text" name="address"/></td>
34             </tr>
35             <tr>
36                 <td>Phone:</td>
37                 <td><input type="text" name="phone"/></td>
38             </tr>
39             <tr>
40                 <td><input type="submit" value="Query"/></td>
41                 <td><a href="newcustomer.jsp">Add New Customer</a></td>
42             </tr>
43         </table>
44     </form>
45
46     <br><br>
47
48     <c:if test="${!empty requestScope.customers }">
49
50         <hr>
51         <br><br>
52
53         <table border="1" cellpadding="10" cellspacing="0">
54             <tr>
55                 <th>^ID</th>
56                 <th>CustomerName</th>
57                 <th>Address</th>
58                 <th>Phone</th>
59                 <th>UPDATE\DELETE</th>
60             </tr>
61
62             <c:forEach items="${requestScope.customers }" var="cust">
63
64                     <tr>
65                         <td>${cust.id }</td>
66                         <td>${cust.name }</td>
67                         <td>${cust.address }</td>
68                         <td>${cust.phone }</td>
69                         <td>
70                             <c:url value="/edit.do" var="editurl">
71                                 <c:param name="id" value="${cust.id }"></c:param>
72                             </c:url>
73                             <a href="${editurl }">UPDATE</a>
74                             <c:url value="/delete.do" var="deleteurl">
75                                 <c:param name="id" value="${cust.id }"></c:param>
76                             </c:url>
77                             <a href="${deleteurl }" class="delete">DELETE</a>
78                         </td>
79                     </tr>
80
81             </c:forEach>
82
83         </table>
84     </c:if>
85
86 </body>
87 </html>

3.删除

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>    

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script type="text/javascript" src="scripts/jquery-1.7.2.js"></script>

</head>
<body>

    <form action="query.do" method="post">
        <table>
            <tr>
                <td>CustomerName:</td>
                <td><input type="text" name="name"/></td>
            </tr>
            <tr>
                <td>Address:</td>
                <td><input type="text" name="address"/></td>
            </tr>
            <tr>
                <td>Phone:</td>
                <td><input type="text" name="phone"/></td>
            </tr>
            <tr>
                <td><input type="submit" value="Query"/></td>
                <td><a href="newcustomer.jsp">Add New Customer</a></td>
            </tr>
        </table>
    </form>

    <br><br>

    <c:if test="${!empty requestScope.customers }">

        <hr>
        <br><br>

        <table border="1" cellpadding="10" cellspacing="0">
            <tr>
                <th>^ID</th>
                <th>CustomerName</th>
                <th>Address</th>
                <th>Phone</th>
                <th>UPDATE\DELETE</th>
            </tr>

            <c:forEach items="${requestScope.customers }" var="cust">

                    <tr>
                        <td>${cust.id }</td>
                        <td>${cust.name }</td>
                        <td>${cust.address }</td>
                        <td>${cust.phone }</td>
                        <td>
                            <c:url value="/edit.do" var="editurl">
                                <c:param name="id" value="${cust.id }"></c:param>
                            </c:url>
                            <a href="${editurl }">UPDATE</a>
                            <c:url value="/delete.do" var="deleteurl">
                                <c:param name="id" value="${cust.id }"></c:param>
                            </c:url>
                            <a href="${deleteurl }" class="delete">DELETE</a>
                        </td>
                    </tr>

            </c:forEach>

        </table>
    </c:if>

</body>
</html>

4.修改

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<!--[if IE]><meta http-equiv="x-ua-compatible" content="IE=9" /><![endif]-->
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="Your Description Here">
<meta name="keywords"
    content="bootstrap themes, portfolio, responsive theme">
<meta name="author" content="ThemeForces.Com">

<!-- Favicons
    ================================================== -->
<link rel="shortcut icon" href="img/favicon.ico" type="image/x-icon">
<link rel="apple-touch-icon" href="img/apple-touch-icon.png">
<link rel="apple-touch-icon" sizes="72x72"
    href="img/apple-touch-icon-72x72.png">
<link rel="apple-touch-icon" sizes="114x114"
    href="img/apple-touch-icon-114x114.png">

<!-- Bootstrap -->
<link rel="stylesheet" type="text/css" href="css/bootstrap.css">
<link rel="stylesheet" type="text/css"
    href="fonts/font-awesome/css/font-awesome.css">

<!-- Stylesheet
    ================================================== -->
<link rel="stylesheet" type="text/css" href="css/style.css">
<link rel="stylesheet" type="text/css" href="css/responsive.css">

<script type="text/javascript" src="js/modernizr.custom.js"></script>

<title></title>
</head>
<body>

    <c:if test="${requestScope.massage != null }">
        <br>
        <h3 style="text-align: center;"><font color="red"><c:out value="${massage}"></c:out></font></h3>
        <br>
        <br>
    </c:if>

    <c:set var="id" value="${customer != null ? customer.id : param.id }"></c:set>

    <c:set var="name"
        value="${customer != null ? customer.name : param.name }"></c:set>
    <c:set var="address"
        value="${customer != null ? customer.address : param.address }"></c:set>
    <c:set var="phone"
        value="${customer != null ? customer.phone : param.phone }"></c:set>
    <div id="tf-contact">
        <div class="container">
            <div class="section-title">

                <hr>
            </div>

            <div class="space"></div>

            <div class="row">
                <div class="col-md-6 col-md-offset-3">
                    <form id="contact" action="updata.do" method="post">
                    <input type="hidden" name="id" value="${id }"></input>
                        <div class="form-group">
                            <h4>姓名:</h4>
                            <input class="form-control" type="text" name="name"
                                value="${name}" placeholder="姓名" />
                        </div>

                        <div class="form-group">
                            <h4>班级:</h4>
                            <input class="form-control" type="text" name="address"
                                value="${address}" placeholder="班级" />
                        </div>

                        <div class="form-group">
                                <h4>手机:</h4>
                                <input class="form-control" type="text" name="phone"
                                    value="${phone}" placeholder="手机" />
                            </div> <input class="btn btn-primary my-btn dark" type="submit"
                            value="修改" />
                    </form>
                </div>
            </div>
        </div>
    </div>
    <script type="text/javascript" src="js/jquery.1.11.1.js"></script>
    <!-- Include all compiled plugins (below), or include individual files as needed -->
    <script type="text/javascript" src="js/bootstrap.js"></script>

    <!-- Javascripts
    ================================================== -->
    <script type="text/javascript" src="js/main.js"></script>
</body>
</html>

运行效果 增加信息

数据库内数据

时间: 2024-10-25 04:26:54

简单MVC实现增删改查的相关文章

数往知来 ASP.NET MVC HtmlHelper、MVC快速增删改查 Cache MVC3客户端验证 MVC隐式异步提交 &lt;二十八&gt;

一.HtmlHelper.MVC快速增删改查 MVC 在MVC里面请求首先到控制器-->然后 -->数据库数据放在APP_DATE文件夹里, -->js.css文件放在content文件夹里 -->控制器放在Controllers里,控制器要以controller结尾 控制器下面的所有方法都称为action 2)webform跟 aspnet MVC:区别请求的地址不一样了 MVC请求的是控制器下面的action webform:aspx页面或者是一般处理程序 -->a标签

【Mybatis】简单的mybatis增删改查模板

简单的mybatis增删改查模板: <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" > <mapper namespace="com.sunee

Mybatis实现简单的数据库增删改查操作

Mybatis实现简单的数据库增删改查操作 框架:mybatis(3.5.2) 数据库:mysql 工具:idea 1.新建一个maven项目,在pom文件中添加mybatis依赖及MySQL依赖 <!-- mybatis核心依赖 --> <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis --> <dependency> <groupId>org.mybatis</groupId&g

MVC——数据库增删改查

MVC: V(View) :视图→就是页面的模板 C(Control): 控制器→客户主要面对的就是控制器, M(Model):模板→在模板里面主要就是写关于数据库的各种增删改查的方法 它们之间的关系就是→ 在控制器里调用模板里的方法,然后把得到的数据传到视图里,视图就会把得到的数据添加到自己的页面上,在通过视图里反馈的值传到控制器上.以实现对数据库的操作和控制器页面的显示.(大概是这样) 下面是对数据库增删改查的代码 一.各种数据库操作的方法(增删改查) namespace 数据库增删改查.M

富文本内容简单的的增删改查

由于html本身的textarea标签的文本编辑功能较为简单,不能设置文字的样式,因此需要富文本控件来增强textarea的功能.       一些常见的富文本控件有:UEditor.kindeditor.simditor.bootstrap-wysiwyg.wangEditor.CKEditor.tinymce,各有优缺点,网上也有对不介绍,不再赘述. 此处选用tinymce,因其兼容性较好,插入页面也较为简单,此外还有丰富的插件可以扩展功能. 首先,在页面上使用tinymce:1.引入js文

Salesforce零基础(三)简单的数据增删改查页面的构建(Ajax样式)

VisualForce封装了很多的标签用来进行页面设计 下面以一个单一的表进行数据增删改查.表结构如图1所示.通过图可以看出GOODS表自己定义的参数主要包括以下: GoodsName__c,GoodsType__c,GoodsBrand__c,GoodsDescribe__c,GoodsPrice__c. 图1 VF每个页面都是以<apex:page>标签起始</apex:page>结束,每个VF页面都有一个Controller用来控制其业务逻辑.本篇例子中主要用到的控件包括如下

MVC——数据库增删改查(Razor)——Html语法

一.显示界面 1.Models(模板) private MyDBDataContext _context = new MyDBDataContext(); public List<Info> Select() //查询 { return _context.Info.ToList(); } 2.Contrallers(控制器) public ActionResult Index() { //在这里没用ViewBag List<Info> list = new InfoBF().Sel

MVC——数据库增删改查(Razor)

一.显示信息 1.Models(模板) private MyDBDataContext _context = new MyDBDataContext(); //定义一个变量取出所有数据 public List<Student> Select() { return _context.Student.ToList();//把所有数据都显示出来,全部查询 } 2.Controllers(控制器) public ActionResult Index()//显示信息 { ViewBag.data = n

Asp.net简单三层+Sqllite 增删改查

新建项目à新建一个空白解决方案 在Model新建一个实体类 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks;     namespace factory.Model {     public class factorys     {     //ID INTEGER PRIMARY KEY AUTOINCREMENT