SprintBoot + thyemleaf页面开发之一

 

  以前用过servlet开发页面,用Springmvc开发了接口,不过那时候懵懵懂懂,也没有时间去总结。这次使用SprintBoot + thyemleaf进行页面开发也磕磕碰碰,不过好在通过网络查资料后,弄懂了部分,后面继续学。 其实有时候也迷茫,我是测试,开发学好了真的有用吗?其实平时工作中并不需要我采用SpringBoot这么潮流的架构,唯一的好处就是白盒测试效率比对代码一知半解的人高。

 废话不多说,正式进入主题。

 SpringBoot 开发接口的几种方式:

 1. @RestController + @RequestMapping. 返回结果是json格式String。比如

@RestController

public class caseAction{
@RequestMapping("/singleRun")
    public ArrayList<TestCase> executeSingleCase(String projectName, String caseName, String pageSize, String pageNum){
        int pageSizeTemp = StringUtils.isBlank(pageSize) == true ? 10 : Integer.parseInt(pageSize);
        int pageNumTemp = StringUtils.isBlank(pageNum) == true ? 1 : Integer.parseInt(pageNum);
        Result result = new Result();
        ArrayList<TestCase> caseList = caseService.executeSingleCase(projectName, caseName, pageSizeTemp, pageNumTemp ,result);
        FileUtils.writeLog(projectName, result);
        return caseList;
    }
}

2. @Controller + @RequestMapping + @ResponseBody

@Controller
public class caseAction{ 
@RequestMapping("/singleRun")
@ResponseBody
 public ArrayList<TestCase> executeSingleCase(String projectName, String caseName, String pageSize, String pageNum){
        return caseList;
    }
}

 3. 采用@Controller+ModelAndView

@Controller
public class caseAction{ 
@RequestMapping("/singleRun")
 public ModelAndView executeSingleCase(String projectName, String caseName, String pageSize, String pageNum){
.........
     ModelAndView mv = new ModelAndView();
mv.addObject("caseList",caseList)
        return caseList;
    }
}

 这几种方式最后通过页面访问(get请求),返回的都是json格式String,如果要让其显示在模版里,就需要thyemleaf。例如

@Controller
public class ProjectAction {

    @Resource
    private ProjectService proService;

    @RequestMapping("/")
    public String index(RedirectAttributes attributes) {
        return "redirect:/project/listProject";
    }

    @RequestMapping("/project/listProject")
    public String queryAll(HttpServletRequest request){
        Result result = new Result();
        ArrayList<Project> projectList = proService.queryAll(result);
        FileUtils.writeLog("wali-autoTestPlat",result);
        request.setAttribute("projectList",projectList);
        return "project";
    }
}
由于没有用@RestController,也没有用@ResponseBody,所以index方法不会转化为json格式。 这时候就会按照redirect:/project/listProject 跳转到路径为/project/listProject的方法(也就是queryAll)
方法,如果返回结果转了json,那redirect不会生效,也就是不会跳转其他方法。
如果返回"project",那么就会去默认的模版目录下(resources/templates)找project.html文件,如果没找到就会报错。
如果不返回值,那就会拿路径(/project/listProject)去默认的模板目录下找。

本篇暂时到这,下一篇正式讲到thyemleaf


猜你喜欢

转载自www.cnblogs.com/jefzha/p/9984270.html
今日推荐