Servlet开发(一)

(一)体现MVC分层架构的思想,使用原生的JDBC技术进行简单的Servlet开发,实现表单数据到数据的增删改查操作,后期使用框架进行练习。

(二)环境的搭建

(1)导包


(2)进行简单的架构


(三)实现过程:

(1)实体类User的书写,实体类几种常见的写法
cn.itcast.entity
cn.itcast.javabean
cn.itcast.bean
cn.itcast.pojo
cn.itcast.domain
package cn.edu.user;

public class User {
	
	private Integer id;
	private String name;
	private String age;
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getAge() {
		return age;
	}
	public void setAge(String age) {
		this.age = age;
	}
}

(2)定义一个接口方法IUserDao(命名规范接口方法前大写I)
package cn.edu.dao;

import cn.edu.user.User;

public interface IUserDao {
	
	//增删改查
	
	void add(User user);
	
	//删除方法传入的参数必须是唯一的,不然会造成误删
	void delete(Integer id);
	
	void update(User user);
	
	void find(Integer id);
}
(3)在实现IUserDao接口的方法之前,先书写一个工具类JdbcUtils
package cn.edu.utils;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

import javax.sql.DataSource;

import org.apache.commons.dbutils.QueryRunner;

import com.mchange.v2.c3p0.ComboPooledDataSource;

public class JdbcUtils {
	public static void main(String args[]) {
	private static DataSource dataSource;
	// 初始化连接池
	static {
		dataSource = new ComboPooledDataSource();
	}

	// 获取连接池
	public DataSource getDataSource() {
		return dataSource;
	}

	// 获取操作sql语句对象
	public static QueryRunner getQueryRunner() {
		return new QueryRunner(dataSource);

	}

}
书写c3p0连接池配置文件:
<c3p0-config>
  <default-config>
     <property name="driverClass">com.mysql.jdbc.Driver</property> 
     <property name="jdbcUrl">jdbc:mysql://localhost:3306/users</property> 
     <property name="user">root</property> 
     <property name="password">123456</property> 
     <property name="initialPoolSize">5</property> 
     <property name="maxPoolSize">10</property> 
 <property name="minPoolSize">2</property> 
  </default-config>
</c3p0-config>


(4)复写接口IUserDao中的方法,书写UserDaoImpl类
package cn.edu.dao;

import java.sql.SQLException;

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

import cn.edu.user.User;
import cn.edu.utils.JdbcUtils;

public class UserDaoImpl implements IUserDao{

