Servlet

使用Servlet进行增删改查

步骤

1.  导入以下几个jar包到WEB-INF下的lib包里,必要时build path,其中jstl.jar和standard.jar是使用jstl要用的(eclipse中)

2.  写对应的dao,service,以及实现类

3.  写对应的servlet类,必须继承HttpServlet类

  1. 在此servlet类里加私有的service实现类;
  2. 添加doPost()和doGet方法:一般是在doPost()里写具体操作代码,doGet()方法里调用doPost,这样,不管提交方式是post还是get,都可以访问;
  3. doPost()方法里要先加

request.setCharacterEncoding("utf-8");

response.setContentType("text/html;charset=utf-8");

  1. 取参和传参,转发和重定向

取参:

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();

@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());
if(emp!=null){
request.setAttribute("emp", emp);
request.getRequestDispatcher("/update.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);
}

}

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>

servlet增删改查的更多相关文章

  1. 12 Servlet_04 Servlet增删改查 静态页面与动态页面 EL表达式 table表格的一些样式

    今天学习了servlet的增删改查: 存储数据 setAttribute(String name,Object obj );获取数据 getAttribute(String name);删除数据 re ...

  2. 最简单的jsp+servlet的增删改查代码

    package ceet.ac.cn.dao; import java.sql.Connection; import java.sql.PreparedStatement; import java.s ...

  3. web项目总结——通过jsp+servlet实现对oracle的增删改查功能

    1.DAO模式 分包:依次建立 entity:实体包,放的是跟oracle数据库中表结构相对应的对象的属性,也就是这个对象有什么 dao:增删改查接口,实现增删改查的具体方法 service:同dao ...

  4. 数据库中的记录通过servlet回显到jsp页面中(连接数据库或者查询參照:对数据进行增删改查)

    我们常常会用到通过图书的名称来查询图书那么这种话我们也就会使用到从数据库中搜索出数据而且载入到自己的Jsp页面中 这种话我们须要将从数据库中获取到的数据放进响应中然后通过%=request.getAt ...

  5. jsp-2 简单的servlet连接mysql数据库 增删改查

    连接mysql数据库的操作 有增删改查 用的包有 commons-lang3-3.5 mysql-connector-java-5.1.40-bin 但是实际上也就是 数据查询和数据处理两种 所以对数 ...

  6. JavaWeb程序利用Servlet的对SQLserver增删改查操作

    声明:学了几天终于将增删改查的操作掌握了,也发现了一些问题,所以总结一下. 重点:操作数据库主要用的是SQL语句跟其他无关. 一:前提知识:PreparedStatement PreperedStat ...

  7. Servlet练习:实现增删改查的综合练习

    ---恢复内容开始--- 本文为原创,转载请注明出处:https://www.cnblogs.com/Tom-shushu/p/9383066.html 本篇内容主要介绍:通过Servlet,JSP, ...

  8. JSP+Servlet+JavaBean实现数据库的增删改查

    基本思想:JSP文件显示页面,使用form或href超链接传值到Servlet中方法,在Servlet方法中调用Dao层的类对象,实现对数据库里的数据的增删改查,之后重新返回到JSP输出操作完的结果. ...

  9. mysql+servlet+jsp实现数据库的增删改查

    首先,了解数据库目前我们仅仅用来存放数据,在这里我们在数据库中生成一个表,包含id,classname,teacher,location.Tomcat用来配置eclipse,只有这样我们才能使用JSP ...

随机推荐

  1. [NOI2017]游戏(2-SAT)

    这是约半年前写的题解了,就搬过来吧 感觉这是NOI2017最水的一题(当然我还是不会2333),因为是一道裸的2-SAT.我就是看着这道题学的2-SAT 算法一:暴力枚举.对于abc二进制枚举,对于x ...

  2. ubuntu vim01

    不小心按了ctrl+s(停止向终端输入),解决办法ctrl+q(恢复向终端输入)

  3. JS学习笔记Day4

    一.什么是函数 将反复使用的功能代码,封装成一独立的模块,这个模块叫做函数 二.封装函数的好处 1.一次封装,多次使用 2.使程序可控 三.函数的分类:内置()函数和自定义函数 四.函数的数据类型(f ...

  4. bzoj3991 LCA + set

    https://www.lydsy.com/JudgeOnline/problem.php?id=3991 小B最近正在玩一个寻宝游戏,这个游戏的地图中有N个村庄和N-1条道路,并且任何两个村庄之间有 ...

  5. KVM安装启动虚拟机

    KVM定制OpenStack云主机 如何定制化OpenStack云主机?从去年10月份刚开始接触OpenStack,到现在也有一年了.虽说目前只是停留在用它,对它的一些组件简单的了解,但谈到制作出一个 ...

  6. NLTK的安装

    一.NLTK:Natural Language Toolkit(自然语言工具包) 下载:http://www.nltk.org pip install nltk 二.使用 import nltk nl ...

  7. beeswarm-蜜蜂图

    一.beeswarm作为一维散点图包R包,可以生成点不重复的图,与stripchart的区别就是等值点不会重叠到一起,下图展示了stripchart与beeswarm图的区别: stripchart( ...

  8. PubMed数据下载

    目标站点分析 目标:抓取页面中的机构名称,日期,标题,作者, 作者信息, 摘要 程序实现 # -*- coding: utf-8 -*- """ @Datetime: 2 ...

  9. svn 基础

    安装,略过. 快速创建.配置及启动项目 创建项目 svnadmin create /home/svn/project_name #创建名为project_name的项目(/home/svn为自定义创建 ...

  10. Nginx 简单安装

    关于nginx的介绍:http://baike.baidu.com/link?url=UZjpP8y4MUgrjqACfxd7c3Cm4L8PnJsKkxSJQ3CrRcKZUjkkl4zGNs6Pr ...