前几次更新博客都是每次周日晚上到周一,这次是周一晚上开始写,肯定也是有原因的!那就是我的 Tomact 忽然报错,无法启动,错误信息如下!同时我的 win10 也崩了,重启之后连 WIFI 的标志也不见了,上不了网。额。额。额。。。后面连 IDEA 也报错,就很无奈!不过现在能写也就是我把他折腾好了!原因很简单就是执行了下面简单的几句命令后重启就可以上网了,我对这方面的知识不是很熟悉但应该重置网络方面的东西!接着 Tomact 的报错也熟悉了 --- 端口被占用!这都是小事,改好端口就开始本周的学习之路!cmd 命令:
ipconfig /flushdns netsh int ip rese netsh winsock reset
Tomac报错如图(错误太多我就折叠了,懂的大神还望指教):
Microsoft Windows [版本 10.0.16296.0]
(c) 2017 Microsoft Corporation。保留所有权利。 C:\Users\lenovo>catalina run
Using CATALINA_BASE: D:\apache-tomcat-6.0.16
Using CATALINA_HOME: D:\apache-tomcat-6.0.16
Using CATALINA_TMPDIR: D:\apache-tomcat-6.0.16\temp
Using JRE_HOME: D:\Java\jdk1.7.0_71
十一月 19, 2017 8:05:03 下午 org.apache.catalina.core.AprLifecycleListener init
信息: The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: D:\Java\jdk1.7.0_71\bin;C:\WINDOWS\Sun\Java\bin;C:\WINDOWS\system32;C:\WINDOWS;c:\gtk\bin;F:\app\yin‘zhao\product\11.2.0\client_1\bin;:\orcal\product\11.2.0\dbhome_1\bin;C:\Program Files (x86)\Intel\iCLS Client\;D:\gradle\gradle-4.2\bin;C:\Program Files\Intel\iCLS Client\;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\IPT;C:\Program Files\Intel\Intel(R) Management Engine Components\IPT;C:\Program Files (x86)\NVIDIA Corporation\PhysX\Common;C:\Program Files\Intel\WiFi\bin\;C:\Program Files\Common Files\Intel\WirelessCommon\;C:\Program Files (x86)\Microsoft SQL Server\100\Tools\Binn\;C:\Program Files\Microsoft SQL Server\100\Tools\Binn\;C:\Program Files\Microsoft SQL Server\100\DTS\Binn\;C:\Program Files (x86)\Microsoft SQL Server\100\Tools\Binn\VSShell\Common7\IDE\;C:\Program Files (x86)\Microsoft Visual Studio 9.0\Common7\IDE\PrivateAssemblies\;C:\Program Files (x86)\Microsoft SQL Server\100\DTS\Binn\;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\Program Files\Microsoft SQL Server\130\Tools\Binn\;C:\Users\lenovo\AppData\Local\Microsoft\WindowsApps;C:\Program Files\MySQL\MySQL Utilities 1.6\;D:\Java\jdk1.7.0_71\bin;D:\apache-tomcat-6.0.16\bin;F:\Git\cmd;C:\TortoiseGit\bin;F:\nodejs\;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;D:\Java\jdk1.7.0_71\jre\bin;C:\Users\lenovo\AppData\Local\Microsoft\WindowsApps;F:\nodejs\node_global;C:\Users\lenovo\AppData\Local\GitHubDesktop\bin;%USERPROFILE%\AppData\Local\Microsoft\WindowsApps;;.
十一月 19, 2017 8:05:03 下午 org.apache.coyote.http11.Http11Protocol init
严重: Error initializing endpoint
java.net.SocketException: Protocol wrong type for socket: create
at java.net.ServerSocket.createImpl(ServerSocket.java:308)
at java.net.ServerSocket.getImpl(ServerSocket.java:257)
at java.net.ServerSocket.bind(ServerSocket.java:376)
at java.net.ServerSocket.<init>(ServerSocket.java:237)
at java.net.ServerSocket.<init>(ServerSocket.java:181)
at org.apache.tomcat.util.net.DefaultServerSocketFactory.createSocket(DefaultServerSocketFactory.java:50)
at org.apache.tomcat.util.net.JIoEndpoint.init(JIoEndpoint.java:496)
at org.apache.coyote.http11.Http11Protocol.init(Http11Protocol.java:176)
at org.apache.catalina.connector.Connector.initialize(Connector.java:1058)
at org.apache.catalina.core.StandardService.initialize(StandardService.java:677)
at org.apache.catalina.core.StandardServer.initialize(StandardServer.java:795)
at org.apache.catalina.startup.Catalina.load(Catalina.java:530)
at org.apache.catalina.startup.Catalina.load(Catalina.java:550)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.apache.catalina.startup.Bootstrap.load(Bootstrap.java:260)
at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:412) 十一月 19, 2017 8:05:03 下午 org.apache.catalina.startup.Catalina load
严重: Catalina.start
LifecycleException: Protocol handler initialization failed: java.net.SocketException: Protocol wrong type for socket: create
at org.apache.catalina.connector.Connector.initialize(Connector.java:1060)
at org.apache.catalina.core.StandardService.initialize(StandardService.java:677)
at org.apache.catalina.core.StandardServer.initialize(StandardServer.java:795)
at org.apache.catalina.startup.Catalina.load(Catalina.java:530)
at org.apache.catalina.startup.Catalina.load(Catalina.java:550)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.apache.catalina.startup.Bootstrap.load(Bootstrap.java:260)
at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:412) 十一月 19, 2017 8:05:03 下午 org.apache.catalina.startup.Catalina load
信息: Initialization processed in 362 ms
十一月 19, 2017 8:05:03 下午 org.apache.catalina.core.StandardService start
信息: Starting service Catalina
十一月 19, 2017 8:05:03 下午 org.apache.catalina.core.StandardEngine start
信息: Starting Servlet Engine: Apache Tomcat/6.0.16
十一月 19, 2017 8:05:04 下午 org.apache.catalina.core.StandardContext addApplicationListener
信息: The listener "listeners.ContextListener" is already configured for this context. The duplicate definition has been ignored.
十一月 19, 2017 8:05:04 下午 org.apache.catalina.core.StandardContext addApplicationListener
信息: The listener "listeners.SessionListener" is already configured for this context. The duplicate definition has been ignored.
十一月 19, 2017 8:05:04 下午 org.apache.coyote.http11.Http11Protocol start
严重: Error starting endpoint
java.net.SocketException: Protocol wrong type for socket: create
at java.net.ServerSocket.createImpl(ServerSocket.java:308)
at java.net.ServerSocket.getImpl(ServerSocket.java:257)
at java.net.ServerSocket.bind(ServerSocket.java:376)
at java.net.ServerSocket.<init>(ServerSocket.java:237)
at java.net.ServerSocket.<init>(ServerSocket.java:181)
at org.apache.tomcat.util.net.DefaultServerSocketFactory.createSocket(DefaultServerSocketFactory.java:50)
at org.apache.tomcat.util.net.JIoEndpoint.init(JIoEndpoint.java:496)
at org.apache.tomcat.util.net.JIoEndpoint.start(JIoEndpoint.java:515)
at org.apache.coyote.http11.Http11Protocol.start(Http11Protocol.java:203)
at org.apache.catalina.connector.Connector.start(Connector.java:1131)
at org.apache.catalina.core.StandardService.start(StandardService.java:531)
at org.apache.catalina.core.StandardServer.start(StandardServer.java:710)
at org.apache.catalina.startup.Catalina.start(Catalina.java:578)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:288)
at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:413) 十一月 19, 2017 8:05:04 下午 org.apache.catalina.startup.Catalina start
严重: Catalina.start:
LifecycleException: service.getName(): "Catalina"; Protocol handler start failed: java.net.SocketException: Protocol wrong type for socket: create
at org.apache.catalina.connector.Connector.start(Connector.java:1138)
at org.apache.catalina.core.StandardService.start(StandardService.java:531)
at org.apache.catalina.core.StandardServer.start(StandardServer.java:710)
at org.apache.catalina.startup.Catalina.start(Catalina.java:578)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:288)
at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:413) 十一月 19, 2017 8:05:04 下午 org.apache.catalina.startup.Catalina start
信息: Server startup in 515 ms
十一月 19, 2017 8:05:04 下午 org.apache.catalina.core.StandardServer await
严重: StandardServer.await: create[8005]:
java.net.SocketException: Protocol wrong type for socket: create
at java.net.ServerSocket.createImpl(ServerSocket.java:308)
at java.net.ServerSocket.getImpl(ServerSocket.java:257)
at java.net.ServerSocket.bind(ServerSocket.java:376)
at java.net.ServerSocket.<init>(ServerSocket.java:237)
at org.apache.catalina.core.StandardServer.await(StandardServer.java:373)
at org.apache.catalina.startup.Catalina.await(Catalina.java:642)
at org.apache.catalina.startup.Catalina.start(Catalina.java:602)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:288)
at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:413) 十一月 19, 2017 8:05:04 下午 org.apache.coyote.http11.Http11Protocol pause
信息: Pausing Coyote HTTP/1.1 on http-9090
十一月 19, 2017 8:05:04 下午 org.apache.catalina.connector.Connector pause
严重: Protocol handler pause failed
java.lang.NullPointerException
at org.apache.jk.server.JkMain.pause(JkMain.java:679)
at org.apache.jk.server.JkCoyoteHandler.pause(JkCoyoteHandler.java:153)
at org.apache.catalina.connector.Connector.pause(Connector.java:1073)
at org.apache.catalina.core.StandardService.stop(StandardService.java:563)
at org.apache.catalina.core.StandardServer.stop(StandardServer.java:744)
at org.apache.catalina.startup.Catalina.stop(Catalina.java:628)
at org.apache.catalina.startup.Catalina$CatalinaShutdownHook.run(Catalina.java:671) 十一月 19, 2017 8:05:05 下午 org.apache.catalina.core.StandardService stop
信息: Stopping service Catalina
十一月 19, 2017 8:05:05 下午 org.apache.catalina.connector.MapperListener destroy
警告: Error unregistering MBeanServerDelegate
java.lang.NullPointerException
at org.apache.catalina.connector.MapperListener.destroy(MapperListener.java:162)
at org.apache.catalina.connector.Connector.stop(Connector.java:1179)
at org.apache.catalina.core.StandardService.stop(StandardService.java:593)
at org.apache.catalina.core.StandardServer.stop(StandardServer.java:744)
at org.apache.catalina.startup.Catalina.stop(Catalina.java:628)
at org.apache.catalina.startup.Catalina$CatalinaShutdownHook.run(Catalina.java:671) 十一月 19, 2017 8:05:05 下午 org.apache.coyote.http11.Http11Protocol destroy
信息: Stopping Coyote HTTP/1.1 on http-9090
十一月 19, 2017 8:05:05 下午 org.apache.catalina.connector.Connector stop
严重: Coyote connector has not been started
============================================================================================================================================================
接下来就开始介绍我们今天的主题 -- MVC 小案例
我先大概介绍我练习的这个小案例,主要所用知识有 JSP, Servlet, C3p0, DBUtils, Mysql 数据库, IDEA 开发环境
数据库(Mysql),其中 ID 为主键,且自增,customer_name 不为空,且不可以有相同值,如下
CREATE TABLE customer (
id INT,
customer_name VARCHAR(10) NOT NULL UNIQUE,
customer_address VARCHAR(20),
customer_phone VARCHAR(10),
customer_thing VARCHAR(20)
)
接着说一下我们项目的目录结构,我们这个案例并不是特别大,但也应该有好的目录结构,我们要有这样的好习惯,要不怕麻烦,为自己以后看的时候提供便利(如果有不懂的,接下来将会为大家进行详细的讲解):
再强调一遍在 IDEA 中我们一般导包都是将所使用的包封装为一个 library,哪个项目需要就直接导入 library 就好,但是对于连接数据库应该将其加入 lib 目录,这样项目才可以找到对应的包(因为这个错,由 eclipse 转 IDEA 的我废了我好多时间)。
首先我们从获取数据库连接开始,我们使用的是 c3p0 数据库连接池,其配置文件以及获取数据库连接和释放数据库连接的代码如下(项目中的 JDBCTools.java),这个没有什么可说的,我前面的博文也讲过。
<?xml version="1.0" encoding="UTF-8" ?>
<c3p0-config>
<named-config name="mvcC3p0">
<property name="user">root</property>
<property name="password">zy961029</property>
<property name="driverClass">com.mysql.jdbc.Driver</property>
<property name="jdbcUrl">jdbc:mysql:///sh_db</property> <property name="maxStatements">1</property>
<property name="maxStatementsPerConnection">5</property>
</named-config>
</c3p0-config>
JDBCTools.java
package com.java.homework.db; import com.mchange.v2.c3p0.ComboPooledDataSource; import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException; /**
* 获取数据库连接和释放数据库连接的工具类
*/
public class JDBCTools { // 由于静态代码块只执行一次,所以只会创建一份 dataSource,达到节省资源的目的,并且将工具类方法声明为静态的,可由类直接调用
private static DataSource dataSource = null; static {
dataSource = new ComboPooledDataSource("mvcC3p0");
} public static Connection getConnection() {
Connection connection = null;
try {
connection = dataSource.getConnection();
} catch (SQLException e) {
e.printStackTrace();
}
return connection;
} public static void reledse(Connection connection) {
try {
if (connection != null) {
connection.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
获取到数据库连接之后我们开始我们共有的 DAO 方法,本案例中我们只是操作 Customer 一个数据表,也就只有 CustomerDao 接口,对于复杂的案例不止一个表,那么这样的一个 DAO 基类将会是特别有用的,其包括了增、删、改、查方法。同时针对我们数据表创建其对应的 domain 类。
DAO.java
package com.java.homework.dao; import com.java.homework.db.JDBCTools;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler; import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List; /**
* 封装 CRUD 的方法,
* 利用 C3P0 数据库连接池和 DBUtils 连接数据库
* 注意 type 的获取方法,直接在构造器中初始化,为 BeanHandler、BeanListHandler 传值
* @param <T> 当前 DAO 处理的实体类类型
*/
public class DAO<T> { private QueryRunner queryRunner;
private Class<T> type; /*
* 构造器直接初始化 queryRunner 对象和 BeanHandler 和 BeanListHandler 所需要的 Class 对象(利用反射创建,使其更有可扩展性)
* */
public DAO() {
queryRunner = new QueryRunner(); Type superclass = getClass().getGenericSuperclass();
if (superclass instanceof ParameterizedType) {
ParameterizedType parameterizedType = (ParameterizedType) superclass; Type[] args = parameterizedType.getActualTypeArguments();
if (args != null && args.length > 0) {
if (args[0] instanceof Class) {
type = (Class<T>) args[0];
}
}
}
} /*
* 封装了增删改的方法
* */
public void update(String sql, Object...args) {
Connection connection = JDBCTools.getConnection();
try {
queryRunner.update(connection, sql, args );
} catch (SQLException e) {
e.printStackTrace();
}finally {
JDBCTools.reledse(connection);
}
} /*
获取单个值,比如某一列的某一个值,或 count 值
*/
public Object getForValue(String sql, Object...args){
Connection connection = JDBCTools.getConnection();
Object value = null;
try {
value = queryRunner.query(connection, sql, new ScalarHandler(), args);
} catch (SQLException e) {
e.printStackTrace();
} finally {
JDBCTools.reledse(connection);
}
return value;
} /*
* 获取多行值,封装为 List 返回
* */
public List<T> getForList(String sql, Object...args) {
Connection connection = JDBCTools.getConnection();
List<T> list = null;
try {
list = queryRunner.query(connection, sql, new BeanListHandler<T>(type),args);
} catch (SQLException e) {
e.printStackTrace();
}finally {
JDBCTools.reledse(connection);
}
return list;
} /*
* 获取单列值
* */
public T get(String sql, Object...args){
Connection connection = JDBCTools.getConnection();
T entity = null;
try {
entity = queryRunner.query(connection, sql, new BeanHandler<T>(type), args);
} catch (SQLException e) {
e.printStackTrace();
}finally {
JDBCTools.reledse(connection);
}
return entity;
}
}
Customer.java
package com.java.homework.domain; public class Customer { private Integer id;
private String customerName;
private String customerAddress;
private String customerPhone;
private String customerThing; @Override
public String toString() {
return "Customer{" +
"id=" + id +
", customerName='" + customerName + '\'' +
", customerAddress='" + customerAddress + '\'' +
", customerPhone='" + customerPhone + '\'' +
", customerThing='" + customerThing + '\'' +
'}';
} public Integer getId() {
return id;
} public void setId(Integer id) {
this.id = id;
} public String getCustomerName() {
return customerName;
} public void setCustomerName(String customerName) {
this.customerName = customerName;
} public String getCustomerAddress() {
return customerAddress;
} public void setCustomerAddress(String customerAddress) {
this.customerAddress = customerAddress;
} public String getCustomerPhone() {
return customerPhone;
} public void setCustomerPhone(String customerPhone) {
this.customerPhone = customerPhone;
} public String getCustomerThing() {
return customerThing;
} public void setCustomerThing(String customerThing) {
this.customerThing = customerThing;
} // 为了方便测试我们写一个带参的构造器
public Customer(Integer id, String customerName, String customerAddress, String customerPhone, String customerThing) {
this.id = id;
this.customerName = customerName;
this.customerAddress = customerAddress;
this.customerPhone = customerPhone;
this.customerThing = customerThing;
}
// 由于需要利用反射,所以必须写无参构造器
public Customer() {
}
}
有了 DAO 类之后我们便要针对于我们案例去定制操作数据表的方法,并将其封装为一个接口:
CustomerDao.java
package com.java.homework.dao; import com.java.homework.criteria.CriteriaCustomer;
import com.java.homework.domain.Customer; import java.sql.SQLException;
import java.util.List; /**
* 针对本数据表封装所需功能的方法,将其封装为一个接口
*/
public interface CustomerDao {
// 获得数据表的所有值
List<Customer> getAll();
// 根据 id 获取单行
Customer get(Integer id) throws SQLException;
// 执行删除操作
void delete(Integer id) throws SQLException;
// 执行保存操作
void save(Customer customer) throws SQLException;
// 根据 customerName 获取与之匹配行的行数
Long getCountWithName(String name1) throws SQLException;
// 模糊查询,将查询条件封装为一个单类,CriteriaCustomer。因为有些查询条件并不是像本案例一样和 Customer 基类一样
List<Customer> getListOfLike(CriteriaCustomer criteriaCustomer);
// 执行更新操作
void update(Customer customer, Integer id);
// 获取 customerName
Object getCusName(Integer id);
}
接下来就是实现我们所写的接口,该类 继承自 DAO.java 和 CustomerDao.java 实现 CustomerDao.java 方法,如下:
CustomerDaoImpl.java
package com.java.homework.daoImpl; import com.java.homework.criteria.CriteriaCustomer;
import com.java.homework.dao.CustomerDao;
import com.java.homework.dao.DAO;
import com.java.homework.domain.Customer; import java.sql.SQLException;
import java.util.List; /**
* 继承 DAO 类实现 CustomerDao 接口
*/
public class CustomerDaoImpl extends DAO<Customer> implements CustomerDao { @Override
public List<Customer> getAll() {
String sql = "SELECT id, customer_name customerName, customer_address customerAddress, customer_phone customerPhone," +
"customer_thing customerThing FROM customer";
List<Customer> customerList;
customerList = getForList(sql);
return customerList;
} @Override
public Customer get(Integer id) throws SQLException {
String sql = "SELECT id,customer_name customerName, customer_address customerAddress, customer_phone customerPhone," +
"customer_thing customerThing FROM customer WHERE id=?";
return get(sql, id);
} @Override
public void delete(Integer id) throws SQLException {
String sql = "DELETE FROM customer WHERE id=?";
update(sql, id);
} @Override
public void save(Customer customer) throws SQLException {
String sql = "INSERT INTO customer(customer_name, customer_address, customer_phone, customer_thing) VALUES(" +
"?,?,?,?)";
update(sql, customer.getCustomerName(), customer.getCustomerAddress(), customer.getCustomerPhone(), customer.getCustomerThing());
} @Override
public Long getCountWithName(String name) throws SQLException {
Long value;
String sql = "SELECT COUNT(id) FROM customer WHERE customer_name=?";
value = (Long) getForValue(sql, name);
return value;
} @Override
public List<Customer> getListOfLike(CriteriaCustomer criteriaCustomer) {
String sql = "SELECT id, customer_name customerName, customer_address customerAddress, customer_phone customerPhone," +
"customer_thing customerThing FROM customer WHERE customer_name LIKE ? AND customer_address LIKE ? AND " +
"customer_phone LIKE ? AND customer_thing LIKE ?"; return getForList(sql, criteriaCustomer.getCustomerName(), criteriaCustomer.getCustomerAddress(), criteriaCustomer
.getCustomerPhone(), criteriaCustomer.getCustomerThing());
} @Override
public void update(Customer customer, Integer id) {
String sql = "UPDATE customer SET customer_name=?, customer_address=?, customer_phone=?," +
" customer_thing=? WHERE id=?";
update(sql, customer.getCustomerName(), customer.getCustomerAddress(), customer.getCustomerPhone(), customer.getCustomerThing(), id);
} @Override
public Object getCusName(Integer id) {
String sql = "SELECT customer_name customerName FROM customer WHERE id=?";
return getForValue(sql, id);
}
}
写到这里我们已经写了不少的方法了,在一个案例甚至以后的项目中我们每写好一个方法都应该去测试,以免后面大量的错误不容易定位,下面的代码包括了我所写的所有的测试方法,后面的几个的方法就不在单独放出了,记得都在这就好:
package homeworl.test; import com.java.homework.criteria.CriteriaCustomer;
import com.java.homework.dao.CustomerDao;
import com.java.homework.daoImpl.CustomerDaoImpl;
import com.java.homework.db.JDBCTools;
import com.java.homework.domain.Customer;
import org.junit.Test; import java.sql.Connection;
import java.sql.SQLException;
import java.util.List; /**
* Created by shkstart on 2017/11/13.
*/
public class TestCustomerDaoImpl { private CustomerDao customerDao = new CustomerDaoImpl();
@Test
public void testGetForList() {
List<Customer> customerList = customerDao.getAll();
System.out.println(customerList);
} @Test
public void testGetConnection() {
Connection connection = JDBCTools.getConnection();
System.out.println(connection);
} @Test
public void testGet() throws SQLException {
Customer customer = customerDao.get(1);
System.out.println(customer);
} @Test
public void testGetForValue() throws SQLException {
System.out.println(customerDao.getCountWithName("a"));
} @Test
public void testAdd() throws SQLException {
Customer customer = new Customer(null,"dsa", "dad", "sdas", "dsa");
customerDao.save(customer);
} // 按条件查询的测试方法
@Test
public void testGetListForLike() {
CriteriaCustomer criteriaCustomer = new CriteriaCustomer("a","s",null, null);
List<Customer> customerList = customerDao.getListOfLike(criteriaCustomer);
System.out.println(customerList);
} @Test
public void testUpdate() {
Customer customer = new Customer(null, "dsa", "dad", "sdas", "dsa");
customerDao.update(customer, 19);
} @Test
public void testGetUserName() {
Object cusName = customerDao.getCusName(6);
System.out.println(cusName);
}
}
写完上面的代码并将其测试成功之后我们便可以利用这些代码去写页面的部分功能,首先我们实现点击 Submit 按钮之后将数据表中的所有信息都打印出来。首先贴出一张实现后的动图,如下:
其页面代码如下,Index.jsp(我们还没有使用 EL 和 JSTL 而是在页面中直接使用 java 代码,使用了 EL 和 JSTL 之后将会使代码更整洁)
<%@ page import="com.java.homework.domain.Customer" %>
<%@ page import="java.util.List" %><%--
Created by IntelliJ IDEA.
User: yin‘zhao
Date: 2017/11/13
Time: 16:38
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Customer</title>
</head>
</html>
<body>
<table cellspacing="10">
<form action="list.do" method="post">
<tr>
<td>CusName:</td>
<td><input type="text" name="cus_name"></td>
</tr>
<tr>
<td>CusAddress:</td>
<td><input type="text" name="cus_address"></td>
</tr>
<tr>
<td>CusPhone:</td>
<td><input type="text" name="cus_phone"></td>
</tr>
<tr>
<td>CusThing:</td>
<td><input type="text" name="cus_thing"></td>
</tr>
<tr>
<td>
<button type="submit">Submit</button>
</td>
<%--转到 add.jsp 进行添加用户--%>
<td><a href="add.jsp">CreateNewCustomer</a></td>
</tr>
</form>
</table> <table border="1" cellpadding="10" cellspacing="0">
<%-- java 代码写在元素中,不应直接写在 body 中 --%>
<%-- 获取所有的 customer 判断若不为空则将其打印在页面上 --%>
<%
List<Customer> customerList = (List<Customer>) request.getAttribute("customerList");
if (customerList != null && customerList.size() > 0) {
%>
<tr>
<th>CUSNAME</th>
<th>CUSADDRESS</th>
<th>CUSPHONE</th>
<th>CUSTHING</th>
<th>DELETE/UPDATE</th>
</tr>
<%
for (int i = 0; i < customerList.size(); i++) {
%>
<tr>
<td><%= customerList.get(i).getCustomerName()%>
</td>
<td><%= customerList.get(i).getCustomerAddress()%>
</td>
<td><%= customerList.get(i).getCustomerPhone()%>
</td>
<td><%= customerList.get(i).getCustomerThing()%>
</td>
<%--执行删除和更新操作--%>
<td><a href="delete.do?id=<%= customerList.get(i).getId()%>" class="delete">DELETE</a>
<a href="query.do?id=<%= customerList.get(i).getId()%>">UPDATE</a></td>
</tr>
<%
}
%>
<%
}
%>
</table>
</body>
</html>
对于 index.jsp 我们提交到的是 list.do 而不是某一个 servlet,不要惊讶,因为我们的 servlet 的映射为 *.do,这样便实现了多个请求使用同一个 Servlet 的第一步,把每次提交的地址写为 xxx.do,然后在 Servlet 中利用反射根据所请求的参数执行不同方法,代码如下:
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<servlet>
<servlet-name>AllServlet</servlet-name>
<servlet-class>com.java.homework.controller.AllServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>AllServlet</servlet-name>
<!-- 注意是 *.do -->
<url-pattern>*.do</url-pattern>
</servlet-mapping>
</web-app>
首先贴出 AllServlet.java 中利用反射执行不同方法的代码,如下:
package com.java.homework.controller; import com.java.homework.criteria.CriteriaCustomer;
import com.java.homework.dao.CustomerDao;
import com.java.homework.daoImpl.CustomerDaoImpl;
import com.java.homework.domain.Customer; import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.SQLException;
import java.util.List; /**
* 使用反射实现多个请求使用同一个 Servlet,利用反射
*/
public class AllServlet extends javax.servlet.http.HttpServlet { private CustomerDao customerDao = new CustomerDaoImpl(); protected void doPost(HttpServletRequest request, HttpServletResponse response) throws javax.servlet.ServletException, IOException {
// 获取 servletPath,为 /xxx.do
String servletPath = request.getServletPath();
// 去除 servletPath 前面的 / 和后面的 .do
String methodName = servletPath.substring(1).substring(0, servletPath.length() - 4);
try {
// 利用反射执行方法名为上述字符串的方法
Method method = getClass().getDeclaredMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
method.invoke(this, request, response);
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
} // 若为 get 请求则执行 post 请求的方法
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
}
上面的代码实现我们的需求 ---- 多个请求使用一个 Servlet。接下来我们在前面的功能上加上查询条件的查询,再贴出代码,展示如下:
上面 GIF 展示了在查询的基础上我们加了查询条件,如果查询条件为空我们就将所有的数据打印出来,但若查询条件不为空我们就将符合条件的数据打印出来。
我们首先要知道带查询条件的 SQL 语句应该如何写,如
SELECT * FROM customer WHERE customer_name LIKE '%xx%' AND customer_address LIKE '%xx%' AND customer_phone LIKE '%123%' AND customer_thing LIKE '%%'
首先我们需要将查询条件封装为一个单独类。上面的语句表示 customer_name 的值中包含 xx,customer_phone 中包含 123,且其他两个条件不受限制的写法。由于在案例中某一个条件为空时不能不写,所以将其条件为空的时候在 CriteriaCustomer 将其处理为 %%,等同于没有查询条件,其具体用在 CustomerDaoImpl.java 类中的 getForListOfLike(CriteriaCustomer criteriaCustomer) 方法中,详情可参见其方法体。
CriteriaCustomer.java
package com.java.homework.criteria; /**
* 封装查询条件的类
*/
public class CriteriaCustomer {
private String customerName;
private String customerAddress;
private String customerPhone;
private String customerThing; public String getCustomerName() {
// 如果其为空就将其置为 %%,否则将查询条件加在 %% 中间,拼出正确的 SQL 语句
if (customerName == null) {
customerName = "%%";
} else {
customerName = "%" + customerName + "%";
}
return customerName;
} public String getCustomerAddress() {
if (customerAddress == null) {
customerAddress = "%%";
} else {
customerAddress = "%" + customerAddress + "%";
}
return customerAddress;
} public String getCustomerPhone() {
if (customerPhone == null) {
customerPhone = "%%";
} else {
customerPhone = "%" + customerPhone + "%";
}
return customerPhone;
} public String getCustomerThing() {
if (customerThing == null) {
customerThing = "%%";
} else {
customerThing = "%" + customerThing + "%";
}
return customerThing;
} public CriteriaCustomer(String customerName, String customerAddress, String customerPhone, String customerThing) {
this.customerName = customerName;
this.customerAddress = customerAddress;
this.customerPhone = customerPhone;
this.customerThing = customerThing;
}
}
下面我们看 AllServlet.java 中的 list 方法(在 index.jsp 页面的显示代码可参见上面 index.jsp 代码,我觉得不是很难理解),如下:
// 显示数据表所有的信息
protected void list(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
List<Customer> customerList;
String cusName = request.getParameter("cus_name");
String cusAddress = request.getParameter("cus_address");
String cusPhone = request.getParameter("cus_phone");
String cusThing = request.getParameter("cus_thing");
// 将查询条件封装为 CriteriaCustomer 对象
CriteriaCustomer criteriaCustomer = new CriteriaCustomer(cusName, cusAddress, cusPhone, cusThing); if (cusName == null) {
// 执行查询所有数据
customerList = customerDao.getAll();
} else {
// 执行按条件查询
customerList = customerDao.getListOfLike(criteriaCustomer);
}
// 将查询到的 List 对象添加到 request 域对象中,并转发到 index.jsp 中,在页面上显示数据库信息
request.setAttribute("customerList", customerList);
request.getRequestDispatcher("/index.jsp").forward(request, response);
}
到这里我们就讲完了查询包括带条件和不带条件查询,接下来我们讲解删除和更新用户信息操作,删除操作可能很简单只需要调用 CustomerDaoImpl 的 delete() 方法即可,那么想一想会应该如何定位我们操作的是哪行信息?
对于更新操作我们在点击更新的超链接之后跳转到 update.jsp 之后首先要将其信息回显出来,我们要求 customer_name 属性必须唯一,所以我们在更新的时候必须在提交的时候查询数据库是否合法,若合法则执行更新,否则提示错误消息 XXX 已经被占用,我们该如何判断我们更新的 username 是否存在?如果查询 username 为所改值的列数来判断是否存在相同的 username,由于改之前还没有提交同时我们如果没有提交的话那么如何将它原来的 username 行排除在外?
在 index.jsp 页面上点击删除的超链接将请求提交到 delete.do,在 AllServlet 中执行 delete方法,执行删除操作,delete() 方法代码如下:
protected void delete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String id = request.getParameter("id");
try {
customerDao.delete(Integer.parseInt(id));
} catch (SQLException e) {
e.printStackTrace();
}
// 应该将重定向放于 try 块之后,那么如果出现异常也会转到 list.do,
response.sendRedirect("list.do");
}
update.jsp
<%@ page import="com.java.homework.domain.Customer" %><%--
Created by IntelliJ IDEA.
User: yin‘zhao
Date: 2017/11/13
Time: 23:45
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>UpdateCustomer</title>
</head>
<body>
<table cellspacing="10">
<%--保存错误消息,用户名重复时错误消息--%>
<%
String message = (String) request.getAttribute("message");
Customer customer = (Customer) request.getAttribute("customer");
%>
<h3><%
if (message != null) {
out.print(message);
}
%></h3>
<form action="update.do" method="post">
<input type="hidden" name="id" value=<%=customer.getId()%>>
<tr>
<td>CusName:</td>
<td><input type="text" name="cus_name" value=<%=customer.getCustomerName() %>></td>
</tr>
<tr>
<td>CusAddress:</td>
<td><input type="text" name="cus_address" value=<%=customer.getCustomerAddress() %>></td>
</tr>
<tr>
<td>CusPhone:</td>
<td><input type="text" name="cus_phone" value=<%=customer.getCustomerPhone()%>></td>
</tr>
<tr>
<td>CusThing:</td>
<td><input type="text" name="cus_thing" value=<%=customer.getCustomerThing()%>></td>
</tr>
<tr>
<td>
<button type="submit">Update</button>
</td>
</tr>
</form>
</table>
</body>
</html>
AllServlet 中的 update 方法和为了第一次回显所用到的 query 方法
{
Customer customer = getCustomer(request);
Integer id = customer.getId();
String cusName = customer.getCustomerName();
String cusNameReal = (String) customerDao.getCusName(id);
try {
Long count = customerDao.getCountWithName(cusName);
System.out.println(count);
// 如果所传入的用户名的行数大于0,分为两种情况,没改存在一个,改了存在相同的
// 由于或运算是计算了前面的若为假就不在执行后面的所以,当用户名相同时不判断后面的部分为正常操作,若不相等且有重复的则回馈错误信息
// 也可以将旧的用户名存为一个隐藏表单,用上面同样的方法进行处理,与之相比少了对数据库的请求
// 使用 equalsIgnoreCase 可以忽略大小写进行比较,那么在将当前值改为大写或者小写的时候就不会返回错误信息
if (!(cusNameReal.equalsIgnoreCase(cusName)) && (count > 0)) {
String message = "用户名" + cusName + "已经被占用!";
// 如果因为用户名重复那么就将传入 request 域中的 name 属性改为最原始的,其他属性为改好的
customer.setCustomerName(cusNameReal);
request.setAttribute("message", message);
request.setAttribute("customer", customer);
request.getRequestDispatcher("update.jsp").forward(request, response);
} else {
customerDao.update(customer, id);
response.sendRedirect("list.do");
}
} catch (SQLException e) {
e.printStackTrace();
}
}
我们由代码可知,对于删除操作中如何定位删除的是哪行是通过点击删除的超链接的时候将该行的 id 同时也传过去;对于更新操作其第u一次回显是先将请求给 query 方法,query方法通过传过来的 id 属性将 customer 对象转发到更新页面完成回显,再次提交到 update 方法中,通过 customer_username 获取行数,其 customer_username 是通过 update.jsp 中的隐藏值将 id 传到 servlet,通过 id 获取 Customer 对象,并在用户名出错的情况下将 Customer 对象返回,保存修改以前的信息,具体可以去读代码。
删除、更新和查询都处理完了就剩添加了,通过前面的 GIF 也可以看到我们 index.jsp 有一个 CreateNewCustomer 超链接,没错就是添加新用户,它和更新一样也需要去查询数据库判断是否存在相同的值,也需要报错,同时它需要信息的完整性,如果不完整也会报错!代码和演示如下:
点击超链接到 add.jsp;
add.jsp
<%@ page import="com.java.homework.domain.Customer" %><%--
Created by IntelliJ IDEA.
User: yin‘zhao
Date: 2017/11/13
Time: 23:45
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>CreateNewCustomer</title>
</head>
</html>
<body>
<br>
<h3>
<%--保存错误消息,当信息不完整和用户名重复时的错误消息--%>
<%
String message1 = (String) request.getAttribute("message1");
String message2 = (String) request.getAttribute("message2");
if (message1 != null) {
out.print(message1);
} if (message2 != null) {
out.print(message2);
}
%></h3>
<br>
<table cellspacing="10">
<form action="add.do" method="post">
<tr>
<td>CusName:</td>
<td><input type="text" name="cus_name"
value=<%= request.getParameter("cus_name") == null ? "" : request.getParameter("cus_name")%>></td>
</tr>
<tr>
<td>CusAddress:</td>
<td><input type="text" name="cus_address"
value=<%= request.getParameter("cus_address") == null ? "" : request.getParameter("cus_address")%>></td>
</tr>
<tr>
<td>CusPhone:</td>
<td><input type="text" name="cus_phone"
value=<%= request.getParameter("cus_phone") == null ? "" : request.getParameter("cus_phone")%>></td>
</tr>
<tr>
<td>CusThing:</td>
<td><input type="text" name="cus_thing"
value=<%= request.getParameter("cus_thing") == null ? "" : request.getParameter("cus_thing")%>></td>
</tr>
<tr>
<td>
<button type="submit">Submit</button>
</td>
</tr>
</form>
</table>
</body>
</html>
AllServlet 中的 add 方法
{
String cusName = request.getParameter("cus_name");
String cusAddress = request.getParameter("cus_address");
String cusPhone = request.getParameter("cus_phone");
String cusThing = request.getParameter("cus_thing");
Customer customer = new Customer(null, cusName, cusAddress, cusPhone, cusThing);
Long count = null;
try {
count = customerDao.getCountWithName(cusName);
} catch (SQLException e) {
e.printStackTrace();
} if (cusName.trim().equals("") || cusAddress.trim().equals("") || cusPhone.trim().equals("") || cusThing.trim().equals("")) {
request.setAttribute("message1", "请输入完整的信息后在确认!");
request.getRequestDispatcher("add.jsp").forward(request, response);
return;
}
if (count > 0) {
request.setAttribute("message2", "用户名" + cusName + "已经被占用");
request.getRequestDispatcher("add.jsp").forward(request, response);
return;
}
try {
customerDao.save(customer);
// 如果使用转发,那么新加的页面和list 页面将会冲突,导致list 页面将会执行模糊查询
// request.getRequestDispatcher("list.do").forward(request, response);
response.sendRedirect("list.do");
} catch (SQLException e) {
e.printStackTrace();
}
}
到这里我们的这个小案例就讲解的差不多了,有什么讲解的纰漏还望指出,谢谢!