jsp自定义标签实现新闻列表(与spring整合)

时间:2021-11-28 23:15:47

1.自定义标签类(注意与spring的整合:service层的调用)

package com.mingda.tag;

import org.apache.log4j.Logger;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.List;

import javax.servlet.ServletContext;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.SimpleTagSupport;

import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.mingda.entity.News;
import com.mingda.service.NewsService;

public class ListNewsTag extends SimpleTagSupport {
    /**
     * Logger for this class
     */
    private static final Logger logger = Logger.getLogger(ListNewsTag.class);

    private int record;
    private String url;

    private NewsService newsService;

    @Override
    public void doTag() throws JspException, IOException {
        setNewsService();
        List<News> newsList = newsService.listNews();
        StringBuffer sb = new StringBuffer();
        sb.append("<div class=\"con clearself\">");
        for (int i = 0; i < newsList.size(); i++) {
            News news = (News) newsList.get(i);
            if (i == 0) {
                sb.append("<ul style=\"width:410px;\" class=\"list fl\">");
            }
            if (i % 3 == 0 && i != 0) {
                sb.append("<ul style=\"width:410px; margin-left:50px; padding-left:50px; border-left:1px solid #e6e5e5;\" class=\"list fl\">");
            }
            sb.append("<li><span class=\"fr\">");
            sb.append(new SimpleDateFormat("yyyy-MM-dd").format(news.getCreateTime()));
            sb.append("</span><a href=\"");
            sb.append(news.getHref());
            sb.append("\">");
            sb.append(news.getTitle());
            sb.append("</a></li>");
            if (i % 3 == 2 || newsList.size() - 1 == i) {
                sb.append("</ul>");
            }
        }
        sb.append("</div>");
        JspWriter out = getJspContext().getOut();
        System.out.println(sb.toString());
        out.write(sb.toString());
    }

    public void setNewsService() {
        logger.info("注入newsService");
        PageContext pageContext = (PageContext) this.getJspContext();
        ServletContext servletContext = pageContext.getServletContext();
        WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);
        this.newsService = (NewsService) wac.getBean("newsService");
    }

    public void setRecord(int record) {
        this.record = record;
    }

    public void setUrl(String url) {
        this.url = url;
    }

}

 

2.WEB-INF先新建hao.tld文件

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <taglib xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd" version="2.0">
 3 <description>自定义标签集合(QQ:1176069533)</description>
 4     <tlib-version>1.0</tlib-version>
 5     <short-name>hao</short-name>
 6     <uri>/hao-tags</uri>
 7     <!-- 输出新闻列表标签  -->
 8     <tag>
 9         <description>输出新闻列表标签</description>
10         <name>listOut</name>
11         <tag-class>com.mingda.tag.ListNewsTag</tag-class>
12         <body-content>scriptless</body-content>
13         <attribute>
14             <name>record</name>
15             <required>true</required>
16             <rtexprvalue>true</rtexprvalue>
17             <type>int</type>
18         </attribute>
19         <attribute>
20             <name>url</name>
21             <required>true</required>
22             <rtexprvalue>true</rtexprvalue>
23             <type>java.lang.String</type>
24         </attribute>
25     </tag>
26 </taglib>


3.前台调用test.jsp

<%@ page language="java" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@taglib prefix="hao" uri="/hao-tags"%>
<!DOCTYPE html>
<html>
<head>
<base href="${pageContext.request.scheme}://${pageContext.request.serverName}:${pageContext.request.serverPort}${pageContext.request.contextPath}/"> 
<meta content="text/html; charset=utf-8" http-equiv="Content-Type">
<meta content="IE=EmulateIE7" http-equiv="X-UA-Compatible">
<%@ include file="include/include.jsp"%>
</head>
<!-- 新闻列表 -->
<hao:listOut record="10" url="/newsList"></hao:listOut>

4.service层模拟返回的结果

 1 package com.mingda.service.impl;
 2 
 3 import java.io.Serializable;
 4 import java.util.Date;
 5 import java.util.LinkedList;
 6 import java.util.List;
 7 
 8 import org.apache.log4j.Logger;
 9 import org.springframework.beans.factory.annotation.Autowired;
10 import org.springframework.stereotype.Service;
11 
12 import com.mingda.dao.NewsDao;
13 import com.mingda.entity.News;
14 import com.mingda.service.NewsService;
15 
16 @Service(value = "newsService")
17 public class NewsServiceImpl implements NewsService {
18     /**
19      * Logger for this class
20      */
21     private static final Logger logger = Logger.getLogger(NewsServiceImpl.class);
22     private NewsDao newsDao;
23 
24     public NewsDao getNewsDao() {
25         return newsDao;
26     }
27     @Autowired
28     public void setNewsDao(NewsDao newsDao) {
29         this.newsDao = newsDao;
30     }
31 
32     @Override
33     public List<News> listNews() {
34         logger.info("查看新闻列表!");
35         List<News> newses=new LinkedList<News>();
36         for(int i=0;i<6;i++){
37             News news=new News();
38             news.setId(""+i);
39             news.setTitle("明大企业集团XXXX"+i);
40             news.setContent("明大企业集团战略发展XXXXX"+i);
41             news.setHref("news/00"+(i+1));
42             news.setCreateTime(new Date());
43             newses.add(news);
44         }
45         return newses;
46     }
47 
48     @Override
49     public Serializable save(News news) {
50         return newsDao.save(news);
51     }
52 
53 }

 5.效果预览:

jsp自定义标签实现新闻列表(与spring整合)