日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程语言 > java >内容正文

java

使用Java和Spring构建现代Web应用程序

發(fā)布時間:2023/12/3 java 28 豆豆
生活随笔 收集整理的這篇文章主要介紹了 使用Java和Spring构建现代Web应用程序 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

使用Spring Framework創(chuàng)建Java Web應(yīng)用程序從未如此簡單。 如果您已經(jīng)熟悉Java并且?guī)缀鯖]有創(chuàng)建Web應(yīng)用程序的經(jīng)驗,或者如果您擔(dān)心所有很酷的孩子都放棄Java取而代之的是Ruby和Node.js,那么您想讀這篇。

我的意圖是在此處提供實用指南,以快速入門并使用Java和Spring創(chuàng)建現(xiàn)代Web應(yīng)用程序。

我們將使用Java,Spring Framework(4.x),Spring Boot(v1.2.x),Spring Security,Spring Data JPA,Thymeleaf和Maven 3框架的最新版本。

為什么使用Spring框架

Spring是最流行的開源Java框架之一。

  • Spring是一個成熟但仍具有創(chuàng)新性的開源框架
  • 春天有一個非常活躍的社區(qū)
  • 彈簧重量輕–可以使用嵌入式容器從命令行運行
  • Spring,尤其是Spring Boot使您的工作效率更高–無需XML配置

春天不僅僅是一個框架……

…這是一個平臺,可讓您了解構(gòu)建Web應(yīng)用程序所需的大多數(shù)技術(shù):

  • 創(chuàng)建MVC應(yīng)用程序
  • 提供身份驗證和授權(quán)
  • 使用JDBC,Hibernate和JPA連接到RDBMS數(shù)據(jù)庫
  • 連接到NoSQL數(shù)據(jù)庫(MongoDB,Neo4J,Redis,Solr,Hadoop等)
  • 處理消息(JMS,AMQP)
  • 快取
  • 等等

是時候創(chuàng)建一些代碼了

在本教程中,我們將創(chuàng)建一個示例url-shortener應(yīng)用程序( 此處提供源代碼),盡管本文不涵蓋構(gòu)建Web應(yīng)用程序的所有方面,但希望您會找到足夠的有用信息,以便能夠開始并想了解更多。

該應(yīng)用程序由一個HTML頁面組成,它可以從任何URL創(chuàng)建一個短URL,并且您可能已經(jīng)猜到了,它還可以從該短URL重定向到原始URL。

要運行它,請在命令行中執(zhí)行以下命令(假設(shè)您已經(jīng)安裝了Maven v3 ):

$ mvn spring-boot:run

組件

YourlApplication.java

