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

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 前端技术 > javascript >内容正文

javascript

jstl视图_使用JSTL视图探索Spring Controller

發布時間:2023/12/3 javascript 33 豆豆
生活随笔 收集整理的這篇文章主要介紹了 jstl视图_使用JSTL视图探索Spring Controller 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

jstl視圖

讓我們通過對Spring MVC的Controller開發的更多探索來改進我們以前的Spring JDBC應用程序 。 我將展示另一種編寫新的Controller的練習,該Controller處理HTML表單并在JSP視圖頁面中使用JSTL標簽。

要在Spring MVC應用程序中啟用JSTL,您需要將以下內容添加到WebAppConfig配置類中。 讓我們將其WebApp.java之外,并移至src/main/java/springweb/WebAppConfig.java它自己的頂級類文件中。

package springweb;import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.view.InternalResourceViewResolver;@Configuration @EnableWebMvc @ComponentScan("springweb.controller") public class WebAppConfig {@Beanpublic InternalResourceViewResolver viewResolver() {InternalResourceViewResolver result = new InternalResourceViewResolver();result.setPrefix("/");result.setSuffix(".jsp");return result;} }

在InternalResourceViewResolver bean內,您定義在哪里可以找到其中包含JSTL標記的JSP頁面。 prefix設置器是相對于您的src/webapp位置的路徑。 如果需要,這可以讓您完全隱藏JSP文件。 例如,通過將其設置為"/WEB-INF/jsp"您可以將所有JSP文件移動并存儲到src/webapp/WEB-INF/jsp ,該文件在Web應用程序中是私有的。 suffix只是文件擴展名。 這兩個值使您可以使用JSP文件的基本名稱返回控制器內的視圖名稱,該名稱可以縮寫為“ / myform”或“ / index”等。

如果要將Tomcat用作Web容器,則還需要添加JSTL jar依賴項,因為Tomcat服務器不附帶標準標記庫! 因此,現在將其添加到pom.xml文件中。

<dependency><groupId>javax.servlet</groupId><artifactId>jstl</artifactId><version>1.2</version></dependency>

當您使用pom.xml文件時,可能需要添加Tomcat maven插件,以便在運行Web應用程序時可以在命令行中鍵入更少的內容。

<project> ...<build><plugins><plugin><groupId>org.apache.tomcat.maven</groupId><artifactId>tomcat7-maven-plugin</artifactId><version>2.1</version></plugin></plugins></build> ... </project>

這樣,您應該可以在項目的根目錄下運行mvn tomcat7:run ,而無需插件前綴。

那么JSTL給您的應用帶來了什么? 好吧,實際上很多。 它使您可以使用在編寫JSP視圖時經常使用的一些標準JSP標記。 我將通過一組Controller和視圖來演示這一點,以捕獲來自應用程序的用戶評論。 請注意,我將嘗試僅以最基本的方式向您展示如何使用Spring Controller。 Spring實際上帶有一個自定義form JSP標記,該標記使用起來功能強大得多。 我將在其他時間將其保留為另一篇文章。 今天,讓我們集中精力學習更多有關基本Spring Controller和JSTL的知識,以及有關Spring JDBC數據服務的更多知識。

我們想要捕獲用戶評論,所以讓我們添加一個數據庫表來存儲該信息。 將以下DDL添加到src/main/resources/schema.sql文件中。 同樣,這是針對上一篇文章項目設置的H2數據庫。

CREATE TABLE COMMENT (ID INT NOT NULL PRIMARY KEY AUTO_INCREMENT,TEXT VARCHAR(10240) NOT NULL,FROM_USER VARCHAR(15) NULL,FROM_USER_IP VARCHAR(15) NULL,FROM_URL VARCHAR(1024) NULL,TAG VARCHAR(1024) NULL,TS DATETIME NOT NULL );

這次,我們將編寫一個數據模型類來匹配該表。 讓我們添加src/main/java/springweb/data/Comment.java

