java HttpServletResponse response设置返回参数 response.setStatus(200); response.setContentType("application/json"); response.getWriter().write("{'message':'数据已接收'}"); 怎么返回
时间: 2024-03-17 22:44:05 浏览: 246
这段代码的含义是设置 HTTP 响应状态码为 200,设置响应数据类型为 JSON,然后通过输出流将一个 JSON 字符串 "{'message':'数据已接收'}" 返回给客户端。具体的实现可以参考下面的示例代码:
```java
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 设置响应状态码为 200
response.setStatus(200);
// 设置响应数据类型为 JSON
response.setContentType("application/json");
// 获取输出流
PrintWriter out = response.getWriter();
// 输出响应数据
out.write("{'message':'数据已接收'}");
// 关闭输出流
out.close();
}
```
在这个示例代码中,我们通过 setStatus 方法设置响应状态码为 200,通过 setContentType 方法设置响应数据类型为 JSON。然后,我们通过 getWriter 方法获取输出流,并使用 write 方法将 JSON 字符串 "{'message':'数据已接收'}" 输出到客户端。最后,我们通过关闭输出流来释放资源。
相关问题
解释 public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { //支持跨域请求 response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE"); response.setHeader("Access-Control-Max-Age", "3600"); response.setHeader("Access-Control-Allow-Credentials", "true"); response.setHeader("Access-Control-Allow-Headers", "x-requested-with,request-source,Token, Origin,imgType, Content-Type, cache-control,postman-token,Cookie, Accept,authorization"); response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin")); // 跨域时会首先发送一个OPTIONS请求,这里我们给OPTIONS请求直接返回正常状态 if (request.getMethod().equals(RequestMethod.OPTIONS.name())) { response.setStatus(HttpStatus.OK.value()); return false; } IgnoreAuth annotation; if (handler instanceof HandlerMethod) { annotation = ((HandlerMethod) handler).getMethodAnnotation(IgnoreAuth.class); } else { return true; } //从header中获取token String token = request.getHeader(LOGIN_TOKEN_KEY); /** * 不需要验证权限的方法直接放过 */ if(annotation!=null) { return true; } TokenEntity tokenEntity = null; if(StringUtils.isNotBlank(token)) { tokenEntity = tokenService.getTokenEntity(token); } if(tokenEntity != null) { request.getSession().setAttribute("userId", tokenEntity.getUserid()); request.getSession().setAttribute("role", tokenEntity.getRole()); request.getSession().setAttribute("tableName", tokenEntity.getTablename()); request.getSession().setAttribute("username", tokenEntity.getUsername()); return true; } PrintWriter writer = null; response.setCharacterEncoding("UTF-8"); response.setContentType("application/json; charset=utf-8"); try { writer = response.getWriter(); writer.print(JSONObject.toJSONString(R.error(401, "请先登录"))); } finally { if(writer != null){ writer.close(); } } // throw new EIException("请先登录", 401); return false; }
这段代码是一个Java的拦截器,用于对请求进行预处理。在这个方法中,首先设置了支持跨域请求的相关参数,然后判断是否为OPTIONS请求,如果是则直接返回正常状态。接下来判断是否有IgnoreAuth注解,如果有则直接放过,否则从请求头中获取Token,并通过TokenService验证Token的有效性。如果Token有效,则将相关信息存入Session中,否则返回401错误提示。最后,返回true或者false表示是否允许请求继续处理。
@Component public class AuthorizationInterceptor implements HandlerInterceptor { public static final String LOGIN_TOKEN_KEY = "Token"; @Autowired private TokenService tokenService; @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { //支持跨域请求 response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE"); response.setHeader("Access-Control-Max-Age", "3600"); response.setHeader("Access-Control-Allow-Credentials", "true"); response.setHeader("Access-Control-Allow-Headers", "x-requested-with,request-source,Token, Origin,imgType, Content-Type, cache-control,postman-token,Cookie, Accept,authorization"); response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin")); // 跨域时会首先发送一个OPTIONS请求,这里我们给OPTIONS请求直接返回正常状态 if (request.getMethod().equals(RequestMethod.OPTIONS.name())) { response.setStatus(HttpStatus.OK.value()); return false; } IgnoreAuth annotation; if (handler instanceof HandlerMethod) { annotation = ((HandlerMethod) handler).getMethodAnnotation(IgnoreAuth.class); } else { return true; } //从header中获取token String token = request.getHeader(LOGIN_TOKEN_KEY); /** * 不需要验证权限的方法直接放过 */ if(annotation!=null) { return true; } TokenEntity tokenEntity = null; if(StringUtils.isNotBlank(token)) { tokenEntity = tokenService.getTokenEntity(token); } if(tokenEntity != null) { request.getSession().setAttribute("userId", tokenEntity.getUserid()); request.getSession().setAttribute("role", tokenEntity.getRole()); request.getSession().setAttribute("tableName", tokenEntity.getTablename()); request.getSession().setAttribute("username", tokenEntity.getUsername()); return true; } PrintWriter writer = null; response.setCharacterEncoding("UTF-8"); response.setContentType("application/json; charset=utf-8"); try { writer = response.getWriter(); writer.print(JSONObject.toJSONString(R.error(401, "请先登录"))); } finally { if(writer != null){ writer.close(); } } // throw new EIException("请先登录", 401); return false; } }
这是一个基于 Spring 框架的拦截器,用于实现权限验证功能。在每次请求到达控制器之前,该拦截器会检查请求头中是否存在名为 "Token" 的字段,并根据该字段去数据库中查询对应的 Token 实体。如果查询到 Token 实体,则将用户的相关信息存储到当前会话中,然后放行该请求,否则返回未登录的错误信息。该拦截器还实现了跨域请求的支持,将请求头中的 Origin 字段写入响应头的 "Access-Control-Allow-Origin" 字段中,从而允许跨域请求。同时,对于 OPTIONS 请求,直接返回正常状态,不做任何处理。
阅读全文