Servlet基础及实现增删查改案例(JSP--->Servlet--->Java--->数据库)
引言:
本文主要分享了Servlet的基本概述、如何编写一个Servlet及步骤、Servlet的执行流程、与JSP页面的比较最后分享了一个比较大的增删改查案例(涉及到Servlet、Java、JSP以及数据库);
@[toc]
1. Servlet概述
传统的Java代码无法获取请求参数,只有使用Java程序中的Servlet技术才可以获取,但是需要服务器编译环境的支持;
Servlet就是一个Java程序,一个Java类;可以和浏览器进行交互,是一个动态资源;Servlet的使用需要有服务器编译环境的支持需要导入Servlet的API;
2. 编写Servlet的步骤
- 首先需要配置好Tomcat
- 创建一个web项目
- 创建一个HTML表单
- 完善包
- 编写一个继承自HttpServlet的类
- 重写service方法
- 完成业务内容
- 在web.xml中配置Servlet
- 运行
2.1 服务器编译环境
EClipse
IDEA
2.2 创建一个index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>登录界面</title>
<style >
body{
text-align: center;
}
</style>
</head>
<body>
<form action="dealLogin" method = "POST">
USERNAME:<input type = "text" name = "username"/><br/>
PASSWORD:<input type = "password" name = "password"/><br/>
<input type = "submit" value = "LOGIN"/>
</form>
</body>
</html>
2.3 编写一个继承自HttpServlet的类并重写service方法
package com.kaka.web;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class UserServlet extends HttpServlet{
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//转码
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
String username = request.getParameter("username");
String password = request.getParameter("password");
System.out.println("username" + username + "password" + password);
//打印流
PrintWriter out = response.getWriter();
out.print("username" + username + "password" + password);
}
}
2.4 配置xml
<servlet>
<servlet-name>myServlet</servlet-name>
<servlet-class>com.kaka.web.UserServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>myServlet</servlet-name>
<url-pattern>/dealLogin</url-pattern>
</servlet-mapping>
2.5 运行结果
3. Servlet的执行流程
以第二板块的Servlet为例:
- 根据表单中的action属性dealLogin,与web.xml中的servlet-mapping的url-pattern匹配;
- 找到servlet-mapping中的servlet-name指向的对象,如果存在直接调用该对象的service方法;
- 如果对象不存在,在servlet节点中查找同名找到servlet-class项的字符串;
- 使用Class.forName()方法反射该类对象;
- 调用该类的父类的service方法;
- 有同类型的请求到来时,重复步骤2;
4. Servlet与JSP的比较
- 书写方面:jsp由html+java脚本组成;Servlet只能由java语言编写;
- 执行原理上:jsp转化为java然后编译为.class最后执行执行;Servlet.java直接编译为.class然后执行
- 内容方面:jsp有9大隐式对象;servlet没有隐式对象;
- 编写规范上:servlet需要继承HttpServlet,重写父类的方法:service、doGet、doPost.....
5. 基于Servlt完成CRUD
步骤:
- 编写数据库
- 创建web工程、建包
- 配置xml文件
- 创建index.jsp 含有查询部门信息链接,作为主界面;
- 创建StudentList.jsp 全查展示页
创建StuServlet 完成list查询的逻辑
- 含有action=list的传参 根据action的字符串取值做不同的操作
- 编写StuDao
- 编写Student实体
- 在列表页添加链接: < a href="addStudent.jsp" >添加学生信息
编写addStudent.jsp页面
在service方法中添加逻辑分支
5.1 创建数据库STUDENT表
CREATE TABLE student(
id INT PRIMARY KEY AUTO_INCREMENT,
NAME VARCHAR(50) NOT NULL,
sex VARCHAR(10) DEFAULT 'man',
age VARCHAR(5)
) CHARSET = utf8;
5.2 xml文件的配置
<servlet>
<servlet-name>stuServlet</servlet-name>
<servlet-class>com.kaka.controller.StuServlet</servlet-class>
<!-- 设置servlet的初始化参数 -->
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>stuServlet</servlet-name>
<url-pattern>/stu</url-pattern>
</servlet-mapping>
5.3 创建index.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>
<a href="stu?action=list">查询学生信息</a>
</body>
</html>
5.4 创建StudentList.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" import = "java.util.*,com.kaka.entity.*"%>
<!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>
<h2>显示学生信息清单</h2>
<div>
<a href = "addStudent.jsp">添加学生信息</a>
<table>
<tr><td>ID</td><td>NAME</td><td>SEX</td><td>AGE</td>
<%
if(request.getAttribute("stus")!=null){
List<Student> li = (List<Student>)request.getAttribute("stus");
for(int i = 0; i < li.size(); i++){
Student student = li.get(i);
%>
<tr>
<td><%=student.getId() %></td>
<td><%=student.getName() %>
<td><%=student.getSex() %></td>
<td><%=student.getAge() %></td>
<td>
<a href = "stu?action=findOne&id=<%=student.getId()%>">修改</a>
<a href = "stu?action=delete&id=<%=student.getId()%>">删除</a>
</td>
</tr>
<%
}
}
%>
</table>
</div>
</body>
</html>
5.5 创建addStudent.jsp
- 在添加表单中需要含有action的隐藏域
- < input type="hidden" name="action" value="add" / >
<%@ 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>
<h1>添加学生信息</h1>
<form action="stu" method = "POST">
<input type = "hidden" name = "action" value = "add"/>
ID:<input type="text" name="id"/><br/>
NAME:<input type = "text" name = "name"/><br/>
SEX:<input type = "text" name = "sex"/><br/>
AGE:<input type = "text" name = "age"/><br/>
<input type = "submit" value = "add"/><br/>
</form>
</body>
</html>
5.6 创建updateStudent.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" import = "com.kaka.entity.*"%>
<!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>
<h1>修改界面</h1>
<%
Student s = (Student)request.getAttribute("student");
if(s!=null){
%>
<form action="stu" method="POST">
<input type = "hidden" name = "action" value = "update"/>
ID:<input type="text" name="id" value="<%=s.getId()%>" readonly="true"/><br/>
NAME:<input type = "text" name = "name" value="<%=s.getName()%>"/><br/>
SEX:<input type = "text" name = "sex" value="<%=s.getSex()%>"/><br/>
AGE:<input type = "text" name = "age" value="<%=s.getAge()%>"/><br/>
<input type = "submit" value = "update"/><br/>
</form>
<%}else{
out.print("修改的对象不存在!!!");
}
%>
</body>
</html>
5.7 创建JDBCUtil.java
package com.kaka.util;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class JDBCUtil {
//定义常量
final static String driver = "com.mysql.jdbc.Driver";
final static String url = "jdbc:mysql://localhost:3306/db0711?useUnicode=true&characterEncoding=utf8";
final static String username = "root";
final static String password = "root";
//声明常用的对象
protected Connection conn = null;
protected PreparedStatement pstmt = null;
protected ResultSet rs = null;
//静态代码块
static{
try {
Class.forName(driver);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
//获取连接
public void getConnection(){
try {
conn = DriverManager.getConnection(url, username, password);
} catch (SQLException e) {
e.printStackTrace();
}
}
//关闭资源
public void closeAll(){
if(rs != null){
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(pstmt != null){
try {
pstmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(conn != null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
5.8 创建Student.java实现类
package com.kaka.entity;
public class Student {
private int id;
private String name;
private String sex;
private String age;
public Student() {
super();
// TODO Auto-generated constructor stub
}
public Student(int id, String name, String sex, String age) {
super();
this.id = id;
this.name = name;
this.sex = sex;
this.age = age;
}
@Override
public String toString() {
return "Student [id=" + id + ", name=" + name + ", sex=" + sex + ", age=" + age + "]";
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
}
5.9 创建StuDao.java接口
package com.kaka.dao;
import java.util.List;
import com.kaka.entity.Student;
public interface StuDao {
public List<Student> findAll();
public boolean addStudent(Student student);
public Student findOne(int id);
public boolean updateStudent(Student student);
public boolean deleteDeptById(int id);
}
5.10 创建StuDaoImpl.java接口实现类
package com.kaka.dao;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import com.kaka.entity.Student;
import com.kaka.util.JDBCUtil;
public class StuDaoImpl extends JDBCUtil implements StuDao{
@Override
public List<Student> findAll() {
List<Student> li = new ArrayList<Student>();
try {
String sql = "SELECT * FROM STUDENT";
super.getConnection();
super.pstmt = super.conn.prepareStatement(sql);
rs = pstmt.executeQuery();
while(rs.next()){
Student stu = new Student();
stu.setId(rs.getInt("id"));
stu.setName(rs.getString("name"));
stu.setSex(rs.getString("sex"));
stu.setAge(rs.getString("age"));
li.add(stu);
}
return li;
} catch (SQLException e) {
e.printStackTrace();
}finally{
super.closeAll();
}
return null;
}
@Override
public boolean addStudent(Student student) {
try {
String sql = "INSERT INTO STUDENT(id,name,sex,age) VALUES(?,?,?,?)";
super.getConnection();
super.pstmt = super.conn.prepareStatement(sql);
pstmt.setInt(1, student.getId());
pstmt.setString(2, student.getName());
pstmt.setString(3, student.getSex());
pstmt.setString(4, student.getAge());
int i = pstmt.executeUpdate();
if(i > -1){
return true;
}
} catch (SQLException e) {
e.printStackTrace();
}finally{
super.closeAll();
}
return false;
}
@Override
public Student findOne(int id) {
try {
String sql = "SELECT * FROM STUDENT WHERE ID=?";
super.getConnection();
pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, id);
rs = pstmt.executeQuery();
Student student = new Student();
if(rs.next()){
student.setId(rs.getInt("id"));
student.setName(rs.getString("name"));
student.setSex(rs.getString("sex"));
student.setAge(rs.getString("age"));
}
return student;
} catch (SQLException e) {
e.printStackTrace();
}finally{
super.closeAll();
}
return null;
}
@Override
public boolean updateStudent(Student student) {
try {
String sql = "UPDATE STUDENT SET name=?,sex=?,age=? WHERE id=?";
super.getConnection();
super.pstmt = super.conn.prepareStatement(sql);
pstmt.setString(1, student.getName());
pstmt.setString(2, student.getSex());
pstmt.setString(3, student.getAge());
pstmt.setInt(4, student.getId());
int i = pstmt.executeUpdate();
if(i > -1){
return true;
}
} catch (SQLException e) {
e.printStackTrace();
}finally{
super.closeAll();
}
return false;
}
@Override
public boolean deleteDeptById(int id) {
try {
String sql = "DELETE FROM STUDENT WHERE ID=?";
super.getConnection();
super.pstmt = super.conn.prepareStatement(sql);
pstmt.setInt(1, id);
int i = pstmt.executeUpdate();
if(i > -1){
return true;
}
} catch (SQLException e) {
e.printStackTrace();
}finally{
super.closeAll();
}
return false;
}
}
5.11 创建StuServlet.java
package com.kaka.controller;
import java.io.IOException;
import java.util.List;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.kaka.dao.StuDao;
import com.kaka.dao.StuDaoImpl;
import com.kaka.entity.Student;
public class StuServlet extends HttpServlet{
private final static String oldEncoding = "ISO-8859-1";
private static String newEncoding = null;
public StuServlet() {
super();
}
@Override
public void destroy() {
super.destroy();
}
@Override
public void init(ServletConfig config) throws ServletException {
newEncoding = config.getInitParameter("encoding");
}
@Override
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//获取操作类型
String action = request.getParameter("action");
//根据操作类型执行特定操作
if("list".equals(action)){
//获取StuDao对象
StuDao studao = new StuDaoImpl();
//调用dao中的findAll方法
List<Student> all = studao.findAll();
//将查询结果放入request作用域中
request.setAttribute("stus", all);
//请求转向到列表显示页面
request.getRequestDispatcher("studentList.jsp").forward(request, response);
}else if("add".equals(action)){
//获取表单数据
int id = Integer.parseInt(request.getParameter("id")==null?"0":request.getParameter("id"));
String name = request.getParameter("name");
//转码
String newName = new String(name.getBytes(oldEncoding),newEncoding);
String sex = request.getParameter("sex");
String newSex = new String(sex.getBytes(oldEncoding),newEncoding);
String age = request.getParameter("age");
String newAge = new String(age.getBytes(oldEncoding),newEncoding);
//封装实体对象
Student student = new Student(id,newName,newSex,newAge);
//创建dao对象
StuDao studao = new StuDaoImpl();
boolean b = studao.addStudent(student);
if(b){
//使用重定向
response.sendRedirect("stu?action=list");
//request.getRequestDispatcher("stu?action=list").forward(request, response);
}
}else if("findOne".equals(action)){
int id = Integer.parseInt(request.getParameter("id")==null?"0":request.getParameter("id"));
//创建dao对象
StuDao studao = new StuDaoImpl();
//根据ID查找
Student student = studao.findOne(id);
//将需要修改的对象放入request作用域中
request.setAttribute("student", student);
//请求转向到编辑页面
request.getRequestDispatcher("updateStudent.jsp").forward(request, response);
}else if("update".equals(action)){
//获取表单数据
int id = Integer.parseInt(request.getParameter("id")==null?"0":request.getParameter("id"));
String name = request.getParameter("name");
String sex = request.getParameter("sex");
String age = request.getParameter("age");
//转码
String newName = new String(name.getBytes(oldEncoding),newEncoding);
String newSex = new String(sex.getBytes(oldEncoding),newEncoding);
String newAge = new String(age.getBytes(oldEncoding),newEncoding);
//封装实体对象
Student student = new Student(id,newName,newSex,newAge);
//创建dao对象
StuDao studao = new StuDaoImpl();
boolean b = studao.updateStudent(student);
if(b){
//使用重定向
response.sendRedirect("stu?action=list");
//request.getRequestDispatcher("stu?action=list").forward(request, response);
}
}else if("delete".equals(action)){
//获取需要删除的对象id
int id = Integer.parseInt(request.getParameter("id")==null?"0":request.getParameter("id"));
//创建dao对象
StuDao studao = new StuDaoImpl();
boolean b = studao.deleteDeptById(id);
if(b){
//使用重定向
response.sendRedirect("stu?action=list");
}
}
}
}
5.12 运行结果
显示清单页面----->全查