在web项目中一般常见的五种返回形式:
代码见:https://github.com/BenMario315/SpringBootLearn,demo
- 返回页面,使用模板引擎,spring boot推荐使用thymeleaf,类似的还有freemarker等。
- 返回字符串(json),一般用于完全的前后端分离开发,或者提供接口服务。
- 返回重定向,一些较少的业务需求。
- 转发,一些较少的业务需求。
- 流输出,常用于下载文件。
方法前代码:
package cn.mario.springboot.controller; import org.json.JSONException; import org.json.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.thymeleaf.util.StringUtils; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.OutputStream; import java.net.URLEncoder; /** * @PackageName cn.mario.springboot.controller * @ClassName TestController * @Author BenMario * @Date 2018/5/23 3:16 * @Description test controoler * @Version 1.0 **/ @Controller public class TestController { private Logger logger = LoggerFactory.getLogger(TestController.class);
1.返回页面:使用spring boot 推荐的thymeleaf,默认模板路径:resources/templates/*.html
代码:
/** * retrun page * @param request HttpServletRequest * @param response HttpServletResponse * @return test page */ @RequestMapping(value = "/testReturnPage") public String testReturnPage(HttpServletRequest request, HttpServletResponse response) { logger.debug("into testReturnPage function"); System.out.println("into testReturnPage function"); return "test"; }
2.1返回普通字符串
代码:
/** * retrun general string * @param request HttpServletRequest * @param response HttpServletResponse * @return str */ @ResponseBody @RequestMapping(value = "/testReturnString") public String testReturnString(HttpServletRequest request, HttpServletResponse response) { logger.debug("into testReturnString function"); System.out.println("into testReturnString function"); String str = "RETRUN STRING"; return str; }
2.2返回json字符串
代码:
/** * retrun json string * @param request HttpServletRequest * @param response HttpServletResponse * @return JSONObject to string */ @ResponseBody @RequestMapping(value = "/testReturnJSONObject") public String testReturnJSONObject(HttpServletRequest request, HttpServletResponse response) { logger.debug("into testReturnJSONObject function"); System.out.println("into testReturnJSONObject functioin"); JSONObject jsonObject = new JSONObject(); try { jsonObject.put("name_1", StringUtils.toString(1)); jsonObject.put("name_2", 1); } catch (JSONException e) { e.printStackTrace(); } return jsonObject.toString(); }
3.1.1利用关键字“redirect”跨web服务重定向
代码:
/** * retrun cross web project redirect * @param request HttpServletRequest * @param response HttpServletResponse * @return redirect cross web project */ @RequestMapping(value = "/testRedirect_1") public String testRedirect_1(HttpServletRequest request, HttpServletResponse response) { logger.debug("inot testRedirect_1 function"); System.out.println("into testRedirect_1 function"); String url = "http://www.baidu.com"; return "redirect:" + url; }
3.1.2利用关键字“redirect”同web服务重定向
代码:
/** * retrun same web project redirect * @param request HttpServletRequest * @param response HttpServletResponse * @return redirect same web project */ @RequestMapping(value = "/testRedirect_2") public String testRedirect_2(HttpServletRequest request, HttpServletResponse response) { logger.debug("into testRedirect_2 function"); System.out.println("into testRedirect_2 function"); String url = "/testRedirect_1"; return "redirect:" + url; }
3.2.1利用HttpServletRespons对象跨web服务重定向
代码:
/** * retrun cross web project redirect * @param request HttpServletRequest * @param response HttpServletResponse * @return redirect cross web project */ @RequestMapping(value = "/testRedirect_3") public void testRedirect_3(HttpServletRequest request, HttpServletResponse response) { logger.debug("into testRedirect_3 function"); System.out.println("into testRedirect_3 function"); String url = "http://www.baidu.com"; try { response.sendRedirect(url); } catch (IOException e) { e.printStackTrace(); } }
3.2.2利用HttpServletRespons对象同web服务重定向
代码:
/** * retrun same web project redirect * @param request HttpServletRequest * @param response HttpServletResponse * @return redirect same web project */ @RequestMapping(value = "/testRedirect_4") public void testRedirect_4(HttpServletRequest request, HttpServletResponse response) { logger.debug("into TestController中的testRedirect_4 function"); System.out.println("into TestController中的testRedirect_4 function"); String url = "/testRedirect_3"; try { response.sendRedirect(url); } catch (IOException e) { e.printStackTrace(); } }
4.1跨web项目不能转发
代码:
/** * retrun cross web project forward * @param request HttpServletRequest * @param response HttpServletResponse * @return forward cross web project * @note fail. Only the same web project forwarding */ @RequestMapping(value = "/testForward_1") public void testForward_1(HttpServletRequest request, HttpServletResponse response) { logger.debug("into testForward_1 function"); System.out.println("into testForward_1 function"); String url = "http://www.baidu.com"; try { request.getRequestDispatcher(url).forward(request, response); } catch (ServletException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } System.out.println("After the forwarding is completed,the code can also run."); }
4.2同web项目转发
代码:
/**
* retrun same web project forward
* @param request HttpServletRequest
* @param response HttpServletResponse
* @return forward same web project
*/
@RequestMapping(value = "/testForward_2")
public void testForward_2(HttpServletRequest request, HttpServletResponse response) {
logger.debug("into testForward_2 function");
System.out.println("into testForward_2 function");
String url = "/testReturnPage";
try {
request.getRequestDispatcher(url).forward(request, response);
} catch (ServletException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("After the forwarding is completed,the code can also run.");
}
5.1流输出,用于下载文件
代码:
/** * retrun stream for downlaod file * @param request HttpServletRequest * @param response HttpServletResponse */ @RequestMapping(value = "/testReturnStream") public void testReturnStream(HttpServletRequest request, HttpServletResponse response) { logger.debug("into testReturnStream function"); System.out.println("into testReturnStream function"); byte[] bts = new byte[8192]; int len = -1; try { // set type is dawnload response.setHeader("content-Type", "application/force-download"); // set file name and charset response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("test.log", "utf-8")); OutputStream output = response.getOutputStream(); File file = new File("./logs/log.log"); FileInputStream input = new FileInputStream(file); while ((len = input.read(bts)) != -1) { output.write(bts, 0, len); } } catch (IOException e) { e.printStackTrace(); } }
方法后代码:
}
对于一般的web项目来说, 以上五种返回形式应该是比较全面了。几乎也都说明了每种返回形式的应用场景。如有疏漏或错误,请不吝指出。