简单实现servlet查询数据并请求转发给jsp,再输出给客户端

简单上一下逻辑,例子是一个搜索关键字的功能

简单实现servlet查询数据并请求转发给jsp,再输出给客户端_第1张图片

 需要由servlet和jsp使用请求转发共同完成

先看student类

/**
 * @Classname Student
 * @author: 我心
 * @Description:
 * @Date 2021/10/5 11:08
 * @Created by Lenovo
 */
public class Student {
    private int id;
    private String name;
    private int age;

    public Student(int id, String name, int age) {
        this.id = id;
        this.name = name;
        this.age = age;
    }
    //返回测试的学生列表
    public static List getStudentList(int count){
        ArrayList students = new ArrayList<>();
        for(int i=1;i<=count;i++){
            Student student = new Student(i, "学生" + i, 18);
            students.add(student);
        }
        return students;
    }

    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 int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

再看servlet类

public class SearchStudent extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取请求的参数
        //调用对应实现类的service方法去查找并返回数据
        //这里仅用直接生成的数据来代替以上两个步骤
        List studentList = Student.getStudentList(20);
        //将数据保存到request域中,并请求转发给jsp页面
       req.setAttribute("stuList",studentList);
       //请求转发
        req.getRequestDispatcher("/te/studentInformation.jsp").forward(req,resp);
    }
}

 

 jsp页面

<%@ page import="pojo.Student" %>
<%@ page import="java.util.List" %><%--
  Created by IntelliJ IDEA.
  User: Lenovo
  Date: 2021/10/5
  Time: 11:14
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>


    输出学生信息


    
        <%
            List studentList =(List) request.getAttribute("stuList");
            for (Student student : studentList) {
                %>
        
        <%
            }
        %>
    
id name age
<%=student.getId()%> <%=student.getName()%> <%=student.getAge()%>

最终结果

简单实现servlet查询数据并请求转发给jsp,再输出给客户端_第2张图片 

需要注意的是,必须先访问servlet程序,获取数据,才能展示信息,直接访问jsp页面是没有数据的,并且可能发生空指针异常 

你可能感兴趣的:(笔记,java)