为什么在返回使用Java / Jersey的404响应时获得静态文本/ html? [英] Why do I get static text/html when returning a 404 Response with Java / Jersey?

查看:106
本文介绍了为什么在返回使用Java / Jersey的404响应时获得静态文本/ html?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Java,Jetty和Jersey 2.18版本(最新版本),它们托管在Google App Engine上。



假设我有一项服务, / p>

  @GET 
@Produces(MediaType.APPLICATION_JSON)
@Path(/ {userId})
public Response getUser(@PathParam(userId)String userId)
{
...
}

当我这样做时:

  return Response.ok()
.entity(user)
.build();

我正确接收application / json内容类型和正文。
但是当我这样做时:

  return响应
.status(404)
.entity (新的ResponseModel(100,找不到用户))
.build();

与返回任何4XX或5XX状态相同,我收到一个text / html内容类型这个HTML body:

 < html> 
< head>
< meta http-equiv =content-typecontent =text / html; charset = utf-8>
< title> 404未找到< / title>
< / head>
< body text =#000000 bgcolor =#ffffff>
< h1>错误:未找到< / h1>
< / body>
< / html>

而不是我放入的对象.entity()



编辑:这是我的web.xml

 <?xml version =1.0encoding =utf -8\" >?; 
version =2.5
xmlns =http://java.sun.com/xml/ns/javaee
xmlns:xsi = http://www.w3.org/2001/XMLSchema-instance
xsi:schemaLocation =http://java.sun.com/xml/ns/javaee http://java.sun.com/ XML / NS / JavaEE的/网络app_2_5.xsd>

< servlet>
< servlet-name> Jersey Web Application< / servlet-name>
< servlet-class> org.glassfish.jersey.servlet.ServletContainer< / servlet-class>
< init-param>
< param-name> com.sun.jersey.api.json.POJOMappingFeature< / param-name>
< param-value> true< /参数值>
< / init-param>
< init-param>
< param-name> jersey.config.server.provider.packages< / param-name>
< param-value> com.mypackage.services; org.codehaus.jackson.jaxrs< / param-value>
< / init-param>
< init-param>
< param-name> jersey.config.server.provider.classnames< / param-name>
< param-value>
org.glassfish.jersey.server.gae.GaeFeature;
org.glassfish.jersey.server.mvc.jsp.JspMvcFeature;
org.glassfish.jersey.media.multipart.MultiPartFeature;
< / param-value>
< / init-param>
< init-param>
< param-name> com.sun.jersey.config.feature.Trace< / param-name>
< param-value> true< /参数值>
< / init-param>
<加载启动> 1< /加载启动>
< / servlet>
< servlet-mapping>
< servlet-name> Jersey Web Application< / servlet-name>
< url-pattern> / rest / *< / url-pattytern>
< / servlet-mapping>

< welcome-file-list>
< welcome-file> home.jsp< / welcome-file>
< / welcome-file-list>

< filter>
< filter-name> ObjectifyFilter< / filter-name>
< filter-class> com.googlecode.objectify.ObjectifyFilter< / filter-class>
< / filter>
< filter-mapping>
< filter-name> ObjectifyFilter< / filter-name>
< url-pattern> / *< / url-pattern>
< / filter-mapping>

<! - Spring Security Filter - >
< context-param>
< param-name> contextConfigLocation< / param-name>
< param-value> /WEB-INF/applicationContext.xml< / param-value>
< / context-param>

< listener>
< listener-class> org.springframework.web.context.ContextLoaderListener< / listener-class>
< / listener>

< filter>
< filter-name> GlobalResponseFilter< / filter-name>
< filter-class> com.mypackage.GlobalResponseFilter< / filter-class>
< / filter>
< filter-mapping>
< filter-name> GlobalResponseFilter< / filter-name>
< url-pattern> / *< / url-pattern>
< / filter-mapping>

< filter>
< filter-name> springSecurityFilterChain< / filter-name>
< filter-class> org.springframework.web.filter.DelegatingFilterProxy< / filter-class>
< / filter>
< filter-mapping>
< filter-name> springSecurityFilterChain< / filter-name>
< url-pattern> / *< / url-pattern>
< / filter-mapping>

< security-constraint>
< web-resource-collection>
< web-resource-name>所有< / web-resource-name>
< url-pattern> / *< / url-pattern>
< / web-resource-collection>
< user-data-constraint>
< transport-guarantee> CONFIDENTIAL< / transport-guarantee>
< / user-data-constraint>
< / security-constraint>

<! - ** - >
<! - **一般会话超时时间(分钟) - >
<! - ** - >

< session-config>
< session-timeout> 1440< / session-timeout>
< / session-config>
< / web-app>

ResponseModel只是一个基本的可序列化java类:

  import java.io.Serializable; 


public class ResponseModel implements Serializable
{
private static final long serialVersionUID = 1L;

private int code;
私有序列化数据;

public ResponseModel()
{
}

公共ResponseModel(int代码,可序列化数据)
{
System。 err.println(Code+ code +:+ data);
this.code = code;
this.data = data;
}

public int getCode()
{
return code;
}

public void setCode(int code)
{
this.code = code;
}

public Serializable getData()
{
return data;
}

public void setData(可序列化数据)
{
this.data = data;
}
}


