1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
| import com.demo.pojo.Student; import freemarker.template.Configuration; import freemarker.template.Template; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest; import java.io.File; import java.io.FileWriter; import java.util.ArrayList; import java.util.HashMap;
@Controller @RequestMapping("/freemarker") public class FreeMarkerController {
@RequestMapping("/student") public String hello(Model model) throws Exception {
ArrayList<Student> students = new ArrayList<>(); students.add(new Student(1, "jack", 18, "郑州二七")); students.add(new Student(2, "rose", 19, "郑州中原")); students.add(new Student(3, "tom", 20, "郑州金水"));
model.addAttribute("students",students);
return "/student"; }
@RequestMapping("createHtml") @ResponseBody public String createHtml()throws Exception{ Configuration configuration = new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS); configuration.setDefaultEncoding("utf-8");
configuration.setDirectoryForTemplateLoading(new File("D:/ftl")); ArrayList<Student> students = new ArrayList<>(); students.add(new Student(1,"张三",18,"北京")); students.add(new Student(2,"李四",19,"上海")); students.add(new Student(3,"王五",20,"广州"));
HashMap<String,ArrayList> map = new HashMap<>(); map.put("students",students);
FileWriter fileWriter = new FileWriter(new File("D:/ftl_html/student.html"));
Template template = configuration.getTemplate("student.ftl"); template.process(map,fileWriter); fileWriter.close();
return "success"; } }
|