package springweb.data;import java.util.Date;public class Comment {Long id;String text;String fromUrl;String fromUser;String fromUserIp;String tag;Date ts;public Long getId() {return id;}public void setId(Long id) {this.id = id;}public String getText() {return text;}public void setText(String text) {this.text = text;}public String getFromUrl() {return fromUrl;}public void setFromUrl(String fromUrl) {this.fromUrl = fromUrl;}public String getFromUser() {return fromUser;}public void setFromUser(String fromUser) {this.fromUser = fromUser;}public String getFromUserIp() {return fromUserIp;}public void setFromUserIp(String fromUserIp) {this.fromUserIp = fromUserIp;}public String getTag() {return tag;}public void setTag(String tag) {this.tag = tag;}public Date getTs() {return ts;}public void setTs(Date ts) {this.ts = ts;}private String getTrimedComment(int maxLen) {if (text == null)return null;if (text.length() <= maxLen)return text;return text.substring(0, maxLen);}@Overridepublic String toString() {return "Comment{" +"id=" + id +", ts=" + ts +", text='" + getTrimedComment(12) + '\'' +'}';}public static Comment create(String commentText) {Comment result = new Comment();result.setText(commentText);result.setTs(new Date());return result;} }

就像以前的文章一樣,我們將編寫一個數據服務來處理數據模型的插入和檢索。 我們添加一個新的src/main/java/springweb/data/CommentService.java文件

package springweb.data;import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.BeanPropertyRowMapper; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.RowMapper; import org.springframework.jdbc.core.simple.SimpleJdbcInsert; import org.springframework.stereotype.Repository;import javax.sql.DataSource; import java.util.HashMap; import java.util.List; import java.util.Map;@Repository public class CommentService {public static Log LOG = LogFactory.getLog(CommentService.class);private JdbcTemplate jdbcTemplate;private SimpleJdbcInsert insertActor;private RowMapper<Comment> commentBeanRowMapper = new BeanPropertyRowMapper<Comment>(Comment.class);@Autowiredpublic void setDataSource(DataSource dataSource) {this.jdbcTemplate = new JdbcTemplate(dataSource);this.insertActor = new SimpleJdbcInsert(dataSource).withTableName("COMMENT").usingGeneratedKeyColumns("ID");}public void insert(Comment comment) {LOG.info("Inserting Comment + " + comment);Map<String, Object> parameters = new HashMap<String, Object>(2);parameters.put("TEXT", comment.getText());parameters.put("FROM_USER", comment.getFromUser());parameters.put("FROM_USER_IP", comment.getFromUserIp());parameters.put("FROM_URL", comment.getFromUrl());parameters.put("TAG", comment.getTag());parameters.put("TS", comment.getTs());Number newId = insertActor.executeAndReturnKey(parameters);comment.setId(newId.longValue());LOG.info("New Comment inserted. Id=" + comment.getId());}public List<Comment> findComments() {String sql = "SELECT " +"ID as id, " +"TEXT as text, " +"TAG as tag, " +"TS as ts, " +"FROM_USER as fromUser, " +"FROM_USER_IP as fromUserIp, " +"FROM_URL as fromUrl " +"FROM COMMENT ORDER BY TS";List<Comment> result = jdbcTemplate.query(sql, commentBeanRowMapper);LOG.info("Found " + result.size() + " Comment records.");return result;} }

由于我們沒有使用任何花哨的ORM,而只是使用普通的JDBC,因此我們將不得不在數據服務中編寫SQL。 但是要感謝Spring的好東西,它使諸如SimpleJdbcInsert助手使工作變得更加輕松,該助手處理數據庫的插入和自動生成鍵的檢索等。另外還要注意,在查詢中,我們使用Spring的BeanPropertyRowMapper自動將JDBC結果集轉換為Java bean Comment對象! 簡單,直接,快速。

現在我們在src/main/java/springweb/controller/CommentController.java添加Spring控制器來處理Web請求。