這是應(yīng)用程序的主類,用于初始化Spring上下文(包括該項目中的所有Spring組件),并在嵌入式Apache Tomcat( http://tomcat.apache.org )Web容器內(nèi)啟動Web應(yīng)用程序。

@SpringBootApplication public class YourlApplication {public static void main(String[] args) {SpringApplication.run(YourlApplication.class, args);} }

基本上,@ SpringBootApplication和SpringApplication.run()方法在這里起到了神奇的作用。

UrlController.java

@Controller public class UrlController {@Autowiredprivate IUrlStoreService urlStoreService;// ... }

遵循MVC范例,此類用作處理HTTP請求的Controller(請注意@Controller注釋)。 此類中用@RequestMapping注釋的每個方法都映射到特定的HTTP端點:

  • showForm():顯示主屏幕,用戶可以在其中輸入要縮短的網(wǎng)址 @RequestMapping(value="/", method=RequestMethod.GET) public String showForm(ShortenUrlRequest request) {return "shortener"; }
  • redirectToUrl():從縮短的網(wǎng)址重定向到原始網(wǎng)址 @RequestMapping(value = "/{id}", method = RequestMethod.GET)public void redirectToUrl(@PathVariable String id, HttpServletResponse resp) throws Exception {final String url = urlStoreService.findUrlById(id);if (url != null) {resp.addHeader("Location", url);resp.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);} else {resp.sendError(HttpServletResponse.SC_NOT_FOUND);}}
  • shortUrl():顧名思義,它將創(chuàng)建所提供網(wǎng)址的簡化版本,并將其傳遞給shorter.html進行顯示 @RequestMapping(value="/", method = RequestMethod.POST) public ModelAndView shortenUrl(HttpServletRequest httpRequest,@Valid ShortenUrlRequest request,BindingResult bindingResult) {String url = request.getUrl();if (!isUrlValid(url)) {bindingResult.addError(new ObjectError("url", "Invalid url format: " + url));}ModelAndView modelAndView = new ModelAndView("shortener");if (!bindingResult.hasErrors()) {final String id = Hashing.murmur3_32().hashString(url, StandardCharsets.UTF_8).toString();urlStoreService.storeUrl(id, url);String requestUrl = httpRequest.getRequestURL().toString();String prefix = requestUrl.substring(0, requestUrl.indexOf(httpRequest.getRequestURI(),"http://".length()));modelAndView.addObject("shortenedUrl", prefix + "/" + id);}return modelAndView; }

如您所見,@ RequestMapping批注負責(zé)將單個URL映射到Java方法。 該方法可以具有多個參數(shù):

  • @PathVariable(即id),它來自網(wǎng)址的動態(tài)部分(/ {id}),或者
  • @RequestParam,或者
  • 一個POJO(普通舊Java對象),其中字段對應(yīng)于請求參數(shù),或者
  • 如果是POST請求,則為@RequestBody;或者
  • Spring提供的其他預(yù)定義的Bean(例如HttpServletResponse)

ShortenUrlRequest.java

Spring將縮短的url請求映射到此POJO(普通的舊Java對象)中。 Spring還負責(zé)驗證請求,請參見url字段上的注釋。

public class ShortenUrlRequest {@NotNull@Size(min = 5, max = 1024)private String url;public String getUrl() {return url;}public void setUrl(String url) {this.url = url;} }

shorter.html

這是基于Thymeleaf的( http://www.thymeleaf.org/ )模板,該模板使用Twitter Bootstrap( http://getbootstrap.com/ )來呈現(xiàn)主屏幕HTML代碼。 它呈現(xiàn)UrlController類中的請求映射所提供的數(shù)據(jù)(模型)。

... <div class="jumbotron"><div class="container"><h1>Shorten your url</h1><p><div class="alert alert-success" role="alert" th:if="${shortenedUrl}"th:utext="'Link created: &lt;a href=\'' + ${shortenedUrl} + '\'&gt;' + ${shortenedUrl}+ '&lt;/a&gt;'"></div><form class="form-inline" th:action="@{/}" th:object="${shortenUrlRequest}" method="POST"><div class="alert alert-danger" role="alert" th:if="${#fields.hasErrors('*')}"th:errors="*{url}">Input is incorrect</div><div class="form-group"><input type="text" class="form-control" id="url" name="url"placeholder="http://www.example.com"th:field="*{url}" th:class="${#fields.hasErrors('url')}? fieldError"/></div><button type="submit" class="btn btn-primary">Shorten</button></form></p></div> </div> ...

InMemoryUrlStoreService.java

該應(yīng)用程序當(dāng)前僅將縮短的url持久存儲在此簡約類中實現(xiàn)的內(nèi)存持久層中。 稍后,我們可以通過實現(xiàn)IUrlStoreService接口將數(shù)據(jù)持久保存到數(shù)據(jù)庫中來改善這一點。

@Service public class InMemoryUrlStoreService implements IUrlStoreService{private Map<String, String> urlByIdMap = new ConcurrentHashMap<>();@Overridepublic String findUrlById(String id) {return urlByIdMap.get(id);}@Overridepublic void storeUrl(String id, String url) {urlByIdMap.put(id, url);} }

請注意,@ Service方法告訴Spring這是Service層中的一個bean,可以將其注入到其他bean中,例如UrlController。

結(jié)論

簡而言之就是這樣。 我們涵蓋了此Web應(yīng)用程序的所有部分。 我希望您現(xiàn)在同意,使用Java和Spring構(gòu)建Web應(yīng)用程序會很有趣。 不再需要樣板代碼和XML配置,Spring的最新版本將為我們處理所有這些工作。

如果您想了解有關(guān)Spring框架和Spring Boot的更多信息,請不要忘了訂閱我的新聞通訊以獲取有關(guān)Spring的最新更新。 如果您有任何疑問或建議,請隨時在下面發(fā)表評論。

翻譯自: https://www.javacodegeeks.com/2015/08/building-modern-web-applications-using-java-and-spring.html

總結(jié)

以上是生活随笔為你收集整理的使用Java和Spring构建现代Web应用程序的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。