SprintBoot + thyemleaf页面开发之一

 

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

 废话很少说,正式进入主题。java

 SpringBoot 开发接口的几种方式:json

 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+ModelAndViewmvc

@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。例如app

@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
相关文章
相关标签/搜索