最近Kotlin編程語言比較火,谷歌在I/O2017開發者大會上宣佈了Kotlin成為安卓開發一級語言。
前面兩篇文章 Kotlin從入門到放棄(入門篇)Kotlin編程入門之android ndk開發 分別介紹了Kotlin編程
基本語法及kotlin編寫android程序調用andorid ndk。現在來介紹Kotlin在web編程方面的入門知識。
本篇文章是在前面文章基於spring boot快速搭建Java服務器 的基礎上修改而來,代碼已經上傳到github
上,項目分別用Java 和Kotlin實現的。大家可以對比Java和Kotlin的語法區別。
Kotlin中主函數如下:
kotlin中class類型需要改成open,在kotlin中class默認為final類型,但是由於spring的CGLIB代理不能為
final類型。init為初始化代碼塊,這裡並沒有用到初始化。
Java中主函數如下:
在kotlin中Application.class的寫法是
Application::class.java
同時在kotlin中並沒有static關鍵字。
定義實體
java中定義如下:
在kotlin中定義如下:
是的,在kotlin中一行代碼就可以了。
GreetingController在java中代碼如下:
GreetingController在Kotlin中代碼如下:
在Kotlin中是沒有new關鍵字的,創建對象時不需要new 關鍵字。
private final AtomicLong counter = new AtomicLong();
對應kotlin代碼
private val counter = AtomicLong()
在kotlin常量用val聲明,var聲明變量。kotlin中編譯會自動推斷變量類型可以不指定變量類型。
kotlin中沒有static關鍵字,類似Java中static關鍵字的功能是通過引入了companion object來實現的。
但是要注意一個類中只能有一個companion object。
FileUploadController實現了文件的上傳和下載。
kotlin代碼實現如下:
package hellokotlin.controller
/**
* Created by dongxie on 2017/5/7.
*/
import org.springframework.stereotype.Controller
import org.springframework.ui.ModelMap
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RequestMethod
import org.springframework.web.bind.annotation.RequestParam
import org.springframework.web.bind.annotation.ResponseBody
import org.springframework.web.multipart.MultipartFile
import org.springframework.web.multipart.MultipartHttpServletRequest
import java.io.*
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
@Controller
class FileUploadController {
@RequestMapping("/upload")
@ResponseBody
fun handleFileUpload(@RequestParam("file") file: MultipartFile): String {
if (!file.isEmpty) {
try {
val out = BufferedOutputStream(FileOutputStream(File(file.originalFilename)))
out.write(file.bytes)
out.flush()
out.close()
} catch (e: IOException) {
e.printStackTrace()
return "upload failed" + e.message
}
return "upload success"
} else {
return "upload failed,because file is empty"
}
}
@RequestMapping(value = "/multiUpload", method = arrayOf(RequestMethod.POST))
@ResponseBody
fun handleFileUpload(request: HttpServletRequest): String {
val files = (request as MultipartHttpServletRequest)
.getFiles("file")
var file: MultipartFile?
var stream: BufferedOutputStream?
for (i in files.indices) {
file = files[i]
if (!file!!.isEmpty) {
try {
val bytes = file.bytes
stream = BufferedOutputStream(FileOutputStream(
File(file.originalFilename)))
stream.write(bytes)
stream.close()
} catch (e: Exception) {
return "You failed to upload $i => " + e.message
}
} else {
return "You failed to upload $i because the file was empty."
}
}
return "upload successful"
}
@RequestMapping(value = "/multipleSave", method = arrayOf(RequestMethod.POST))
@ResponseBody
fun multipleSave(@RequestParam("file") files: Array<MultipartFile>): String {
var stream: BufferedOutputStream? = null
for (file in files) {
if (!file.isEmpty) {
try {
val bytes = file.bytes
stream = BufferedOutputStream(FileOutputStream(
File(file.originalFilename)))
stream.write(bytes)
stream.flush()
stream.close()
} catch (e: Exception) {
stream = null
return "You failed to upload " + file.originalFilename + " => " + e.message
} finally {
if (null != stream) {
try {
stream.close()
} catch (e: IOException) {
e.printStackTrace()
}
}
}
} else {
return "You failed to upload " + file.originalFilename + " because the file was empty."
}
}
return "upload successful"
}
@RequestMapping(value = "/download", method = arrayOf(RequestMethod.GET))
fun downloadFile(res: HttpServletResponse) {
val fileName = "spring_test.jpg"
res.setHeader("content-type", "application/octet-stream")
res.contentType = "application/octet-stream"
res.setHeader("Content-Disposition", "attachment;filename=" + fileName)
val buff = ByteArray(1024)
var bis: BufferedInputStream? = null
var os: OutputStream? = null
try {
os = res.outputStream
bis = BufferedInputStream(FileInputStream(File(fileName)))
while (bis.read(buff) != -1) {
os!!.write(buff, 0, buff.size)
os.flush()
}
} catch (e: IOException) {
e.printStackTrace()
} finally {
if (null != os) {
try {
os.close()
} catch (e: IOException) {
e.printStackTrace()
}
}
if (null != bis) {
try {
bis.close()
} catch (e: IOException) {
e.printStackTrace()
}
}
}
}
@RequestMapping("/")
fun index(map: ModelMap): String {
map.addAttribute("host", "http://blog.didispace.com")
return "index"
}
}
其中handleFileUpload 為單文件上傳方法,handleFileUpload 和 multipleSave都支持多文件上傳,接收稍有不同,downloadFile為下載文件,String fileName="spring_test.jpg" spring_test.jpg為放在根目錄下載的文件。在application.properties下設置上傳文件大小限制如下:
server.port=9000 spring.http.multipart.max-file-size=10Mb spring.http.multipart.max-request-size=10Mb
server.port為服務器監聽端口可以根據自己需要設置。
kotlin中for循環和Java的還是有區別的,比較像python中的for循環。
直接運行Application.java 或者 Application.kt即可啟動web項目。
在Application.java中直接運行主函數,如下:
代表項目啟動成功。
在瀏覽器中輸入 http://127.0.0.1:9000/greeting即可訪問
不傳參數時默認值為World,加上參數name,輸入http://127.0.0.1:9000/greeting?name=john
結果如下:
在瀏覽器輸入http://127.0.0.1:9000/index.html
進入到上傳和下載頁面,上傳的文件默認上傳到項目的根目錄。
最後附上源代碼:
代碼下載地址:https://github.com/DavidJohnSmith/SpringBootMaven
相關閱讀:
如果您喜歡這篇文章可以點贊,關注,轉發!