html里面使用:<script language='javascript' src='http://www.yousite.com/rootpath/printWriterHtmlJavascript/PrintWriter'></script>
@RequestMapping(value="/PrintWriter", method={RequestMethod.GET,RequestMethod.POST},produces="text/html;charset=UTF-8")
@ResponseBody
public void PrintWriter(HttpServletRequest request,HttpServletResponse response){
//设置跨域访问
response.setHeader("Access-Control-Allow-Origin","*");
response.setHeader("Access-Control-Allow-Methods","POST, GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age","3600");
response.setHeader("Access-Control-Allow-Headers","x-requested-with,Authorization");
response.setHeader("Access-Control-Allow-Credentials","true");
//设置JavaScript方式输出
response.setContentType("text/javascript;charset=utf-8");
PrintWriter out = = response.getWriter();
StringBuilder sb = new StringBuilder();
//"<script type='text/javascript'>"
sb.append("window.onload = function(){");
sb.append("console.log('javaweb输出JavaScript代码(相当于别人引用了一个.js的文件)');");
sb.append("};");
//"</script>"
out.write(sb.toString());//或者out .println(mm);
out.flush();
out.close();
//自己处理异常try/catch,这里不做列举
}
注意请求头: