给个例子来复习一下,模拟地址本显示。
这里顺便学些一下自动排序的做法,定义Contact类,实现Comparable接口。Contact是个简单的POJO,getter和setter从略。此外MonthDay和Instant是Java 8增加的时间处理类。
public class Contact implements Comparable<Contact>{ private String firstName; private String lastName; private String phoneNumber; private String address; private MonthDay birthday; private Instant dateCreated; public Contact() { } public Contact(String firstName, String lastName, String phoneNumber, String address, MonthDay birthday,Instant dateCreated) { ...... } ..setters 和 getters.... @Override public int compareTo(Contact other) { int last = lastName.compareTo(other.lastName); if(last == 0){ return firstName.compareTo(other.firstName); } return last; } }ListServlet如下。一般而言,应该将jsp隐藏到/WEB-INF这个安全目录下,而不是在外面可直接读取的位置。
@WebServlet(name = "ListServlet", urlPatterns = "/list") public class ListServlet extends HttpServlet { private static final long serialVersionUID = 1L; /* Contact类实现了排序接口Comparable,在此我们定义排序Set,采用TreeSet方式*/ private static final SortedSet<Contact> contacts = new TreeSet<>(); /* 预设数据,模拟地址本*/ static{ contacts.add(new Contact("Flowingflying", "Wei", "13312345678", "Guangzhou", MonthDay.of(Month.MAY, 20),Instant.parse("2016-08-05T21:34:12Z"))); contacts.add(new Contact("John", "Smith", "17712345678", "Guangxi", MonthDay.of(Month.APRIL, 21),Instant.parse("2016-08-04T20:31:13Z"))); contacts.add(new Contact( "Peter", "Smith", "555-0712", "315 Maple St", null,Instant.parse("2012-10-15T15:31:17Z"))); } ... ... /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { if(request.getParameter("empty") != null){/* 为了jsp测试,传递一个空的地址本过去 */ request.setAttribute("contacts", Collections.<Contact>emptySet()); }else{/* 传递地址本信息过去 */ request.setAttribute("contacts", contacts); } /* 跳转到jsp中,注意jsp存放的路径*/ request.getRequestDispatcher("/WEB-INF/jsp/view/list.jsp").forward(request, response); } }index.jsp跳转至/list
<c:redirect url="/list" />在base.jspf中已经给出引入:
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>web.xm有如下信息:
<jsp-config> <jsp-property-group> <url-pattern>*.jsp</url-pattern> <url-pattern>*.jspf</url-pattern> <page-encoding>UTF-8</page-encoding> <scripting-invalid>false</scripting-invalid> <include-prelude>/WEB-INF/jsp/base.jspf</include-prelude> <trim-directive-whitespaces>true</trim-directive-whitespaces> <default-content-type>text/html</default-content-type> </jsp-property-group> </jsp-config>但是,在Eclipse有个问题,如果我们不在本文件中给出taglib,那么jsp就不能自动使用智能拼词,并出现warning,这个是很讨厌的,所以我喜欢在jsp中多写两行,引入tablib。
相关链接: 我的Professional Java for Web Applications相关文章