package springweb.controller;import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; 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.servlet.ModelAndView; import springweb.data.Comment; import springweb.data.CommentService;import javax.servlet.http.HttpServletRequest; import java.util.List;@Controller public class CommentController {@Autowiredprivate CommentService commentService;@RequestMapping(value="/comments")public ModelAndView comments() {List<Comment> comments = commentService.findComments();ModelAndView result = new ModelAndView("/comments");result.addObject("comments", comments);return result;}@RequestMapping(value="/comment")public String comment() {return "comment";}@RequestMapping(value="/comment", method = RequestMethod.POST)public ModelAndView postComment(HttpServletRequest req, @RequestParam String commentText) {String fromUrl = req.getRequestURI();String user = req.getRemoteUser();String userIp = req.getRemoteAddr();Comment comment = Comment.create(commentText);comment.setFromUserIp(userIp);comment.setFromUser(user);comment.setFromUrl(fromUrl);commentService.insert(comment);ModelAndView result = new ModelAndView("comment-posted");result.addObject("comment", comment);return result;} }

在此控制器中,我們映射/comment URL來處理HTML表單的顯示,該表單返回comment.jsp視圖。 該方法默認處理HTTP GET 。 請注意,我們在單獨的postComment()方法上重新映射了相同的/comment URL來處理HTTP POST ! 在此演示中了解Spring Controller可以處理HTTP請求的程度。 非常注意postComment()方法中聲明的參數。 Spring會根據聲明的類型自動處理HTTP請求對象并映射到您的方法! 在某些情況下,您需要借助@RequestParam之類的注釋來使其明確,但是Spring會為您解析HTTP請求和提取! 如果我們要編寫直接的Servlet代碼,則可以節省大量重復的樣板代碼。

現在讓我們看一下視圖以及如何使用JSTL。 /comments URL映射到src/main/webapp/comments.jsp視圖文件,該文件將列出所有Comment模型對象。

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <c:choose> <c:when test="${empty comments}"><p>There are no comments in system yet.</p> </c:when> <c:otherwise><table border="1"><tr><td>INDEX</td><td>TIME</td><td>FROM</td><td>COMMENT</td></tr><c:forEach items="${comments}" var="comment" varStatus="status"><tr valign="top"><td>${status.index}</td><td>${comment.ts}</td><td>${comment.fromUserIp}</td><%-- The c:out will escape html/xml characters. --%><td><pre><c:out value="${comment.text}"/></pre></td></tr></c:forEach></table> </c:otherwise> </c:choose>

JSTL上的相當標準的東西。 接下來是HTML表單,用于在src/main/webapp/comment.jsp文件中發布評論。

<form action="comment" method="POST"> <textarea name="commentText" rows="20" cols="80"></textarea> <br/> <input type="submit" value="Post"/> </form>

成功發布和處理表單后,我們只需返回src/main/webapp/comment-posted.jsp文件中的新頁面作為輸出。

<p>Your comment has been posted. Comment ID=${comment.id}</p>

如果您已正確完成這些操作,則應該可以運行mvn tomcat7:run并瀏覽http://localhost:8080/spring-web-annotation/comment以查看表單。 轉到/comments URL以驗證所有已發布的評論。

請注意,盡管我使用Spring Controller作為后端,但所有視圖都在基本的JSTL中,甚至表單也只是基本HTML元素! 我這樣做是為了讓您看到Spring Controller有多靈活。

我知道今天有很多代碼要發布到博客文章中,但是我想完整一些,并嘗試顯示帶有教程筆記的有效演示。 我選擇將其包含在文件內容中,而不是將項目下載到其他地方。 它使我的注釋和解釋更易于與代碼匹配。

到此為止,我們今天的教程將結束。 如果您覺得有幫助,請留下筆記。

參考: A程序員雜志博客上的JCG合作伙伴 Zemian Deng從JSTL視圖探索Spring Controller 。

翻譯自: https://www.javacodegeeks.com/2013/10/exploring-spring-controller-with-jstl-view.html

jstl視圖

總結

以上是生活随笔為你收集整理的jstl视图_使用JSTL视图探索Spring Controller的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。