1、在UserDao下创建 selectByName方法来实现查找功能
public User selectByName(String name){
ResultSet rs=null;
Connection connection=null;
PreparedStatement pstmt=null;
DButil util=new DButil();
User user=new User();
try {
connection=util.getConnection();
pstmt=connection.prepareStatement("select * from a where name =?");
pstmt.setString(1,name);
rs=pstmt.executeQuery();
//处理结果集
while (rs.next()){
user.setId(rs.getInt(1));
user.setName(rs.getString(2));
user.setPassword(rs.getString(3));
user.setAge(rs.getString(4));
}
}catch (Exception e){
e.printStackTrace();
}finally {
try {
util.closeAll(rs,pstmt,connection);
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
return user;
}
2、在UserService下调用selectByName方法
public User selectByName(String name){
return userDao.selectByName(name);
}
3、在AddServlet写search方法来设置查早显示
public void search(HttpServletRequest req, HttpServletResponse resp) throws IOException {
resp.setContentType("text/html;charset=GBK");
resp.setContentType("text/html");
String name=req.getParameter("name");
User user1=userService.selectByName(name);
if (user1!=null){
resp.getWriter().write("用户名:"+user1.getName()+" 密码:"+user1.getPassword()+" 年龄"+user1.getAge());
}else {
resp.getWriter().write("失败!");
}
}
4、在search.jsp设置查找页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>查找</title>
</head>
<body>
<form action="/add?method=search" method="post">
<input name="name" placeholder="请输入需要查找的名字">
<input type="submit" value="查找">
</form>
</body>
</html>