jsp (二) 练习
package cn.sasa.serv; import java.io.IOException; import java.sql.SQLException; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.dbutils.QueryRunner; import org.apache.commons.dbutils.handlers.BeanListHandler; import cn.sasa.domain.MyUser; import cn.sasa.utils.C3P0Utils; public class UserServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { QueryRunner runner = new QueryRunner(C3P0Utils.getDataSource()); String sql = "select * from user"; List<MyUser> users = null; try { users = runner.query(sql, new BeanListHandler<MyUser>(MyUser.class)); } catch (SQLException e) { e.printStackTrace(); } request.setAttribute("users", users);//将获取到的list传到request域中,供jsp页面获取 request.getRequestDispatcher("/MyUser.jsp").forward(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ page import="java.util.*" %> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> </head> <body> <% List<cn.sasa.domain.MyUser> users = (List<cn.sasa.domain.MyUser>)request.getAttribute("users"); if(users != null){ for(cn.sasa.domain.MyUser user : users){ out.write(user.getName()); out.write("<br/>"); } } %> </body> </html>