2011-03-20 36 views
0

我想要一個操作來發出一個400錯誤的HTTP響應,並在驗證失敗時以文本/純文本解釋問題。struts2 + Tomcat中的純文本400錯誤消息

我可以使用org.apache.struts2.dispatcher.HttpHeaderResult得到400錯誤:

@Action(results = { 
    @Result(name = SUCCESS, type=ResultTypes.HTTP_HEADER, 
      params = { "status", "200" }), 
    @Result(name = INPUT, type=ResultTypes.HTTP_HEADER, 
      params = { "error", "400", "errorMessage", "${errorMessage}" }) 
}) 
@Override 
public String execute() {  
    return INPUT; 
} 

public String getErrorMessage() { 
    return "There was an error"; 
} 

的問題是,Tomcat的 「包裝」 我的反應到HTML頁面如下:

HTTP/1.1 400 Bad Request 
Server: Apache-Coyote/1.1 
Content-Type: text/html;charset=utf-8 
Content-Length: 1214 
Date: Sun, 20 Mar 2011 00:43:55 GMT 
Connection: close 

<html><head><title>Apache Tomcat/6.0.29 - Error report</title><style><!-- 
H1 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:22px;} 
H2 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:16px;} 
H3 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:14px;} 
BODY {font-family:Tahoma,Arial,sans-serif;color:black;background-color:white;} 
B {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;} 
P {font-family:Tahoma,Arial,sans-serif;background:white;color:black;font-size:12px;} 
A {color : black;} A.name {color : black;} HR {color : #525D76;}--></style> </head> 
<body><h1>HTTP Status 400 - There was an error</h1><HR size="1" noshade="noshade"> 
<p><b>type</b> Status report</p><p><b>message</b> <u>There was an error</u></p> 
<p><b>description</b> <u>The request sent by the client was syntactically incorrect (There was an error).</u></p> 
<HR size="1" noshade="noshade"><h3>Apache Tomcat/6.0.29</h3></body></html> 

雖然我只是想是這樣的:

HTTP/1.1 400 Bad Request 
Server: Apache-Coyote/1.1 
Content-Type: text/plain;charset=utf-8 
Content-Length: 18 
Date: Sun, 20 Mar 2011 00:43:55 GMT 
Connection: close 

There was an error 

感謝。

+0

爲對象表示,需要提供自定義錯誤頁。 – 2011-03-20 09:01:48

回答

1

指定頁面使用在web.xml

<error-page> 
     <error-code>400</error-code> 
     <location>/error/400.html</location> 
    </error-page> 
+0

我想這是解決方案的一部分,但: - 正如所給出的,它將發出一個HTML頁面 - 如果被替換爲400.txt,我將得到一個FIXED文本純文本消息 - 不是由操作發出的消息。 – jsalvata 2011-03-20 22:47:06

+0

您可以從錯誤頁面中的操作訪問消息http://stackoverflow.com/questions/995248/how-to-get-the-message-in-a-custom-error-page-tomcat – objects 2011-03-20 23:25:37

+0

讓它成爲一個內容類型爲text/plain的JSP頁面。 – 2011-03-21 02:54:53

0

錯誤頁要使用的配置響應代碼,您可以使用:

- your action code - 
if (errorOccurs) 
    return ERROR; 

struts.xml: 
    <action name="..." class="..."> 
     <result type="json"> <!-- success --> 
      <param name="root">...</param> 
     </result> 
     <result name="error" type="json"> <!-- error --> 
      <param name="root">...</param> 
      <param name="statusCode">500</param> 
     </result> 
    </action>