Servlet
使用Servlet进行增删改查
步骤
1. 导入以下几个jar包到WEB-INF下的lib包里,必要时build path,其中jstl.jar和standard.jar是使用jstl要用的(eclipse中)
2. 写对应的dao,service,以及实现类
3. 写对应的servlet类,必须继承HttpServlet类
- 在此servlet类里加私有的service实现类;
- 添加doPost()和doGet方法:一般是在doPost()里写具体操作代码,doGet()方法里调用doPost,这样,不管提交方式是post还是get,都可以访问;
- doPost()方法里要先加
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
- 取参和传参,转发和重定向
取参:
String age1=request.getParameter("age");
int age = Integer.parseInt(age1);
传参:
request.setAttribute("emp", emp);
转发:
request.getRequestDispatcher("/emp.jsp").forward(request, response);
重定向:
response.sendRedirect(request.getContextPath()+"/error.jsp");
5配置web.xml,写对应的servlet和其映射
访问时:先通过url定位到web.xml里servlet的url-pattern,再对应到servlet-name,再找到对应的servlet类,根据访问时提交的方法调用相应的doPost()或者doGet()方法
6.写对应的前台页面
取后台传过来的数据:${ }
提交的url路径:
<form action="/servletTest/updateEmp" method="post"></form>
<a href="/servletTest/deleteEmp?id=${emp.id }">删除</a>
示例代码
DbUtil.java
package util;
import org.apache.commons.dbutils.QueryRunner;
import com.mchange.v2.c3p0.ComboPooledDataSource;
public class DbUtil {
private static ComboPooledDataSource ds=new ComboPooledDataSource();
public static QueryRunner getQueryRunner(){ QueryRunner qr = new QueryRunner(ds); return qr; }
}
c3p0-config.xml
<c3p0-config>
<default-config> <property name="driverClass">com.mysql.jdbc.Driver</property> <property name="jdbcUrl">jdbc:mysql://localhost/test</property> <property name="user">root</property> <property name="password"></property> <property name="initialPoolSize">5</property> <property name="maxPoolSize">10</property> </default-config></c3p0-config>
EmpDao.java
package dao;
import java.util.List;
import entity.Emp;
public interface EmpDao {
public int add(Emp emp); public int delete(int id); public int update(Emp emp); public Emp find(int id); public List<Emp> findAll();}EmpDaoImpl.java
package dao.impl;
import java.sql.SQLException;
import java.util.List;import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;import org.apache.commons.dbutils.handlers.BeanListHandler;import util.DbUtil;
import dao.EmpDao;import entity.Emp;public class EmpDaoImpl implements EmpDao {
QueryRunner qr = DbUtil.getQueryRunner();
@Override public int add(Emp emp) { String sql="insert into emp(age,name) values(?,?) "; int num=0; try { num = qr.update(sql, emp.getAge(),emp.getName()); } catch (SQLException e) { e.printStackTrace(); } return num; } @Override public List<Emp> findAll() { String sql="select*from emp"; List<Emp> emps=null; try { emps=qr.query(sql, new BeanListHandler<Emp>(Emp.class)); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return emps; } @Override public int delete(int id) { String sql="delete from emp where id="+id; int num=0; try { num=qr.update(sql); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return num; } @Override public int update(Emp emp) { String sql="update emp set name=?,age=? where id=?"; System.out.println("sql---------"+sql); int num=0; try { num=qr.update(sql, emp.getName(),emp.getAge(),emp.getId()); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return num; } @Override public Emp find(int id) { String sql="select * from emp where id="+id; Emp emp=null; try { emp=qr.query(sql, new BeanHandler<Emp>(Emp.class)); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return emp; }}
EmpService.java
package service;
import java.util.List;
import entity.Emp;
public interface EmpService {
public int addEmp(Emp emp); public List<Emp> findAll(); public int delete(int id); public int update(Emp emp); public Emp find(int id);}EmpServiceImpl.java
package service.impl;
import java.util.List;
import service.EmpService;
import dao.impl.EmpDaoImpl;import entity.Emp;public class EmpServiceImpl implements EmpService {
private EmpDaoImpl empDao=new EmpDaoImpl(); @Override public int addEmp(Emp emp) { int num = empDao.add(emp); return num; } @Override public List<Emp> findAll() { return empDao.findAll(); } @Override public int delete(int id) { return empDao.delete(id); } @Override public int update(Emp emp) { return empDao.update(emp); } @Override public Emp find(int id) { return empDao.find(id); }}
AddEmpServlet.java
package 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 service.impl.EmpServiceImpl;
import entity.Emp;public class AddEmpServlet extends HttpServlet {
private EmpServiceImpl empService=new EmpServiceImpl(); @Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); response.setContentType("text/html;charset=utf-8"); String age1=request.getParameter("age"); int age = Integer.parseInt(age1); String name = request.getParameter("name"); Emp emp=new Emp(); emp.setAge(age); emp.setName(name); int num = empService.addEmp(emp); if(num>0){ response.sendRedirect(request.getContextPath()+"/empList"); }else{ response.sendRedirect(request.getContextPath()+"/error.jsp"); } } @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response);; }}DeleteEmpServlet.java
package 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 service.impl.EmpServiceImpl;
import entity.Emp;public class DeleteEmpServlet extends HttpServlet {
private EmpServiceImpl empService=new EmpServiceImpl();
@Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); response.setContentType("text/html;charset=utf-8"); String id1 = request.getParameter("id"); Integer id=Integer.parseInt(id1); System.out.println("进入删除,id="+id); int num = empService.delete(id); System.out.println("删除?---"+num); if(num>0){ response.sendRedirect(request.getContextPath()+"/empList"); }else{ response.sendRedirect("/error.jsp"); } } @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); }}//修改时,先找到要修改的对象,再转发到需要修改的页面,显示要修改的对象信息,然后提交时修改
FindUpdEmpServlet .java
package 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 entity.Emp;
import service.impl.EmpServiceImpl;public class FindUpdEmpServlet extends HttpServlet {
private EmpServiceImpl empService=new EmpServiceImpl();
@Overridepublic void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException { request.setCharacterEncoding("utf-8");response.setContentType("text/html;charset=utf-8");Integer id=Integer.parseInt(request.getParameter("id"));Emp emp = empService.find(id);System.out.println("要修改的emp"+emp.getName());if(emp!=null){ request.setAttribute("emp", emp);request.getRequestDispatcher("/update.jsp").forward(request, response);;}else{ response.sendRedirect(request.getContextPath()+"/error.jsp");}}@Overridepublic void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException { doPost(request, response);}}UpdateEmpServlet.java
package 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 service.impl.EmpServiceImpl;
import entity.Emp;public class UpdateEmpServlet extends HttpServlet {
private EmpServiceImpl empService=new EmpServiceImpl(); @Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); response.setContentType("text/html;charset=utf-8"); String id1 = request.getParameter("id"); Integer id=Integer.parseInt(id1); String name = request.getParameter("name"); String age1 = request.getParameter("age"); Integer age=Integer.parseInt(age1); Emp emp=new Emp(); emp.setId(id); emp.setAge(age); emp.setName(name); //empService.find(id); int num = empService.update(emp); if(num>0){ response.sendRedirect(request.getContextPath()+"/empList"); }else{ response.sendRedirect("/error.jsp"); } } @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); }}FindEmpServlet.java
package 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 entity.Emp;
import service.impl.EmpServiceImpl;public class FindEmpServlet extends HttpServlet {
private EmpServiceImpl empService=new EmpServiceImpl(); @Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); response.setContentType("text/html;charset=utf-8"); Integer id=Integer.parseInt(request.getParameter("id")); Emp emp = empService.find(id); System.out.println("emp---"+emp.getName()+"---"+emp.getAge()); if(emp!= null){ request.setAttribute("emp", emp); request.getRequestDispatcher("/emp.jsp").forward(request, response); }else{ response.sendRedirect(request.getContextPath()+"/error.jsp"); } } @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); }}FindEmpsServlet.java
package servlet;
import java.io.IOException;
import java.util.List;import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import entity.Emp;
import service.impl.EmpServiceImpl;public class FindEmpsServlet extends HttpServlet {
private EmpServiceImpl empService=new EmpServiceImpl(); @Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); response.setContentType("text/html;charset=utf-8"); List<Emp> emps = empService.findAll(); if(emps!=null){ request.setAttribute("emps", emps); request.getRequestDispatcher("/list.jsp").forward(request, response); }else{ response.sendRedirect(request.getContextPath()+"/error.jsp"); } } @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); }}web.xml
<?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_3_0.xsd" id="WebApp_ID" version="3.0"> <display-name>servletTest</display-name><servlet><servlet-name>addEmp</servlet-name><servlet-class>servlet.AddEmpServlet</servlet-class></servlet> <servlet> <servlet-name>deleteEmp</servlet-name> <servlet-class>servlet.DeleteEmpServlet</servlet-class> </servlet> <servlet> <servlet-name>findUpdEmp</servlet-name> <servlet-class>servlet.FindUpdEmpServlet</servlet-class> </servlet> <servlet> <servlet-name>updateEmp</servlet-name> <servlet-class>servlet.UpdateEmpServlet</servlet-class> </servlet> <servlet> <servlet-name>findEmp</servlet-name> <servlet-class>servlet.FindEmpServlet</servlet-class> </servlet> <servlet> <servlet-name>empList</servlet-name> <servlet-class>servlet.FindEmpsServlet</servlet-class> </servlet><servlet-mapping><servlet-name>addEmp</servlet-name><url-pattern>/addEmp</url-pattern></servlet-mapping> <servlet-mapping> <servlet-name>deleteEmp</servlet-name> <url-pattern>/deleteEmp</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>findUpdEmp</servlet-name> <url-pattern>/findUpdEmp</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>updateEmp</servlet-name> <url-pattern>/updateEmp</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>findEmp</servlet-name> <url-pattern>/findEmp</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>empList</servlet-name> <url-pattern>/empList</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list></web-app>前台页面
add.jsp
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%><!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>添加员工</title></head><body><form action="/servletTest/addEmp" method="post"> 姓名:<input type="text" name="name"/><p> 年龄:<input type="text" name="age"/><p> <input type="submit" value="添加"/> </form></body></html>list.jsp
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%><%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%><!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>员工列表</title></head><body> 添加成功<table> <tr > <td colspan="3"> <a href="index.jsp">添加</a> </td> </tr> <tr> <th>编号</th> <th>年龄</th> <th>age</th> <th colspan="3">操作</th> </tr> <!--items里面写${requestScope.emps}也可以 --> <c:forEach items="${emps }" var="emp" varStatus="vs"> <tr> <td>${emp.id }</td> <td>${emp.name }</td> <td>${emp.age }</td> <td><a href="/servletTest/deleteEmp?id=${emp.id }">删除</a></td> <td><a href="/servletTest/findUpdEmp?id=${emp.id }">修改</a></td> <td><a href="/servletTest/findEmp?id=${emp.id }">查看</a></td> </tr> </c:forEach> </table></body></html>emp.jsp
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%><!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></head><body>编号:${emp.id }<p> 姓名:${emp.name }<p> 年龄:${emp.age }</body></html>update.jsp
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%><!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>修改员工</title></head><body> <form action="/servletTest/updateEmp" method="post"> 编号:<input type="text" name="id" value="${emp.id }" readonly="readonly"/><p> 姓名:<input type="text" name="name" value="${emp.name }"/><p> 年龄:<input type="text" name="age" value="${emp.age }"/><p> <input type="submit" value="提交"/> </form></body></html>error.jsp
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%><!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></head><body><h1>出错了</h1></body></html>