解决方案

Can您再次尝试以下配置:

 < servlet> 
< servlet-name> API< / servlet-name>
< servlet-class> org.glassfish.jersey.servlet.ServletContainer< / servlet-class>
...
< init-param>
< param-name> jersey.config.server.response.setStatusOverSendError< / param-name>
< param-value> true< /参数值>
< / init-param>
< / servlet>

flag 定义了Jersey在发送4xx或5xx响应状态时是否使用 ServletResponse.sendError (标志 false )或 ServletResponse.setStatus (标志为 true )。


$ b 调用 ServletResponse.sendError 通常会重置响应实体和标题,并返回一个(text / html)错误页面状态码。



由于您想要返回自定义错误实体,因此您需要将此标志设置为 true


I'm working with Java, Jetty and Jersey 2.18 (latest for now) hosted on a Google App Engine.

Let say I have a service such that

@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("/{userId}")
public Response getUser(@PathParam("userId") String userId)
{
    ...
}

When I do:

    return Response.ok()
            .entity(user)
            .build();

I correctly receive an application/json content-type and body. But when I do:

    return Response
            .status(404)
            .entity(new ResponseModel(100, "user not found"))
            .build();

same as for returning any 4XX or 5XX status, I receive a text/html content-type along with this HTML body:

<html>
  <head>
    <meta http-equiv="content-type" content="text/html;charset=utf-8">
    <title>404 Not Found</title>
  </head>
  <body text=#000000 bgcolor=#ffffff>
    <h1>Error: Not Found</h1>
  </body>
</html>

and not the object I put in .entity()

Edit: Here is my web.xml

<?xml version="1.0" encoding="utf-8"?>
<web-app
    version="2.5"
    xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

    <servlet>
        <servlet-name>Jersey Web Application</servlet-name>
        <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
        <init-param>
            <param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
            <param-value>true</param-value>
        </init-param>
        <init-param>
            <param-name>jersey.config.server.provider.packages</param-name>
            <param-value>com.mypackage.services;org.codehaus.jackson.jaxrs</param-value>
        </init-param>
        <init-param>
            <param-name>jersey.config.server.provider.classnames</param-name>
            <param-value>
                org.glassfish.jersey.server.gae.GaeFeature;
                org.glassfish.jersey.server.mvc.jsp.JspMvcFeature;
                org.glassfish.jersey.media.multipart.MultiPartFeature;
            </param-value>
        </init-param>
        <init-param>
            <param-name>com.sun.jersey.config.feature.Trace</param-name>
            <param-value>true</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>Jersey Web Application</servlet-name>
        <url-pattern>/rest/*</url-pattytern>
    </servlet-mapping>

    <welcome-file-list>
        <welcome-file>home.jsp</welcome-file>
    </welcome-file-list>

    <filter>
        <filter-name>ObjectifyFilter</filter-name>
        <filter-class>com.googlecode.objectify.ObjectifyFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>ObjectifyFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <!-- Spring Security Filter -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/applicationContext.xml  </param-value>
    </context-param>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <filter>
        <filter-name>GlobalResponseFilter</filter-name>
        <filter-class>com.mypackage.GlobalResponseFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>GlobalResponseFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <filter>
        <filter-name>springSecurityFilterChain</filter-name>
        <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>springSecurityFilterChain</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <security-constraint>
        <web-resource-collection>
            <web-resource-name>everything</web-resource-name>
            <url-pattern>/*</url-pattern>
        </web-resource-collection>
        <user-data-constraint>
            <transport-guarantee>CONFIDENTIAL</transport-guarantee>
        </user-data-constraint>
    </security-constraint>

    <!-- ** -->
    <!-- ** General session timeout in minutes -->
    <!-- ** -->

    <session-config>
        <session-timeout>1440</session-timeout>
    </session-config>    
</web-app>

ResponseModel is just a basic serializable java class :

import java.io.Serializable;


public class ResponseModel implements Serializable
{
    private static final long   serialVersionUID    = 1L;

    private int                 code;
    private Serializable        data;

    public ResponseModel()
    {
    }

    public ResponseModel(int code, Serializable data)
    {
        System.err.println("Code " + code + " : " + data);
        this.code = code;
        this.data = data;
    }

    public int getCode()
    {
        return code;
    }

    public void setCode(int code)
    {
        this.code = code;
    }

    public Serializable getData()
    {
        return data;
    }

    public void setData(Serializable data)
    {
        this.data = data;
    }
}

解决方案

Can you try again with the following configuration:

<servlet>
    <servlet-name>API</servlet-name>
    <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
    ...
    <init-param>
        <param-name>jersey.config.server.response.setStatusOverSendError</param-name>
        <param-value>true</param-value>
   </init-param>
</servlet>

This flag defines if Jersey - when sending a 4xx or 5xx response status - uses ServletResponse.sendError(flag is false) or ServletResponse.setStatus (flag is true).

Calling ServletResponse.sendError usually resets the response entity and headers and returns a (text/html) error page for the status code.

Since you want to return an own custom error entity, you need to set this flag to true.

这篇关于为什么在返回使用Java / Jersey的404响应时获得静态文本/ html?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