jsp+servlet实现搜索框

这是搜索框的html代码

 <form action="/pre/search" method="post">
            <div class="indexSearch">
                <input type="text" placeholder="请输入帖子名" name="partname"/>
                <input type="submit" value="搜索"/>
            </div>
            </form>

搜索其实是sql的模糊查询功能

@Override
    public List<Apost> findByPartName(String partName) {
     
        List<Apost> aposts = new ArrayList<>();
        try{
     
            Connection conn = MySqlDbUtil.getConnection();
           String sql = "SELECT * FROM apost where apName like '%" + partName + "%'";
           PreparedStatement pstmt = conn.prepareStatement(sql);

           //pstmt.setObject(1,obj);
            ResultSet rs = pstmt.executeQuery();
            while(rs.next()){
     
                Apost apost=new Apost();
                User user  = new User();
                Topic topic = new Topic();
                apost.setApId(rs.getInt("apId"));
                apost.setApName(rs.getString("apName"));
                apost.setApContent(rs.getString("apContent"));
                apost.setPublishTime(rs.getTimestamp("publishTime"));
                apost.setReplyTime(rs.getTimestamp("replyTime"));
                apost.setReplyCount(rs.getInt("replyCount"));
                apost.setScanCount(rs.getInt("scanCount"));
                user.setUserId(rs.getInt("userId"));
                apost.setUser(user);
                topic.setTopId(rs.getInt("topId"));
                apost.setTopic(topic);
                aposts.add(apost);
            }

            rs.close();
            pstmt.close();
            conn.close();
        } catch (SQLException e) {
     
            e.printStackTrace();
        } catch (Exception e) {
     
            e.printStackTrace();
        }
        return aposts;
    }
@WebServlet("/pre/search")
public class SearchController extends HttpServlet {
     
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
     
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
     
        String partname = req.getParameter("partname");  //获取搜索框内容
        IApostService service = new ApostService();
        List<Apost> aposts=service.findByPartName(partname);//调用模糊查询
        req.setAttribute("at",aposts);
        req.getRequestDispatcher("/pre/searchapost.jsp").forward(req,resp);


    }
}

你可能感兴趣的:(jsp)