如何在Scalatra中设置默认响应Content-Type为application/json
Got it, let's get your Scalatra app returning JSON by default without needing the Accept: application/json header every time. Here are the straightforward steps to make this happen:
1. Ensure Jackson JSON Support is Configured
First, make sure you have the Scalatra-Jackson dependency added to your build (for SBT, add this to your build.sbt):
libraryDependencies += "org.scalatra" %% "scalatra-json" % "2.8.0" // Use your matching Scalatra version
This gives you automatic serialization of Scala objects to JSON, which is far cleaner than manually crafting JSON strings.
2. Update Your Servlet to Set Default Content-Type
Modify your servlet class to extend JacksonJsonSupport and add a before filter that sets the default content type to JSON. This filter runs before every request, ensuring the response header is always set correctly:
import org.scalatra._ import org.scalatra.json._ import com.fasterxml.jackson.databind.ObjectMapper import com.fasterxml.jackson.module.scala.DefaultScalaModule class ExampleServlet extends ScalatraServlet with JacksonJsonSupport { // Register Scala module for Jackson to handle Scala-specific types (Maps, case classes, etc.) override protected def defaultObjectMapper: ObjectMapper = { val mapper = super.defaultObjectMapper mapper.registerModule(DefaultScalaModule) mapper } // Set default Content-Type to JSON for all incoming requests before() { contentType = formats("json") // Uses Scalatra's predefined JSON format, which automatically handles charset } get("/v1/example") { // Return a Scala object (Map, case class, etc.) – Jackson will serialize it to JSON automatically Map("hello" -> "hello", "world" -> "world") } }
3. Test the Change
Now when you run your app and hit the endpoint without the Accept header:
$ curl -i -X GET 'http://localhost:8080/v1/example'
You should see the response header Content-Type: application/json;charset=utf-8 and the JSON body:
{"hello":"hello","world":"world"}
Quick Notes:
- If you were previously returning raw strings (like your
HelloWorld(hello,world)example), switch to returning Scala objects (Maps, case classes) – Jackson handles serialization cleanly and avoids manual JSON formatting errors. - If you need to override the default for specific endpoints, you can set
contentTypedirectly in that route (e.g.,contentType = "text/html"for a single HTML-focused route).
内容的提问来源于stack exchange,提问作者Bob Kuhar

