Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/308.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Spring mvc Spring拦截器的json格式错误响应_Spring Mvc_Jboss_Iinterceptor - Fatal编程技术网

Spring mvc Spring拦截器的json格式错误响应

Spring mvc Spring拦截器的json格式错误响应,spring-mvc,jboss,iinterceptor,Spring Mvc,Jboss,Iinterceptor,我正在编写一个基于REST的web服务。我需要以JSON格式返回所有响应。我有一个拦截器来验证我的身份验证参数。在身份验证失败的情况下,我必须以JSON格式返回错误响应 目前我正在做 setHeader(“内容类型”、“应用程序/json”); senderro(HttpServletResponse.SCu UNAUTHORIZED,“{\”error\”:\“缺少身份验证参数\”}) 响应主体如下所示 JBoss Web/2.1.3.GA-错误报告HTTP状态401-{“错误”:“缺少身份

我正在编写一个基于REST的web服务。我需要以JSON格式返回所有响应。我有一个拦截器来验证我的身份验证参数。在身份验证失败的情况下,我必须以JSON格式返回错误响应

目前我正在做

setHeader(“内容类型”、“应用程序/json”); senderro(HttpServletResponse.SCu UNAUTHORIZED,“{\”error\”:\“缺少身份验证参数\”})

响应主体如下所示

JBoss Web/2.1.3.GA-错误报告HTTP状态401-{“错误”:“缺少身份验证参数”}键入状态报告{p>消息{“错误”:“缺少身份验证参数”}

说明此请求需要HTTP身份验证({“错误”:“缺少身份验证参数”})。

JBoss Web/2.1.3.GA


我只需要JSON字符串作为响应。请帮助我。

您可能应该为此使用spring security。如果您想手动执行,在响应中使用
senderro
的另一种方法是使用SpringMVC和返回JSON

首先定义一个错误类*:

public class Error {
    public message;
    public exception;
    public Error(String message, Exception ex) {
        this.message = message;
        this.exception = ex;
    }
}
还有一个例外:

public class NotAuthenticatedException extends Exception {
    // ...
}
然后在控制器中,在适当的时间抛出异常,用
@ExceptionHandler
捕捉它,并返回一个
响应属性
,其中包含
错误
实例和适当的错误代码

@Controller
public class SimpleController {
    @RequestMapping(...)
    public String aMethod() {
        // ...
        throw new NotAuthenticatedException("Missing Authentication Parameters");
    }

    @ExceptionHandler(NotAuthenticatedException.class)
    public ResponseEntity<Error> handleNotAuthenticatedException(
            NotAuthenticatedException ex, 
            HttpServletRequest request) {
        return new ResponseEntity<Error>(
            new Error(ex.getMessage(), ex), 
            HttpStatus.UNAUTHORIZED
        );
    }
}
@控制器
公共类SimpleController{
@请求映射(…)
公共字符串aMethod(){
// ...
抛出新的NotAuthenticationDexception(“缺少身份验证参数”);
}
@ExceptionHandler(NotAuthenticationDexception.class)
公共响应处理未经身份验证异常(
未经认证,
HttpServletRequest(请求){
返回新响应(
新错误(例如getMessage(),例如),
HttpStatus.UNAUTHORIZED
);
}
}
*使用getter/setter来取悦java约定