开发者

How to invoke converter in JSP file in Spring Framework?

I am Spring Framework newbe, and I managed to make a very simple CMS, using Hibernate data persistence (I use mySQL database) to display articles on frontpage. My data model is using some Drupalesque terminology (like "node"), because I am used to that CMS. ;)

Now I'm struggling with the task of converting the UNIX timestamp, that is stored in database, into ISO date format. I decided to write my own converter to do this task.

I did my homework, and I read the Spring reference guides, googled for tutorials etc, but it seems that converters are primarily a tool for converting data from GET parameters and POST queries. And what about converting fields from objects binded into Model by controllers? What did I missed during m开发者_C百科y research?

Part of JSP's code (frontpage.jsp):

    <div id="content-wrapper">
        <div id="center-column">
            <c:forEach items="${NodeCollection}" var="node">
                <div class="node">
                    <h3>${node.title}</h3>
                    <span class="pub_time">${node.timestamp}</span>
                    <div class="content">${node.teaser}</div>
                </div>
            </c:forEach>
        </div>

My controller:

@Controller
public class FrontpageController {

    private NodeRevisionsDAOImpl nodeRevisionsDAO;

    @Autowired
    void setnodeRevisionsDAO(NodeRevisionsDAOImpl myNodeRevisionsDAOImpl) {
        this.nodeRevisionsDAO = myNodeRevisionsDAOImpl;
    }

    @RequestMapping ( value = "/index.htm", method = RequestMethod.GET )
    ModelAndView getMainPage(ModelAndView mav) {
        ModelMap modelMap = new ModelMap();
        Collection nodes = nodeRevisionsDAO.listNodeRevisions(5);
        modelMap.addAttribute("NodeCollection", nodes);
        mav.setViewName("frontpage");
        mav.addAllObjects(modelMap);
        return mav;
    }

}

My dummy converter (I'll add implementation later):

package converters;

import org.springframework.core.convert.converter.Converter;

public class TimestampToDateConverter implements Converter<Long, String> {

    public String convert(Long s) {
        return "0000-00-00 00:00:00"; //Dummy code
    }

}

Dispacher's config:

<mvc:annotation-driven conversion-service="conversionService" />

<bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean">
    <property name="converters">
        <list>
            <bean class="converters.TimestampToDateConverter"/>
        </list>
    </property>
</bean>


Why don't you use Date data type. Using JSTL you can implement your case easily without additional converter, for example

<fmt:formatDate pattern="yyyy-MM-dd hh:mm:ss" value="${node.time}" />
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