一、模糊查询
在allUser.jsp中添加如下代码
在去web.xml中添加上
在servlet包中新建一个SearchServlet:
package com.zhongruan.servlet;
import com.zhongruan.model.User;
import com.zhongruan.pojo.PageInfo;
import com.zhongruan.service.IUserService;
import com.zhongruan.service.impl.UserServiceImpl;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;
public class SearchServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
IUserService userService=new UserServiceImpl();
String username=req.getParameter("username");
List<User> users=userService.search(username);
HttpSession session=req.getSession();
PageInfo pageInfo=new PageInfo();
pageInfo.setList(users);
session.setAttribute("pageInfo",pageInfo);
req.getRequestDispatcher("/allUser.jsp").forward(req,resp);
}
}
在IUserDao中添加“List search(String username);”.
在UserDaolmpl中添加以下代码:
@Override
public List<User> search(String username) {
ResultSet resultSet = null;
PreparedStatement statement = null;
Connection connection = null;
List<User>users = new ArrayList<>();
try {
connection = DBUtil.getConnection();
String sql = "select * from account where username like ?";
statement = connection.prepareStatement(sql);
statement.setString(1,"%"+username+"%");
resultSet = statement.executeQuery();
while (resultSet.next()) {
User user = new User();
user.setId(resultSet.getInt(1));
user.setUsername(resultSet.getString(2));
user.setPassword(resultSet.getString(3));
users.add(user);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
DBUtil.closeALL(resultSet, statement, connection);
}
return users;
}
在IUserService中添加“ Listsearch(String username);”。
在UserServicelmpl中添加以下代码:
@Override
public List<User> search(String username) {
return userDao.search(username);
}