本文整理汇总了Scala中javax.servlet.http.HttpServlet类的典型用法代码示例。如果您正苦于以下问题:Scala HttpServlet类的具体用法?Scala HttpServlet怎么用?Scala HttpServlet使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了HttpServlet类的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。
示例1: doGet
//设置package包名称以及导入依赖的类
package co.informatica.mvc.controllers
import javax.servlet.http.{HttpServlet, HttpServletRequest, HttpServletResponse}
import co.informatica.mvc.models.Model
import co.informatica.mvc.views.BaseTemplate
trait BaseController extends HttpServlet {
lazy val model: Model = null
lazy val template: BaseTemplate = null
override def doGet(req: HttpServletRequest, resp: HttpServletResponse) = {
println("GET: " + this.getClass.getName)
println("getPathInfo:")
println(req.getPathInfo())
}
override def doPost(req: HttpServletRequest, resp: HttpServletResponse) = {
println("POST: " + this.getClass.getName)
}
}
示例2: AdminServlet
//设置package包名称以及导入依赖的类
package org.eck.servlets
import java.util.logging.Logger
import javax.servlet.http.{HttpServletResponse, HttpServletRequest, HttpServlet}
import com.google.gson.JsonParser
import org.eck.entities.Settings
class AdminServlet extends HttpServlet {
val logger = Logger.getLogger("AdminServlet")
override def doGet(req: HttpServletRequest, resp: HttpServletResponse) = {
if (req.getParameter("json") != null) {
val json = new JsonParser().parse(req.getParameter("json")).getAsJsonObject
logger.info("Updating settings data " + json.toString)
Settings.fromJson(json)
}
printForm(resp)
}
def printForm(resp: HttpServletResponse) = {
resp.setContentType("text/html")
resp.getWriter.append("<form action=\"/admin\">")
resp.getWriter.append(" <textarea name=\"json\" rows=\"30\">")
resp.getWriter.append(Settings.asJson.toString)
resp.getWriter.append(" </textarea>")
resp.getWriter.append(" <br/>")
resp.getWriter.append(" <button type=\"submit\">Save</button>")
}
}
示例3: PlayerServlet
//设置package包名称以及导入依赖的类
package org.leanpoker.player
import javax.servlet.annotation.WebServlet
import javax.servlet.http.{HttpServlet, HttpServletRequest, HttpServletResponse}
import com.google.gson.JsonParser
@WebServlet(Array("/"))
class PlayerServlet extends HttpServlet {
override def doGet(req: HttpServletRequest, resp: HttpServletResponse) {
resp.getWriter.print("Scala player is running")
}
@Override
override def doPost(req: HttpServletRequest, resp: HttpServletResponse) {
req.getParameter("action") match {
case "bet_request" =>
val gameState = req.getParameter("game_state")
resp.getWriter.print(Player.betRequest(new JsonParser().parse(gameState)))
case "showdown" =>
val gameState = req.getParameter("game_state")
Player.showdown(new JsonParser().parse(gameState))
case _ =>
resp.getWriter.print(Player.VERSION)
}
}
}
示例4: doGet
//设置package包名称以及导入依赖的类
package com.clay.web.servlets
import java.io._
import java.util.ResourceBundle
import javax.activation.MimetypesFileTypeMap
import javax.servlet.ServletConfig
import javax.servlet.annotation.WebServlet
import javax.servlet.http.{HttpServlet, HttpServletRequest, HttpServletResponse}
import org.springframework.util.StreamUtils
override def doGet(req: HttpServletRequest, response: HttpServletResponse): Unit = {
// We only support HTTP/1.0 and HTTP/1.1
if (!req.getProtocol.endsWith("1.0") && !req.getProtocol.endsWith("1.1")) {
throw new BadRequestServletErrorException()
}
val file = new File(resourcePath + "/" + req.getPathInfo)
if (file.isDirectory) {
throw new UnauthorizedServletErrorException()
}
if (!file.exists()) {
throw new NotFoundServletErrorException()
}
var in: InputStream = null
try {
in = new FileInputStream(file)
response.setContentType(mimeType.getContentType(file))
response.setContentLength(in.available())
StreamUtils.copy(in, response.getOutputStream.asInstanceOf[OutputStream])
} finally {
if (in != null) {
try {
in.close()
} catch {
case ex: Exception => // Ignore
}
}
}
}
}
示例5: RackServer
//设置package包名称以及导入依赖的类
package coder36.rack
import javax.servlet.http.{HttpServlet, HttpServletRequest, HttpServletResponse}
import com.typesafe.scalalogging.LazyLogging
import org.eclipse.jetty.server.Server
import org.eclipse.jetty.servlet.{ServletContextHandler, ServletHolder}
import scala.collection.mutable.Map
class RackServer extends LazyLogging {
val port : Int = 8080
var path : String = ""
val apps = scala.collection.mutable.Map[String,RackServlet]()
def map(path: String) : RackServer = {
this.path = path
this
}
def onto(rack: Rack) = {
apps(path) = new RackServlet(rack, path)
}
def start() : RackServer = {
val context = new ServletContextHandler(ServletContextHandler.SESSIONS)
context.setContextPath("/")
val server = new Server(port)
server.setHandler(context)
apps.foreach( app => context.addServlet(new ServletHolder(app._2), (app._1 + "/*").replaceAll("//", "/")) )
println(s"\u001B[34mRack started... listening for HTTP on /0.0.0.0:${port}")
server.start
this
}
}
class RackServlet(val rack: Rack, val path: String) extends HttpServlet {
override def service(request: HttpServletRequest, response: HttpServletResponse) {
val res = Middleware.BaseRack( rack, request, response ).call(Map('base_path -> path))
val status = res._1
val headers = res._2
val body = res._3
response.setStatus(status)
headers.foreach( (h) => response.addHeader(h._1, h._2))
if( body != null ) response.getWriter().write(body)
}
}
示例6: PluginAssetsServlet
//设置package包名称以及导入依赖的类
package gitbucket.core.servlet
import javax.servlet.http.{HttpServlet, HttpServletRequest, HttpServletResponse}
import gitbucket.core.plugin.PluginRegistry
import gitbucket.core.util.FileUtil
import org.apache.commons.io.IOUtils
class PluginAssetsServlet extends HttpServlet {
override def doGet(req: HttpServletRequest, resp: HttpServletResponse): Unit = {
val assetsMappings = PluginRegistry().getAssetsMappings
val path = req.getRequestURI.substring(req.getContextPath.length)
assetsMappings
.find { case (prefix, _, _) => path.startsWith("/plugin-assets" + prefix) }
.flatMap { case (prefix, resourcePath, classLoader) =>
val resourceName = path.substring(("/plugin-assets" + prefix).length)
Option(classLoader.getResourceAsStream(resourcePath.replaceFirst("^/", "") + resourceName))
}
.map { in =>
try {
val bytes = IOUtils.toByteArray(in)
resp.setContentLength(bytes.length)
resp.setContentType(FileUtil.getContentType(path, bytes))
resp.setHeader("Cache-Control", "max-age=3600")
resp.getOutputStream.write(bytes)
} finally {
in.close()
}
}
.getOrElse {
resp.setStatus(404)
}
}
}
示例7: NativeBinaryProvider
//设置package包名称以及导入依赖的类
package ru.gonative
import java.io._
import javax.servlet.http.{HttpServlet, HttpServletRequest, HttpServletResponse}
class NativeBinaryProvider extends HttpServlet {
override def doGet(req: HttpServletRequest, resp: HttpServletResponse): Unit = {
resp.setContentType("plain/text")
resp.setHeader("Content-Disposition", """attachment; filename="native-binary"""")
val userAgent = Option(req.getHeader("User-Agent"))
if (userAgent.forall(_.toLowerCase.contains("linux")))
copy(new FileInputStream("native/build/out/native-linux-amd64"), resp.getOutputStream)
else if (userAgent.forall(_.toLowerCase.contains("windows")))
copy(new FileInputStream("native/build/out/native-windows-amd64.exe"), resp.getOutputStream)
}
def copy(in: InputStream, out: OutputStream): Unit = try {
val buffer = new Array[Byte](8096)
def copy(): Unit = {
val read = in.read(buffer)
if (read != -1) {
out.write(buffer, 0, read)
copy()
}
}
copy()
} finally in.close()
}
示例8: resolveFileMimeType
//设置package包名称以及导入依赖的类
package io.udash.rpc.utils
import java.io.File
import java.nio.file.Files
import javax.servlet.http.{HttpServlet, HttpServletRequest, HttpServletResponse}
protected def resolveFileMimeType(file: File): String =
Option(getServletContext.getMimeType(file.getAbsolutePath)).getOrElse("application/octet-stream")
override def doGet(request: HttpServletRequest, response: HttpServletResponse): Unit = {
val file = resolveFile(request)
if (!file.exists()) response.sendError(404, "File not found!")
else {
// MIME type
response.setContentType(resolveFileMimeType(file))
// content length
response.setContentLengthLong(file.length)
// file name
response.setHeader("Content-Disposition", s"""attachment; filename="${presentedFileName(file.getName)}"""")
val outStream = response.getOutputStream
Files.copy(file.toPath, outStream)
outStream.close()
}
}
}
示例9: handleFile
//设置package包名称以及导入依赖的类
package io.udash.rpc.utils
import java.io.InputStream
import java.nio.file.Paths
import javax.servlet.http.{HttpServlet, HttpServletRequest, HttpServletResponse}
protected def handleFile(name: String, content: InputStream): Unit
override protected def doPost(request: HttpServletRequest, response: HttpServletResponse): Unit = {
import scala.collection.JavaConverters._
request.getParts.asScala
.filter(part => fileFields.contains(part.getName.stripSuffix("[]")))
.foreach(filePart => {
val fileName = Paths.get(filePart.getSubmittedFileName).getFileName.toString
val fileContent = filePart.getInputStream
handleFile(fileName, fileContent)
fileContent.close()
})
}
}
示例10: handleServerException
//设置package包名称以及导入依赖的类
package io.udash.rest.server
import javax.servlet.http.{HttpServlet, HttpServletRequest, HttpServletResponse}
import com.avsystem.commons.SharedExtensions._
import io.udash.rest._
import scala.concurrent.{ExecutionContext, Future}
import scala.util.{Failure, Success, Try}
protected def handleServerException(req: HttpServletRequest, resp: HttpServletResponse)(ex: Throwable): Unit =
resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, ex.toString)
private def handle(req: HttpServletRequest, resp: HttpServletResponse, httpMethod: Class[_ <: RESTMethod]): Unit = {
val asyncCtx = req.startAsync()
Future.fromTry(Try(createEndpoint(req)))
.flatMapNow(_.handleRestCall(req, httpMethod))
.onComplete {
case Success(response) =>
resp.getOutputStream.print(response)
resp.getOutputStream.flush()
resp.setStatus(HttpServletResponse.SC_OK)
asyncCtx.complete()
case Failure(ex: ExposesREST.NotFound) =>
resp.sendError(HttpServletResponse.SC_NOT_FOUND, ex.getMessage)
asyncCtx.complete()
case Failure(ex: ExposesREST.Unauthorized) =>
resp.sendError(HttpServletResponse.SC_UNAUTHORIZED, ex.getMessage)
asyncCtx.complete()
case Failure(ex: ExposesREST.MethodNotAllowed) =>
resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, ex.getMessage)
asyncCtx.complete()
case Failure(ex: ExposesREST.BadRequestException) =>
resp.sendError(HttpServletResponse.SC_BAD_REQUEST, ex.getMessage)
asyncCtx.complete()
case Failure(ex) =>
handleServerException(req, resp)(ex)
asyncCtx.complete()
}
}
}
class DefaultRestServlet(exposedInterfaces: ExposesREST[_])(implicit ec: ExecutionContext) extends RestServlet {
override protected def createEndpoint(req: HttpServletRequest): ExposesREST[_] =
exposedInterfaces
}