Develop Spring MVC Applications (2)

xiaoxiao2021-03-06  167

2, development and configuration applications

(13) Improve index.jsp

l We want to use JSTL in JSP, so import lib / j2ee / jstl.jar and lib / jakarta-taglibs / standard.jar into the SpringApp / Web-INF / LIB directory

l Create include.jsp contains references to Taglibs so that other JSPs contain quotes:

<% @ Page session = "false"%>

<% @ taglib prefix = "c" uri = "http://java.sun.com/jstl/core"%>

<% @ taglib prefix = "FMT" URI = "http://java.sun.com/jstl/fmt"%>

l For these files that do not allow users to directly access them directly, you can put files in / web-infirectory, where you put files in / web-inf / jsp directory

l Modify index.jsp, use the redirection to the controller

<% @ include file = "/ web-inf / jsp / incrude.jsp"%>

<% - Redirected Because We can't set the welcome page to a Virtual URL. -%>

(14) Improve view and controller

L, like include.jsp, hello.jsp also cannot access directly, so move hello.jsp into the / web-inf / jsp directory

l In Hello.jsp, we increase the output of the current date and event, which is obtained from the MODEL mentioned later.

<% @ include file = "/ web-inf / jsp / incrude.jsp"%>

Hello :: Spring Application </ Title> </ hEAD></p> <p><body></p> <p><H1> Hello - Spring Application </ h1></p> <p><p> Greetings, IT is now <c: out value = "$ {now}" /></p> <p></ p></p> <p></ body></p> <p></ html></p> <p>l Since the path change of Hello.jsp, it is necessary to modify the controller to adjust the path to the output view and provide Model data.</p> <p>Import Org.SpringFramework.Web.Servlet.mvc.controller;</p> <p>Import org.springframework.Web.Servlet.ModelandView;</p> <p>Import javax.servlet.servletException;</p> <p>Import javax.servlet.http.httpservletRequest;</p> <p>Import javax.servlet.http.httpservletResponse;</p> <p>Import java.io.ioException;</p> <p>Import org.apache.commons.logging.log;</p> <p>Import org.apache.commons.logging.logfactory; Public Class Springappcontroller Implements Controller {</p> <p>/ ** Logger for this class and subclasses * /</p> <p>Protected final log logger = logfactory.getlog (getclass ());</p> <p>Public ModlandView HandleRequest (httpservletRequest Request, HttpservletResponse Response)</p> <p>Throws servletexception, ioException {</p> <p>String now = (New java.util.date ()). TOSTRING ();</p> <p>Logger.info ("Returning Hello View with" Now);</p> <p>Return New ModelandView ("/ Web-INF / JSP / HELLO.JSP", "now", now</p> <p>}</p> <p>}</p> <p>l Enter http: // localhost: 8888 / SPRINGAPP in your browser, you will show the welcome page with the current date and time</p> <p>(15) Reduce the coupling of views and controllers</p> <p>l The above example is dependent on the view and controller. Our idea is to use logical names to map views. This allows you to modify the controller when changing the view (such as name, path).</p> <p>l Simple mapping is to set the prefix and suffix using the InternalResourceViewResolver</p> <p>l Modify springapp-servlet.xml to add ViewResolver entry</p> <p><? XML Version = "1.0" encoding = "UTF-8"?></p> <p><! Doctype beans public "- // Spring // DTD bean // en" "http://www.springframework.org/dtd/spring-beans.dtd"></p> <p><! -</p> <p>- Application Context Definition for "SpringApp" DispatcherServlet.</p> <p>-></p> <p><beans></p> <p><bean id = "SpringAppController" class = "springappcontroller" /></p> <p><bean id = "urlmapping" class = "org.springframework.web.servlet.Handler.SIMPLEURLHANDLERMAPPING"></p> <p><Property Name = "MAppings"></p> <p><PrOPS></p> <p><prop key = "/ hello.htm> SpringAppController </ prop></p> <p></ prOPS></p> <p></ Property></p> <p></ bean></p> <p><bean id = "ViewResolver" class = "org.springframework.web.servlet.view.internalResourceViewResolver"></p> <p><Property Name = "ViewClass"> <value> org.springframework.web.servlet.view.jstlview </ value> </ property> <property name = "prefix"> <value> / web-inf / jsp / </ Value> </ property></p> <p><Property Name = "SUFFIX"> <value> .jsp </ value> </ property></p> <p></ bean></p> <p></ beans></p> <p>l You can remove the prefix and suffix of the view in the controller.</p> <p>Import Org.SpringFramework.Web.Servlet.mvc.controller;</p> <p>Import org.springframework.Web.Servlet.ModelandView;</p> <p>Import javax.servlet.servletException;</p> <p>Import javax.servlet.http.httpservletRequest;</p> <p>Import javax.servlet.http.httpservletResponse;</p> <p>Import java.io.ioException;</p> <p>Import org.apache.commons.logging.log;</p> <p>Import org.apache.commons.logging.logfactory;</p> <p>Public Class SpringAppController Implements Controller {</p> <p>/ ** Logger for this class and subclasses * /</p> <p>Protected final log logger = logfactory.getlog (getclass ());</p> <p>Public ModlandView HandleRequest (httpservletRequest Request, HttpservletResponse Response)</p> <p>Throws servletexception, ioException {</p> <p>String now = (New java.util.date ()). TOSTRING ();</p> <p>Logger.info ("Returning Hello View with" Now);</p> <p>Return New ModelandView ("Hello", "NOW", NOW;</p> <p>}</p> <p>}</p> <p>(16) Add business logic</p> <p>l Product class provides business data, the ProductManager class is used to manage Product (ie business data); they are all implemented as Javabean</p> <p>Package bus;</p> <p>Import java.io.serializable;</p> <p>Public Class Product Implements Serializable {</p> <p>Private string description;</p> <p>PRIVATE DOUBLE PRICE;</p> <p>Public void setdescription (String s) {</p> <p>Description = S;</p> <p>}</p> <p>Public string getdescription () {</p> <p>Return description;</p> <p>}</p> <p>Public void setprice (double d) {</p> <p>Price = d;</p> <p>}</p> <p>Public double getprice () {</p> <p>Return Price;</p> <p>}</p> <p>}</p> <p>Package bus;</p> <p>Import java.io.serializable; import java.util.list;</p> <p>Public Class ProductManager IMPLEments Serializable {</p> <p>PRIVATE LIST PRODUCTS;</p> <p>Public void setProducts (List P) {</p> <p>Products = P;</p> <p>}</p> <p>Public List getProducts () {</p> <p>Return Products;</p> <p>}</p> <p>}</p> <p>l In order to separate web representations and business logic, these classes and controllers are placed in different packages, BUS and web; pay attention to move SpringAppController to the web package</p> <p>l Modify SpringAppController to save the product of the ProductManager to deliver business data to the view; because multiple objects need to be transmitted, use the MAP structure</p> <p>Package web;</p> <p>Import Org.SpringFramework.Web.Servlet.mvc.controller;</p> <p>Import org.springframework.Web.Servlet.ModelandView;</p> <p>Import javax.servlet.servletException;</p> <p>Import javax.servlet.http.httpservletRequest;</p> <p>Import javax.servlet.http.httpservletResponse;</p> <p>Import java.io.ioException;</p> <p>Import java.util.map;</p> <p>Import java.util.hashmap;</p> <p>Import org.apache.commons.logging.log;</p> <p>Import org.apache.commons.logging.logfactory;</p> <p>Import Bus.ProductManager;</p> <p>Public Class SpringAppController Implements Controller {</p> <p>/ ** Logger for this class and subclasses * /</p> <p>Protected final log logger = logfactory.getlog (getclass ());</p> <p>Private productManager product;</p> <p>Public ModlandView HandleRequest (httpservletRequest Request, HttpservletResponse Response)</p> <p>Throws servletexception, ioException {</p> <p>String now = (New java.util.date ()). TOSTRING ();</p> <p>Logger.info ("Returning Hello View with" Now);</p> <p>Map mymodel = new hashmap ();</p> <p>MyModel.Put ("now", now);</p> <p>MyModel.put ("Products", getProductManager (). getProducts ());</p> <p>Return New ModelandView ("Hello", "Model", MyModel;</p> <p>}</p> <p>Public Void SetProductManager (ProductManager PM) {</p> <p>PRODMAN = PM;</p> <p>}</p> <p>Public productManager getProductManager () {</p> <p>Return Prodman</p> <p>}</p> <p>}</p> <p>(17) Modify the view to display business data, and provide message beam support</p> <p>l Use <c: foreach> to display business data, use <FMT: Message> to get the message from the message file described later, "% @ include file =" / web-inf / jsp / include.jsp "%></p> <p><html></p> <p><head> <title> <fmt: message key = "title" /> </ title> </ head></p> <p><body></p> <p><h1> <fmt: message key = "Heading" /> </ h1></p> <p><p> <fmt: message key = "greeting" /> <c: out value = "$ {model.now}" /></p> <p></ p></p> <p><H3> Products </ h3></p> <p><c: foreach items = "$ {model.products}" var = "prod"></p> <p><C: out value = "$ {prod.description}" /> <i> $ <c: out value = "$ {prod.price}" /> </ i> <br> <br></p> <p></ c: foreach></p> <p></ body></p> <p></ html></p> <p>(18) Increase test data to automatically assemble business objects</p> <p>l The above example has not added a function code from the database to load the business object, so use Spring's bean and application context functionality to instantiate, this needs to add some Bean entry in SpringApp-servlet.xml</p> <p>l Add Messagesource Specify Message Resources Save File Messages.Properties</p> <p><? XML Version = "1.0" encoding = "UTF-8"?></p> <p><! Doctype beans public "- // Spring // DTD bean // en" "http://www.springframework.org/dtd/spring-beans.dtd"></p> <p><! -</p> <p>- Application Context Definition for "SpringApp" DispatcherServlet.</p> <p>-></p> <p><beans></p> <p><bean id = "SpringAppController" class = "Web.SpringAppController"></p> <p><property name = "productManager"></p> <p><ref bean = "prodman" /></p> <p></ Property></p> <p></ bean></p> <p><bean id = "prodman" class = "bus.productmanager"></p> <p><Property Name = "Products"></p> <p><List></p> <p><ref bean = "product1" /></p> <p><ref bean = "product2" /></p> <p><ref bean = "product3" /> </ list></p> <p></ Property></p> <p></ bean></p> <p><bean id = "product1" class = "bus.product"></p> <p><Property Name = "Description"> <value> Lamp </ value> </ property></p> <p><proty name = "price"> <value> 5.75 </ value> </ property></p> <p></ bean></p> <p><bean id = "product2" class = "bus.product"></p> <p><Property Name = "Description"> <value> Table </ value> </ property></p> <p><Property Name = "Price"> <value> 75.25 </ value> </ printty></p> <p></ bean></p> <p><bean id = "product3" class = "bus.product"></p> <p><Property Name = "Description"> <value> chair </ value> </ property></p> <p><Property Name = "Price"> <value> 22.79 </ value> </ property></p> <p></ bean></p> <p><bean id = "messagesource" class = "org.springframework.context.support.resourceBundleMessages"></p> <p><Property Name = "BaseName"> <value> message </ value> </ property></p> <p></ bean></p> <p><bean id = "urlmapping" class = "org.springframework.web.servlet.Handler.SIMPLEURLHANDLERMAPPING"></p> <p><Property Name = "MAppings"></p> <p><PrOPS></p> <p><prop key = "/ hello.htm> SpringAppController </ prop></p> <p></ prOPS></p> <p></ Property></p> <p></ bean></p> <p><bean id = "ViewResolver" class = "org.springframework.web.servlet.view.internalResourceViewResolver"></p> <p><property name = "viewclass"> <value> org.springframework.web.servlet.view.jstlview </ value> </ property></p> <p><Property Name = "prefix"> <value> / web-inf / jsp / </ value> </ proty> <property name = "suffix"> <value> .jsp </ value> </ property></p> <p></ bean></p> <p></ beans></p> <p>(19) Add a message bundle</p> <p>l Create a Messages.properties file in the SpringApp / Web-INF / CLASSES directory, pay attention to the consistency of the Key value and <fmt: message></p> <p>Title = SpringApp</p> <p>Heading = hello :: SpringApp</p> <p>Greeting = Greetings, IT IS NOW</p> <p>l Red deploy, enter http: // localhost: 8888 / SpringApp in your browser, the page with current date and time and business data will be displayed</p></div><div class="text-center mt-3 text-grey"> 转载请注明原文地址:https://www.9cbs.com/read-127952.html</div><div class="plugin d-flex justify-content-center mt-3"></div><hr><div class="row"><div class="col-lg-12 text-muted mt-2"><i class="icon-tags mr-2"></i><span class="badge border border-secondary mr-2"><h2 class="h6 mb-0 small"><a class="text-secondary" href="tag-2.html">9cbs</a></h2></span></div></div></div></div><div class="card card-postlist border-white shadow"><div class="card-body"><div class="card-title"><div class="d-flex justify-content-between"><div><b>New Post</b>(<span class="posts">0</span>) </div><div></div></div></div><ul class="postlist list-unstyled"> </ul></div></div><div class="d-none threadlist"><input type="checkbox" name="modtid" value="127952" checked /></div></div></div></div></div><footer class="text-muted small bg-dark py-4 mt-3" id="footer"><div class="container"><div class="row"><div class="col">CopyRight © 2020 All Rights Reserved </div><div class="col text-right">Processed: <b>0.041</b>, SQL: <b>9</b></div></div></div></footer><script src="./lang/en-us/lang.js?2.2.0"></script><script src="view/js/jquery.min.js?2.2.0"></script><script src="view/js/popper.min.js?2.2.0"></script><script src="view/js/bootstrap.min.js?2.2.0"></script><script src="view/js/xiuno.js?2.2.0"></script><script src="view/js/bootstrap-plugin.js?2.2.0"></script><script src="view/js/async.min.js?2.2.0"></script><script src="view/js/form.js?2.2.0"></script><script> var debug = DEBUG = 0; var url_rewrite_on = 1; var url_path = './'; var forumarr = {"1":"Tech"}; var fid = 1; var uid = 0; var gid = 0; xn.options.water_image_url = 'view/img/water-small.png'; </script><script src="view/js/wellcms.js?2.2.0"></script><a class="scroll-to-top rounded" href="javascript:void(0);"><i class="icon-angle-up"></i></a><a class="scroll-to-bottom rounded" href="javascript:void(0);" style="display: inline;"><i class="icon-angle-down"></i></a></body></html><script> var forum_url = 'list-1.html'; var safe_token = '0K2CoGaY4C_2FtxaF1OLiAuQPSUOpruU2MERG1GUAxx0NVwh32BTRjqO1B3QkGtFPtkJDbPdMc4nn0nHAMoQOfag_3D_3D'; var body = $('body'); body.on('submit', '#form', function() { var jthis = $(this); var jsubmit = jthis.find('#submit'); jthis.reset(); jsubmit.button('loading'); var postdata = jthis.serializeObject(); $.xpost(jthis.attr('action'), postdata, function(code, message) { if(code == 0) { location.reload(); } else { $.alert(message); jsubmit.button('reset'); } }); return false; }); function resize_image() { var jmessagelist = $('div.message'); var first_width = jmessagelist.width(); jmessagelist.each(function() { var jdiv = $(this); var maxwidth = jdiv.attr('isfirst') ? first_width : jdiv.width(); var jmessage_width = Math.min(jdiv.width(), maxwidth); jdiv.find('img, embed, iframe, video').each(function() { var jimg = $(this); var img_width = this.org_width; var img_height = this.org_height; if(!img_width) { var img_width = jimg.attr('width'); var img_height = jimg.attr('height'); this.org_width = img_width; this.org_height = img_height; } if(img_width > jmessage_width) { if(this.tagName == 'IMG') { jimg.width(jmessage_width); jimg.css('height', 'auto'); jimg.css('cursor', 'pointer'); jimg.on('click', function() { }); } else { jimg.width(jmessage_width); var height = (img_height / img_width) * jimg.width(); jimg.height(height); } } }); }); } function resize_table() { $('div.message').each(function() { var jdiv = $(this); jdiv.find('table').addClass('table').wrap('<div class="table-responsive"></div>'); }); } $(function() { resize_image(); resize_table(); $(window).on('resize', resize_image); }); var jmessage = $('#message'); jmessage.on('focus', function() {if(jmessage.t) { clearTimeout(jmessage.t); jmessage.t = null; } jmessage.css('height', '6rem'); }); jmessage.on('blur', function() {jmessage.t = setTimeout(function() { jmessage.css('height', '2.5rem');}, 1000); }); $('#nav li[data-active="fid-1"]').addClass('active'); </script>