- 建数据表
CREATE TABLE `role` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`roleName` varchar(20) DEFAULT NULL,
`roleDesc` varchar(20) DEFAULT NULL,
PRIMARY KEY (`id`)
)
- 插入数据
INSERT INTO `role` VALUES ('1', 'ADMIN', 'vip');
INSERT INTO `role` VALUES ('2', 'USER', 'vip');
数据库页面:
3. 编写三层架构模型
dao实现与数据库的连接,servlet实现请求响应,service层进行业务处理,domain是实体类的包装,utils包是用来放需要的工具类。
4. 导入jar包
数据库的连接包,连接池的jar包,jstl表达式的包,日志包。
包导完记得构建一下,不然写包中的类时会报错。
5.编写工具类以及xml文件
工具类:用来连接创建连接,连接数据库
public class C3P0Utils {
private static ComboPooledDataSource ds = new ComboPooledDataSource();
public static DataSource getDataSource(){
return ds;
}
//static代码块设置数据库连接四大要素
public static Connection getConnection() throws SQLException{
//获取连接,不要自己去DriverManager获取,而是从C3P0连接池获取
return ds.getConnection();
}
//关闭所有资源的统一代码
public static void closeAll(Connection conn,Statement st,ResultSet rs){
//负责关闭
if(conn != null){
try {
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(st != null){
try {
st.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(rs != null){
try {
rs.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
编写c3p0的核心配置文件
<?xml version="1.0" encoding="UTF-8"?>
<c3p0-config>
<default-config><!-- 默认配置 -->
<property name="driverClass">com.mysql.jdbc.Driver</property>
<property name="jdbcUrl">jdbc:mysql://localhost:3306/day10</property>
<property name="user">root</property>
<property name="password">123456</property>
<property name="initialPoolSize">10</property>
</default-config>
</c3p0-config>
我这是连接mysql,所以端口号是3306,对应的用户名和密码可去数据库看
6. 编写dao层,编写sql代码
public class UserDao {
public List<Role> findAll() throws SQLException {
QueryRunner qr=new QueryRunner(C3P0Utils.getDataSource());
List<Role> list=qr.query("select * from role",new BeanListHandler<Role>(Role.class));
return list;
}
}
因为是做的全部查询,所以用BeanListHandle,也用list来接收数据库中的数据。
7.编写service层,实现业务功能。
public class UserService {
public List<Role> findAll() throws SQLException {
UserDao userDao=new UserDao();
return userDao.findAll();
}
}
8.编写实体类,注意与数据库中的字段相同,不然容易报错。
public class Role implements Serializable {
private Integer id;
private String roleName;
private String roleDesc;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getRoleName() {
return roleName;
}
public void setRoleName(String roleName) {
this.roleName = roleName;
}
public String getRoleDesc() {
return roleDesc;
}
public void setRoleDesc(String roleDesc) {
this.roleDesc = roleDesc;
}
@Override
public String toString() {
return "Role{" +
"id=" + id +
", roleName='" + roleName + '\'' +
", roleDesc='" + roleDesc + '\'' +
'}';
}
}
实现对应的get和set方法,以及重写tostring方法。
9.编写servlet层
@WebServlet( "/UseServlet")//请求路径
public class UseServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request,response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String method=request.getParameter("method");
if("findAll".equals(method)){
findAll(request,response);
}
}
protected void findAll(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
UserService userService=new UserService();
List<Role> rolelist= null;
try {
rolelist = userService.findAll();
} catch (SQLException e) {
e.printStackTrace();
}
request.setAttribute("rolelist",rolelist);
request.getRequestDispatcher("/list.jsp").forward(request,response);
}
}
因为我这用了@WebServlet()的注释,所以不需要再web.xml在进行配置。这是请求路径。查到数据后,设置值到域对象中,进行前后端数据的交互。
10.页面发出请求:
<a href="${pageContext.request.contextPath}/UseServlet?method=findAll">查询</a>
用el表达式获取当前的项目名,加上请求路径,method区别实现的方法,可到servlet中查看。
11.结果页面:
<table border="1">
<tr>
<th>ID</th>
<th>角色名称</th>
<th>角色描述</th>
</tr>
<c:forEach items="${rolelist}" var="role">
<tr>
<td>${role.id}</td>
<td>${role.roleName}</td>
<td>${role.roleDesc}</td>
</tr>
</c:forEach>
</table>
12.运行代码,查看结果。
结果显示,说明代码无误,运行成功。
总结:以上就是前后端交互的一个小功能的实现。运用的知识也多。mysql+jsp+EL+jstl+c3p0连接池+servlet。最后感谢大家的纠错改正,以及在代码优化方面,多多探讨。