In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
Today, I will talk to you about the use of SpringMVC in Java. Many people may not know much about it. In order to make you understand better, the editor has summarized the following for you. I hope you can get something according to this article.
Catalogue
Design Restful interface
SpringMVC
Project Integration SpringMVC
Using SpringMVC to implement Restful Interface
Logical interaction
Identity authentication
Timing panel
Summary
Design Restful interface
Design the front-end interaction process according to the requirements.
Three posts:
Products: interpret users' needs and work out requirements documents
Front end: page display on different platforms
Backend: store, display, and process data
Front-end page flow:
Details page process logic:
The standard system time is obtained from the server.
Restful: an elegant URI representation, state and state transition of resources.
Restful specification:
GET query operation
POST add / modify operation (non-idempotent)
PUT modification operation (idempotent, not too strictly differentiated)
DELETE delete operation
URL Design:
/ Module / Resource / {Mark} / Collection /... / user/ {uid} / friends-> Friends list / user/ {uid} / followers-> follower list
URL Design of second-kill API
GET / seckill/list seconds kill list GET / seckill/ {id} / detail details page GET / seckill/time/now system time POST / seckill/ {id} / exposer exposure seconds kill POST / seckill/ {id} / {md5} / execution execution seconds kill
The next step is how to implement these URL interfaces.
SpringMVC
theory
Adapter pattern (Adapter Pattern), which transforms the interface of one class into another interface expected by the client. Adapter pattern enables two classes that cannot work together because of interface mismatch (or incompatibility).
SpringMVC's handler (Controller,HttpRequestHandler,Servlet, etc.) can be implemented in many ways, such as inheriting Controller, based on annotation controller, and HttpRequestHandler. Because the implementation is different, the invocation mode is uncertain.
There are three ways to see the HandlerAdapter interface:
/ / determine whether the adapter supports the HandlerMethodboolean supports (Object handler); / / it is used to execute the controller processing function to get the ModelAndView. The handler method is executed according to the adapter invocation rules. ModelAndView handle (HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception;long getLastModified (HttpServletRequest request, Object handler)
The query process is shown in the figure above. When a user accesses a request, it is first forwarded by DispatcherServlet. Use HandlerMapping to get the desired HandlerExecutionChain (including handler and a bunch of interceptors). Then use handler to get the HandlerAdapter, traverse all the injected HandlerAdapter, and in turn use the supports method to find the adaptor subclass that fits this handler. Finally, the adapter subclass obtained uses the handle method to call the controller function and returns ModelAndView.
Annotation mapping skills
Support for standard URL
? And characters such as * and * *, such as / usr/*/creation will match / usr/AAA/creation and / usr/BBB/creation, etc. / usr/**/creation matches URL such as / usr/creation and / usr/AAA/BBB/creation. URL with {xxx} placeholder.
For example, / usr/ {userid} matches / usr/123, / usr/abc and other URL.
Processing of request method details
Request parameter binding
Request mode restriction
Request forwarding and redirection
Data model assignment
Return json data
Cookie access
Return json data
Cookie access:
Project Integration SpringMVC
The configuration files that need to be loaded to configure springmvc under web.xml:
Seckill-dispatcher org.springframework.web.servlet.DispatcherServlet contextConfigLocation classpath:spring/spring-*.xml seckill-dispatcher /
Add the spring-web.xml file to the spring folder under the resources folder:
Using SpringMVC to implement Restful Interface
Create a new file:
The first is SeckillResult.java, which saves the returned results of controller and makes a package.
/ / return types of all ajax requests, encapsulating the json result public class SeckillResult {private boolean success; / / whether the private T data; was executed successfully / / carrying data private String error; / / error message / / getter setter contructor}
In Seckillcontroller.java, we implemented several URL that we defined earlier:
GET / seckill/list seconds kill list GET / seckill/ {id} / detail details page GET / seckill/time/now system time POST / seckill/ {id} / exposer exposure seconds kill POST / seckill/ {id} / {md5} / execution execution seconds kill
The specific code is as follows:
@ Controller / / @ Service @ Component into the spring container @ RequestMapping ("/ seckill") / / url: module / resource / {id} / subdivision public class SeckillController {private final Logger logger = LoggerFactory.getLogger (this.getClass ()); @ Autowired private SecKillService secKillService; @ RequestMapping (value = "/ list", method = RequestMethod.GET) public String list (Model model) {/ / list.jsp + model = modelandview List list = secKillService.getSecKillList () Model.addAttribute ("list", list); return "list";} @ RequestMapping (value = "/ {seckillId} / detail", method = RequestMethod.GET) public String detail (@ PathVariable ("seckillId") Long seckillId, Model model) {if (seckillId = = null) {/ / 0. If it doesn't exist, redirect to list / / 1. Redirect the access server twice / / 2. Redirection can be redefined to any resource path. / / 3. Redirection results in a new request that cannot share request domain information with the request parameter return "redrict:/seckill/list";} SecKill secKill = secKillService.getById (seckillId); if (secKill = = null) {/ / 0. To show the effect, use forward / / 1. Forwarding only accesses the server once. / / 2. Forwarding can only be forwarded to your own web application / / 3. Forwarding is equivalent to a server jump, equivalent to a method call, and turns to the target file in the process of executing the current file. / / two files (current file and target file) belong to the same request, and the front and back pages share a request. You can pass some data or session information return "forward:/seckill/list" through this. } model.addAttribute ("seckill", secKill); return "detail";} / / ajax json @ RequestMapping (value = "/ {seckillId} / exposer", method = RequestMethod.POST, produces = {"application/json;charset=UTF8"}) @ ResponseBody public SeckillResult exposer (Long seckillId) {SeckillResult result; try {Exposer exposer = secKillService.exportSecKillUrl (seckillId) Result = new SeckillResult (true,exposer);} catch (Exception e) {logger.error (e.getMessage (), e); result = new SeckillResult (false,e.getMessage ());} return result;} @ RequestMapping (value = "/ {seckillId} / {md5} / execution", method = RequestMethod.POST, produces = {"application/json Charset=UTF8 "}) public SeckillResult execute (@ PathVariable (" seckillId ") Long seckillId, / / required = false means that the cookie logic is handled by our program. Springmvc do not report an error @ CookieValue (value =" killPhone ", required = false) Long userPhone, @ PathVariable (" md5 ") String md5) {if (userPhone = = null) {return new SeckillResult (false," unregistered ") } SeckillResult result; try {SeckillExecution execution = secKillService.executeSeckill (seckillId, userPhone, md5); result = new SeckillResult (true, execution); return result;} catch (SeckillCloseException e) {/ / second close SeckillExecution execution = new SeckillExecution (seckillId, SecKillStatEnum.END); return new SeckillResult (false,execution) } catch (RepeatKillException e) {/ / repeat second kill SeckillExecution execution = new SeckillExecution (seckillId, SecKillStatEnum.REPEAT_KILL); return new SeckillResult (false,execution);} catch (Exception e) {/ / not repeat second kill or end second kill, internal error logger.error (e.getMessage (), e) is returned SeckillExecution execution = new SeckillExecution (seckillId, SecKillStatEnum.INNER_ERROR); return new SeckillResult (false,execution);} @ RequestMapping (value = "/ time/now", method = RequestMethod.GET) @ ResponseBody public SeckillResult time () {Date now = new Date (); return new SeckillResult (true,now.getTime ());}}
Page
Here, modify the database to test our code at the right time.
Click and jump to the details page.
The details page involves a lot of interactive logic, such as cookie, success and failure of second kill, and so on. Put it in the logical interaction section.
A problem with the jackson version was found at run time, and the pom.xml was modified to:
Com.fasterxml.jackson.core jackson-databind 2.10.2
The list.jsp code is:
Bootstrap template second kill list name Inventory start time end time creation time detail page ${sk.name} ${sk.number} Link
Logical interactive authentication
There is no mobile phone number in cookie to pop-up window. Incorrect mobile phone number (11 digits) should indicate an error:
After selecting a submission, you should be able to see it in the cookie:
So far detail.jsp:
Second kill details page ${seckill.name} Second kill phone call: Submit $(function () {seckill.detail.init ({seckillId: ${seckill.seckillId}) StartTime: ${seckill.startTime.time}, / / converted to milliseconds Easy to compare endTime: ${seckill.endTime.time},}) })
Our logic is mainly written in another js file:
Seckill.js
/ / to store the main interaction logic js// javascript modular var seckill= URL URL: {}, / / to verify the mobile phone number validatePhone: function (phone) {if (phone & & phone.length==11 & &! isNaN (phone)) {return true;} else {return false }, / / details page second kill logic detail: {/ / details page initialization init: function (params) {/ / Mobile phone authentication and login, timed interaction / / Plan interaction flow / / find mobile phone number var killPhone = $.cookie ('killPhone') in cookie Var startTime = params ['startTime']; var endTime = params [' endTime']; var seckillId = params ['seckillId']; / / verify the mobile phone number if (! seckill.validatePhone (killPhone)) {/ / bind the mobile phone number, and get div id var killPhoneModal = $(' # killPhoneModal') for entering the mobile phone number in the pop-up window KillPhoneModal.modal ({show: true, / / Show pop-up layer backdrop: 'static',// forbidden position to close keyboard: false, / / close keyboard event}) $('# killPhoneBtn') .click (function () {var inputPhone = $('# killphoneKey'). Val () / / enter the format of ok and refresh the page if (seckill.validatePhone (inputPhone)) {/ / write the phone to cookie $.cookie ('killPhone',inputPhone, {expires:7,path:'/seckill'}); _ window.location.reload () } else {/ / A better way is to write the string into the dictionary and then use $('# killphoneMessage'). Hide (). Html ('incorrect mobile number'). Show (500);}}) } / / logged in} timing panel
After the login is complete, process the timing operation:
/ / logged in / / timed interaction $.get (seckill.URL.now (), {}, function (result) {if (result & & result ['success']) {var nowTime = result [' data']; / / written to the function to handle seckill.countdown (seckillId,nowTime,startTime,endTime);} else {console.log ('result:' + result);}})
In the countdown function, there are three judgments: no start, no start, and no end.
URL: {now: function () {return'/ seckill/time/now';}}, handleSeckill: function () {/ / handle the second kill logic}, countdown: function (seckillId,nowTime,startTime,endTime) {var seckillBox = $('# seckillBox'); if (nowTime > endTime) {seckillBox.html ('second kill is over!') ;} else if (nowTime
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.