Showtoday'sdatetime
主页包含一个链接,)com/zetcode/controller/MyController.javapackagecom.zetcode.controller;importorg.springframework.stereotype.Controller;importorg.springframework.web.bind.annotation.GetMapping;importorg.springframework.web.servlet.ModelAndView;importjava.time.LocalDateTime;importjava.time.format.DateTimeFormatter;@ControllerpublicclassMyController{@GetMapping(value="/")publicStringhome(){return"index";}@GetMapping(value="/show")publicModelAndViewshow(){varmav=newModelAndView();varnow=LocalDateTime.now();varformatter=DateTimeFormatter.ISO_DATE_TIME;vardateTimeFormatted=formatter.format(now);mav.addObject("now",dateTimeFormatted);mav.setViewName("show");returnmav;}}MyController提供了两个GET映射,$mvnjetty:run我们运行服务器并找到localhost:8080以获取具有链接的主页,我们具有必要的依赖性。resources/logback.xml%d{HH:mm:ss.SSS}%blue(%-5level)%magenta(%logger{36})-%msg%nlogback.xml是Logback日志库的配置文件,ModelAndViewModelAndView是WebMVC框架中Model和View的持有人,在本教程中, 文章目录ModelAndViewSpringModelAndView示例SpringModelAndView教程展示了如何在SpringWeb应用的控制器中使用ModelAndView,我们使用Freemarker进行视图解析,@OverrideprotectedClass>[]getServletConfigClasses(){returnnewClass[]{WebConfig.class};}getServletConfigClasses()返回Web配置类,@GetMapping(value="/show")publicModelAndViewshow(){show()方法返回ModelAndView,它是SpringWeb应用的前端控制器,,以显示今天的日期时间,ModelAndView仅保留两者,varmav=newModelAndView();varnow=LocalDateTime.now();varformatter=DateTimeFormatter.ISO_DATE_TIME;vardateTimeFormatted=formatter.format(now);mav.addObject("now",dateTimeFormatted);mav.setViewName("show");returnmav;创建一个ModelAndView并填充数据,视图名称由setViewName()设置,Spring将视图名称解析为show.ftl,pom.xmlsrc├───main│├───java││└───com││└───zetcode││├───config│││MyWebInitializer.java│││WebConfig.java││└───controller││MyController.java│└───resources││logback.xml│└───templates│index.ftl│show.ftl└───test└───java这是项目结构,com/zetcode/config/MyWebInitializer.javapackagecom.zetcode.config;importorg.springframework.context.annotation.Configuration;importorg.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;@ConfigurationpublicclassMyWebInitializerextendsAbstractAnnotationConfigDispatcherServletInitializer{@OverrideprotectedClass>[]getRootConfigClasses(){returnnull;}@OverrideprotectedClass>[]getServletConfigClasses(){returnnewClass[]{WebConfig.class};}@OverrideprotectedString[]getServletMappings(){returnnewString[]{"/"};}}MyWebInitializer注册SpringDispatcherServlet,(resources在类路径上。
,我们将模板文件的位置设置为classpath上的templates目录,pom.xml4.0.0com.zetcodespringmodelandview1.0-SNAPSHOTwarUTF-811115.1.3.RELEASEch.qos.logbacklogback-classic1.2.3javax.servletjavax.servlet-api4.0.1providedorg.springframeworkspring-context-support5.1.3.RELEASEorg.springframeworkspring-webmvc5.1.3.RELEASEorg.freemarkerfreemarker2.3.28org.apache.maven.pluginsmaven-war-plugin3.2.2org.eclipse.jettyjetty-maven-plugin9.4.14.v20181114在pom.xml中,以使控制器有可能在单个返回值中返回模型和视图,Spring是用于创建企业应用的流行Java应用框架,我们使用ModelAndView来组织模型和视图。