1、Servlet处理请求三大步
- 获取前端数据(根据需求写,可能会不写,因为前端没有传数据)
- 服务端处理数据
- 服务端把处理好的数据发给客户端
2、运行流程
1.在xml中注册servlet。
2.写servlet-class,这个类一定要继承HttpServlet。
3.写class的步骤就是上面的写servlet三大步骤。
实现具体的get或者post方法。写业务逻辑,按照 1、servlet处理请求三大步 进行操作。
4.第三步骤写完,需要请求转发或者重定向到一个jsp页面或者Servlet。
5.在jsp页面用EL表达式,或者JSTL表达式中的forEach标签,遍历循环出服务端传递过来的参数。
3、demo项目源码
1、demo项目操作步骤:
- 将客户端传递进来的数据进行服务端操作。
- 服务端处理好数据后传给客户端。
2、demo项目代码:
查询到数据库的数据,通过客户端给用户展示。
1. 数据库工具类:
数据库访问工具类BaseDao
(1)工具类BaseDao:
//操作数据库的公共类
public class BaseDao {
private static String driver;
private static String url;
private static String username;
private static String password;
//静态代码块,类加载的时候就初始化了
static {
Properties properties = new Properties();
//通过类加载器读取对应的资源
InputStream is = BaseDao.class.getClassLoader().getResourceAsStream("db.properties");
try {
properties.load(is);
} catch (IOException e) {
e.printStackTrace();
}
driver = properties.getProperty("driver");
url = properties.getProperty("url");
username = properties.getProperty("username");
password = properties.getProperty("password");
}
//获取数据库的链接
public static Connection getConnection(){
Connection connection = null;
try {
Class.forName(driver);
connection = DriverManager.getConnection(url, username, password);
} catch (Exception e) {
e.printStackTrace();
}
return connection;
}
//编写查询公共方法
public static ResultSet execute(Connection connection,PreparedStatement preparedStatement,ResultSet resultSet,String sql,Object[] params) throws SQLException {
//预编译的sql,在后面直接执行就可以了
preparedStatement = connection.prepareStatement(sql);
for (int i = 0; i < params.length; i++) {
//setObject,占位符从1开始,但是我们的数组是从0开始!
preparedStatement.setObject(i+1,params[i]);
}
resultSet = preparedStatement.executeQuery();
return resultSet;
}
//编写增删改公共方法
public static int execute(Connection connection,PreparedStatement preparedStatement,String sql,Object[] params) throws SQLException {
preparedStatement = connection.prepareStatement(sql);
for (int i = 0; i < params.length; i++) {
//setObject,占位符从1开始,但是我们的数组是从0开始!
preparedStatement.setObject(i+1,params[i]);
}
int updateRows = preparedStatement.executeUpdate();
return updateRows;
}
//释放资源
public static boolean closeResource(Connection connection,PreparedStatement preparedStatement,ResultSet resultSet){
boolean flag = true;
if (resultSet!=null){
try {
resultSet.close();
//GC回收
resultSet = null;
} catch (SQLException e) {
e.printStackTrace();
flag = false;
}
}
if (preparedStatement!=null){
try {
preparedStatement.close();
//GC回收
preparedStatement = null;
} catch (SQLException e) {
e.printStackTrace();
flag = false;
}
}
if (connection!=null){
try {
connection.close();
//GC回收
connection = null;
} catch (SQLException e) {
e.printStackTrace();
flag = false;
}
}
return flag;
}
}
(2)db配置文件
配置连接数据库:
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/schemas?useSSL=false&serverTimezone=Hongkong&characterEncoding=utf-8&autoReconnect=true
username=root
password=123456
2. 接口注册到xml文件
<!--查询用户和用户角色的名字-->
<servlet>
<servlet-name>UserAndRoleInfoList</servlet-name>
<servlet-class>com.lei.my.all_user_info.UserAndRoleInfoList</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>UserAndRoleInfoList</servlet-name>
<url-pattern>/my_user/userAndRoleInfoList.do</url-pattern>
</servlet-mapping>
3. 业务实现
(1)Servlet实现类
public class UserAndRoleInfoList extends HttpServlet {
/**
* 1、前端获取数据(不一定要获取)
* 2、服务器处理数据
* 3、返回数据给客户端
*/
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
// 1、前端获取数据(不一定要获取)
// 2、服务器处理数据
List<User> userList = new ArrayList<User>();
// 数据库操作。查询用户列表
PreparedStatement pstm = null;
ResultSet rs = null;
Connection connection = BaseDao.getConnection();
if (connection != null) { // 连接到数据库后,进行sql语句
StringBuffer sql = new StringBuffer();
sql.append("select u.userName,u.address,r.roleName from smbms_user as u " +
"left join smbms_role as r on r.id = u.userRole");
List<Object> list = new ArrayList<Object>();
Object[] params = list.toArray();
try {
rs = BaseDao.execute(connection, pstm, rs, sql.toString(), params); // 执行sql语句
while (rs.next()) {
User user = new User(); // 通过实体类拿到对应的属性
user.setUserName(rs.getString("userName"));
user.setAddress(rs.getString("address"));
user.setUserRoleName(rs.getString("roleName"));
userList.add(user); // 把user添加到userList容器中
}
BaseDao.closeResource(null, pstm, rs); // 关闭资源
} catch (SQLException e) {
e.printStackTrace();
}
}
// 3、返回数据给客户端
// 把数据放到req请求对象内,返回给前端
req.setAttribute("users",userList);
// 请求转发
req.getRequestDispatcher("/my_user/UserAndRoleInfoList.jsp").forward(req,resp);
}
}
(2)实体类
package com.lei.pojo;
import java.util.Date;
public class User {
private Integer id; //id
private String userCode; //用户编码
private String userName; //用户名称
private String userPassword; //用户密码
private Integer gender; //性别
private Date birthday; //出生日期
private String phone; //电话
private String address; //地址
private Integer userRole; //用户角色
private Integer createdBy; //创建者
private Date creationDate; //创建时间
private Integer modifyBy; //更新者
private Date modifyDate; //更新时间
private Integer age;//年龄
private String userRoleName; //用户角色名称
// geter、seter、toString()方法
}
(3)请求处理完后跳转到jsp数据展示页面
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> // 导入的JSTL核心
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h1>取出的值为:</h1>
<%--
var:每一次遍历出来的变量
items:要遍历的对象
begin:从哪个下标开始
end:到哪个下标结束
step:,一次走几个元素
--%>
// 通过jstl表达式中的forEach标签,循环遍历出变量user的值
<c:forEach var="user" items="${users}"> // JSTL代码
${user.userRoleName}// 通过el表达式.方法,指定参数通过客户端传递给服务端
${user.userName}
${user.address}
<br/>
</c:forEach>
</body>
</html>