Spring Boot 入门实战:长链接转短链接
Spring Boot是由Pivotal团队提供的全新框架,其设计目的是用来简化新Spring应用的初始搭建以及开发过程。该框架使用了特定的方式来进行配置,从而使开发人员不再需要定义样板化的配置。通过这种方式,Boot致力于在蓬勃发展的快速应用开发领域(rapid application development)成为领导者。(官方网址:http://projects.spring.io/spring-boot/)
为了能快速了解Spring Boot,做了一个demo,是把用户输入的长链接转为短链接,用户访问短链接可以重定向到长链接的功能!
开发工具:IntelliJ IDEA
开发环境:jdk1.8
1 package demo; 2 3 import org.springframework.boot.SpringApplication; 4 import org.springframework.boot.autoconfigure.SpringBootApplication; 5 import org.springframework.stereotype.Controller; 6 import org.springframework.web.bind.annotation.PathVariable; 7 import org.springframework.web.bind.annotation.RequestMapping; 8 import org.springframework.web.bind.annotation.RequestMethod; 9 import org.springframework.web.bind.annotation.ResponseBody; 10 11 import javax.servlet.http.HttpServletRequest; 12 import java.util.HashMap; 13 import java.util.Map; 14 import java.util.Random; 15 16 @Controller 17 @SpringBootApplication 18 public class Application { 19 private Map<String,String> urlMap = new HashMap<String,String>(); 20 @RequestMapping("/") 21 public String index() { 22 return "/view/index.html"; 23 } 24 @RequestMapping(value="/getShortURL",method= RequestMethod.POST) 25 @ResponseBody 26 public String getShortURL(String url) { 27 String runURL = addShortURL(url); 28 return "http://localhost:8080/url/"+runURL; 29 } 30 @RequestMapping(value="/url/{shortUrl}",method= RequestMethod.GET) 31 public String getRealURL(@PathVariable String shortUrl,HttpServletRequest request) { 32 String currentURL = request.getRequestURL().toString(); 33 34 return "redirect:"+urlMap.get(shortUrl); 35 } 36 37 private synchronized String addShortURL(String url){ 38 String rtnURL = getRandomStr(); 39 if (urlMap.get(rtnURL)==null) { 40 urlMap.put(rtnURL,url); 41 return rtnURL; 42 }else{ 43 return addShortURL(url); 44 } 45 } 46 47 private String getRandomStr(){ 48 //定义一个空字符串 49 String base = "abcdefghijklmnopqrstuvwxyz0123456789"; 50 Random random = new Random(); 51 StringBuffer sb = new StringBuffer(); 52 for (int i = 0; i < 6; i++) { 53 int number = random.nextInt(base.length()); 54 sb.append(base.charAt(number)); 55 } 56 String rtnURL = sb.toString(); 57 return rtnURL; 58 } 59 60 public static void main(String[] args){ 61 SpringApplication.run(Application.class, args); 62 } 63 64 }
页面代码很简单,一个输入框,让用户输入原本链接,点击“Submit”!
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>Title</title> 6 </head> 7 <body> 8 <form action="/getShortURL" method="post"> 9 <p>URL: <input type="text" name="url" /></p> 10 <p><input type="submit" value="Submit" /> <input type="reset" value="Reset" /></p> 11 </form> 12 </body> 13 </html>
Spring Boot内嵌Apache服务器,直接右键“Run”,一个Web服务就启动了。