	@Override
	public void add(User user) {
		String sql = "insert into t_user(name,age) values (?,?)";
		try {
			JdbcUtils.getQueryRunner().update(sql,new BeanHandler<User>(User.class),user.getName(),user.getAge());
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		
	}

	@Override
	public void delete(Integer id) {
		String sql = "delete from t_user where id = ?";
		try {
			JdbcUtils.getQueryRunner().update(sql, id);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		
	}

	@Override
	public void update(User user) {
		String sql = "update t_user set name=? , age=? where id = ?";
		try {
			JdbcUtils.getQueryRunner().update(sql, user.getName(),user.getAge(),user.getId());
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
	}

	@Override
	//查询操作才需要使用BeanHandler来封装查询的结果,形成一个结果集,更新和添加操作不需要
	public void find(Integer id) {
		String sql = "select * from t_user where id = ?";
		try {
			JdbcUtils.getQueryRunner().update(sql, id);
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
		
	}

}
(5)书写接口IUserService
package cn.edu.service;

import cn.edu.user.User;

public interface IUserService {
	
	//增删改查
	
		void add(User user);
		
		void delete(Integer id);
		
		void update(User user);
		
		void find(Integer id);

}
(6)书写Service层代码,实现IUserService接口
package cn.edu.service;

import cn.edu.dao.UserDaoImpl;
import cn.edu.user.User;

public class UserServiceImpl implements IUserService{
	//注入Dao层对象,Service层才可以调用Dao层
	private UserDaoImpl userDaoImpl = new UserDaoImpl();

	@Override
	public void add(User user) {
		
		userDaoImpl.add(user);
	}

	@Override
	public void delete(Integer id) {
		
		userDaoImpl.delete(id);
	}

	@Override
	public void update(User user) {
		
		userDaoImpl.update(user);
	}

	@Override
	public void find(Integer id) {
		
		userDaoImpl.find(id);
	}
	
	
}
(7)书写Servlet文件时,写书写一个表单
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<!--  <form action="/UserDemo/user" method="post">-->
	<form action="./user" method="post">
		姓名:<input type="text" name="name" /><br/>
		年龄:<input type="text" name="age" /><br/>
		<input type="submit" value="提交"/>
	</form>
</body>
</html>
(8)书写Servlet文件,复写doPost和doGet方法。
package cn.edu.servlet;

import java.io.IOException;

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


import cn.edu.service.UserServiceImpl;
import cn.edu.user.User;

public class UserServlet extends HttpServlet{
	/**
	 * ``````````
	 */
	private static final long serialVersionUID = 1L;
	private UserServiceImpl userService = new UserServiceImpl();
	
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		       doGet(req, resp);
	
	}
	
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		req.setCharacterEncoding("UTF-8");//设置乱码问题
               String name = req.getParameter("name");//获取表单中name信息
		String age = req.getParameter("age");//获取表单中age栏信息
		//将上面获取的表单信息进行封装,封装到User对象中
		User u = new User();
		u.setAge(age);
		u.setName(name);
		System.out.println(name);
		System.out.println(age);
		userService.add(u);//调用Service业务层处理逻辑,将获取的信息保存到数据库中
		
	}
}
(9)在数据库中创建一张表格:
create table t_user(
id int(11)  primary key ,
name varchar(50) not null,
age int(30)  not null
)

(10)书写Servlet配置文件
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>UserDemo</display-name>
  <welcome-file-list>
    <welcome-file>sys/form.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  
  
  
<servlet>
	<servlet-name>UserServlet</servlet-name>
	<servlet-class>cn.edu.servlet.UserServlet</servlet-class>	
</servlet>

<servlet-mapping>
	<servlet-name>UserServlet</servlet-name>
	<url-pattern>/user</url-pattern>
</servlet-mapping>

</web-app>

(11)将工程发布到tomcat中,遇到问题如下:


在网上搜索了一波,解决方法如下:

(1)在dos下,输入  netstat   -ano|findstr  8080 

//说明:查看占用8080端口的进程,

显示占用端口的进程

2.taskkill  /pid  11480  /f




(12)继续发布工程,出现结果如下:


因为在web.xml配置文件中位置了默认的跳转页面

(13)继续发布,疯狂报错。。。。。。

mhb
342
七月 14, 2018 5:10:20 下午 com.mchange.v2.log.MLog <clinit>
信息: MLog clients using java 1.4+ standard logging.
七月 14, 2018 5:10:20 下午 com.mchange.v2.c3p0.C3P0Registry banner
信息: Initializing c3p0-0.9.1.2 [built 21-May-2007 15:04:56; debug? true; trace: 10]
七月 14, 2018 5:10:20 下午 com.mchange.v2.c3p0.impl.AbstractPoolBackedDataSource getPoolManager
信息: Initializing c3p0 pool... com.mchange.v2.c3p0.ComboPooledDataSource [ acquireIncrement -> 3, acquireRetryAttempts -> 30, acquireRetryDelay -> 1000, autoCommitOnClose -> false, automaticTestTable -> null, breakAfterAcquireFailure -> false, checkoutTimeout -> 0, connectionCustomizerClassName -> null, connectionTesterClassName -> com.mchange.v2.c3p0.impl.DefaultConnectionTester, dataSourceName -> 1b60w3n9w166u4uhk8le39|5005f13d, debugUnreturnedConnectionStackTraces -> false, description -> null, driverClass -> com.mysql.jdbc.Driver, factoryClassLocation -> null, forceIgnoreUnresolvedTransactions -> false, identityToken -> 1b60w3n9w166u4uhk8le39|5005f13d, idleConnectionTestPeriod -> 0, initialPoolSize -> 5, jdbcUrl -> jdbc:mysql://localhost:3306/users, maxAdministrativeTaskTime -> 0, maxConnectionAge -> 0, maxIdleTime -> 0, maxIdleTimeExcessConnections -> 0, maxPoolSize -> 10, maxStatements -> 0, maxStatementsPerConnection -> 0, minPoolSize -> 2, numHelperThreads -> 3, numThreadsAwaitingCheckoutDefaultUser -> 0, preferredTestQuery -> null, properties -> {user=******, password=******}, propertyCycle -> 0, testConnectionOnCheckin -> false, testConnectionOnCheckout -> false, unreturnedConnectionTimeout -> 0, usesTraditionalReflectiveProxies -> false ]
七月 14, 2018 5:10:21 下午 org.apache.catalina.core.StandardWrapperValve invoke
严重: Servlet.service() for servlet [UserServlet] in context with path [/UserDemo] threw exception
java.lang.RuntimeException: java.sql.SQLException: Wrong number of parameters: expected 2, was given 3 Query: insert into t_user(name,age) values (?,?) Parameters: [org.apache.commons.dbutils.handlers.BeanHandler@38b11674, mhb, 342]
	at cn.edu.dao.UserDaoImpl.add(UserDaoImpl.java:18)
	at cn.edu.service.UserServiceImpl.add(UserServiceImpl.java:13)
	at cn.edu.servlet.UserServlet.doGet(UserServlet.java:37)
	at cn.edu.servlet.UserServlet.doPost(UserServlet.java:22)
	at javax.servlet.http.HttpServlet.service(HttpServlet.java:646)
	at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
	at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
	at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
	at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
	at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
	at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
	at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
	at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
	at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
	at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
	at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1040)
	at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:607)
	at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:313)
	at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
	at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
	at java.lang.Thread.run(Thread.java:748)
Caused by: java.sql.SQLException: Wrong number of parameters: expected 2, was given 3 Query: insert into t_user(name,age) values (?,?) Parameters: [org.apache.commons.dbutils.handlers.BeanHandler@38b11674, mhb, 342]
	at org.apache.commons.dbutils.AbstractQueryRunner.rethrow(AbstractQueryRunner.java:392)
	at org.apache.commons.dbutils.QueryRunner.update(QueryRunner.java:491)
	at org.apache.commons.dbutils.QueryRunner.update(QueryRunner.java:457)
	at cn.edu.dao.UserDaoImpl.add(UserDaoImpl.java:16)
	... 24 more

数据库中当然也没有要提交的数据


继续提交数据,还在报错

hong
xym
七月 14, 2018 5:19:03 下午 com.mchange.v2.log.MLog <clinit>
信息: MLog clients using java 1.4+ standard logging.
七月 14, 2018 5:19:03 下午 com.mchange.v2.c3p0.C3P0Registry banner
信息: Initializing c3p0-0.9.1.2 [built 21-May-2007 15:04:56; debug? true; trace: 10]
七月 14, 2018 5:19:04 下午 com.mchange.v2.c3p0.impl.AbstractPoolBackedDataSource getPoolManager
信息: Initializing c3p0 pool... com.mchange.v2.c3p0.ComboPooledDataSource [ acquireIncrement -> 3, acquireRetryAttempts -> 30, acquireRetryDelay -> 1000, autoCommitOnClose -> false, automaticTestTable -> null, breakAfterAcquireFailure -> false, checkoutTimeout -> 0, connectionCustomizerClassName -> null, connectionTesterClassName -> com.mchange.v2.c3p0.impl.DefaultConnectionTester, dataSourceName -> 1b60w3n9w1675cro1exvtde|149e57c0, debugUnreturnedConnectionStackTraces -> false, description -> null, driverClass -> com.mysql.jdbc.Driver, factoryClassLocation -> null, forceIgnoreUnresolvedTransactions -> false, identityToken -> 1b60w3n9w1675cro1exvtde|149e57c0, idleConnectionTestPeriod -> 0, initialPoolSize -> 5, jdbcUrl -> jdbc:mysql://localhost:3306/users, maxAdministrativeTaskTime -> 0, maxConnectionAge -> 0, maxIdleTime -> 0, maxIdleTimeExcessConnections -> 0, maxPoolSize -> 10, maxStatements -> 0, maxStatementsPerConnection -> 0, minPoolSize -> 2, numHelperThreads -> 3, numThreadsAwaitingCheckoutDefaultUser -> 0, preferredTestQuery -> null, properties -> {user=******, password=******}, propertyCycle -> 0, testConnectionOnCheckin -> false, testConnectionOnCheckout -> false, unreturnedConnectionTimeout -> 0, usesTraditionalReflectiveProxies -> false ]
七月 14, 2018 5:19:04 下午 org.apache.catalina.core.StandardWrapperValve invoke
严重: Servlet.service() for servlet [UserServlet] in context with path [/UserDemo] threw exception
java.lang.RuntimeException: java.sql.SQLException: Field 'id' doesn't have a default value Query: insert into t_user(name,age) values (?,?) Parameters: [hong, xym]
	at cn.edu.dao.UserDaoImpl.add(UserDaoImpl.java:18)
	at cn.edu.service.UserServiceImpl.add(UserServiceImpl.java:13)
	at cn.edu.servlet.UserServlet.doGet(UserServlet.java:37)
	at cn.edu.servlet.UserServlet.doPost(UserServlet.java:22)
	at javax.servlet.http.HttpServlet.service(HttpServlet.java:646)
	at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
	at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
	at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
	at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
	at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
	at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
	at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
	at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
	at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
	at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
	at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1040)
	at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:607)
	at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:315)
	at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
	at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
	at java.lang.Thread.run(Thread.java:748)
Caused by: java.sql.SQLException: Field 'id' doesn't have a default value Query: insert into t_user(name,age) values (?,?) Parameters: [hong, xym]
	at org.apache.commons.dbutils.AbstractQueryRunner.rethrow(AbstractQueryRunner.java:392)
	at org.apache.commons.dbutils.QueryRunner.update(QueryRunner.java:491)
	at org.apache.commons.dbutils.QueryRunner.update(QueryRunner.java:457)
	at cn.edu.dao.UserDaoImpl.add(UserDaoImpl.java:16)
	... 24 more

报错解释说没有默认id值,首先测试一下数据库连接


连接没有问题



在数据库管理工具中添加数据无法操作成功,发现没有给id设置为自增策略,进行设置,如下:


继续执行操作,发现可以添加成功:


继续发布工程,发现添加成功,控制台打印,数据库也可以查询成功:


数据库查询操作如下:


(14)成功实现数据库添加操作,后续将进行剩余的删改查操作、。这破玩意儿搞了这么久,算是搞出来了。



展开阅读全文

没有更多推荐了,返回首页