YMP framework learning notes (iii) ------ processor, controller, interceptor

Source: Internet
Author: User

I. Processors

1. Event Processor

Add webeventhandler. Java class and inherit iwebeventhandler

public class WebEventHandler implements IWebEventHandler {public void onInitialized() {}public void onRequestReceived(IRequestContext context) {}public void onRequestCompleted(IRequestContext context) {}public void onDestroyed() {}public void onStartup(ServletContextEvent event) {}public void onShutdown(ServletContextEvent event) {}public void onSessionCreated(HttpSessionEvent event) {}public void onSessionDestroyed(HttpSessionEvent event) {}public void onRequestInitialized(ServletRequestEvent event) {}public void onRequestDestroyed(ServletRequestEvent event) {}}

2. Exception Processor

Add class errorhandler. Java and inherit iweberrorhandler

public class WebErrorHandler implements IWebErrorHandler {public void onError(Throwable e) {}public IView onConvention(String requestMapping) {return null;}public IView onValidation(Set<ValidateResult> results) {return null;}}

3. Modify the ymp-conf.properties and add related configurations


Note: In the ymp-conf.properties, The YMP. module_list (module list) configuration items are as follows


Ii. Controller

1. Modify ymp-conf.properties, add controller package scan path


Create a controller package and a class Object com. Demo. Controller. democontroller

Democontroller. Java

@Controllerpublic class DemoController {@RequestMapping("hello")@RequestMethodpublic IView hello(){return new TextView("Hello,world!");}}

2. Publish to Tomcat and start it. Access it through a browser:

Http: // localhost: 8080/ympweb/Hello

3. Bind controller parameters.

Add the following code to the Controller:

@RequestMapping("/hello/sayHi")@RequestMethodpublic IView sayHi(@RequestParam String name) {    return new TextView("Hi, " + name);}

Deploy to Tomcat and start it. Access it through a browser:

Http: // localhost: 8080/ympweb/Hello/sayhi? Name = Xiaoming

4. Bind URL parameters

Add the following code to the Controller:

@RequestMapping("/hello/sayHi/{name}")@RequestMethodpublic IView sayHi2(@PathVariable String name) {    return new TextView("Hi, " + name);}

Deploy to Tomcat and start it. Access it through a browser:

Http: // localhost: 8080/ympweb/Hello/sayhi/Xiaoming

5. The controller implements parameter verification.

Add the following code to the Controller:

@RequestMapping("/valid/{name}/{age}")@RequestMethod@Validation(fullMode = true)public IView paramValidator(    @Validate({        @ValidateRule(RequriedValidator.NAME),        @ValidateRule(value = LengthValidator.NAME, params = { "min=3", "max=6" }) })    @PathVariable String name,     @Validate({        @ValidateRule(RequriedValidator.NAME),        @ValidateRule(value = NumericValidator.NAME, params = { "min=18",   "max=20" }) })    @PathVariable String age) {    return new TextView("");}

Access http: // localhost: 8080/ympweb/Hello/sayhi/Xiaoming/13 through a browser. The console throws the following exception:

16:21:39 Org. apache. catalina. core. serious standardwrappervalve invoke: servlet. service () for servlet default threw exceptionnet. ymate. platform. validation. validationexception: [{fieldname: 'age', message: 'length must be between 18 and 20'}, {fieldname: 'name', message: 'length must be between 3 and 6 '}] At net.ymate.platform.mvc.support.requestexecutor.exe cute (requestexecutor. java: 151) at net. ymate. platform. MVC. web. support. dispatchhelper. dorequestprocess (dispatchhelper. java: 119) at net. ymate. platform. MVC. web. dispatcherfilter. dofilter (dispatcherfilter. java: 92) at Org. apache. catalina. core. applicationfilterchain. internaldofilter (applicationfilterchain. java: 235) at Org. apache. catalina. core. applicationfilterchain. dofilter (applicationfilterchain. java: 206) at Org. apache. catalina. core. standardwrappervalve. invoke (standardwrappervalve. java: 233) at Org. apache. catalina. core. standardcontextvalve. invoke (standardcontextvalve. java: 191) at Org. apache. catalina. core. standardhostvalve. invoke (standardhostvalve. java: 127) at Org. apache. catalina. valves. errorreportvalve. invoke (errorreportvalve. java: 103) at Org. apache. catalina. core. standardenginevalve. invoke (standardenginevalve. java: 109) at Org. apache. catalina. connector. coyoteadapter. service (coyoteadapter. java: 293) at Org. apache. coyote. http11.http11processor. process (http11processor. java: 861) at Org. apache. coyote. http11.http11protocol $ http11connectionhandler. process (http11protocol. java: 606) at org.apache.tomcat.util.net. jioendpoint $ worker. run (jioendpoint. java: 489) at java. lang. thread. run (unknown source)

If you want to output the authentication information to the browser, you can use the onvalidation method in the weberrorhandler class. The Code is as follows:

public IView onValidation(Set<ValidateResult> results) {    StringBuilder _sb = new StringBuilder();    for (ValidateResult _result : results) {        _sb.append(_result.getMessage()).append("<br/>");    }    return new TextView(_sb.toString());}

Access through a browser again:

Iii. interceptor

1. Create an interceptor class to intercept an object older than 19 years old. The Code is as follows:

@ Beanpublic class demofilter implements ifilter {public iview dofilter (requestmeta, string Params) throws exception {INTEGER _ age = integer. parseint (stringutils. defaultifempty (string) webcontext. getcontext (). get ("Age"), "0"); If (_ age> 19) {return New textview ("age older than 19 years old, intercepted ");} return NULL ;}}

The project view is as follows:

2. Add @ filter to the paramvalidator method in the democontrol class. The modified code is as follows:

@ Requestmapping ("/valid/{name}/{age}") @ requestmethod @ validation (fullmode = true) @ filter (demofilter. class) Public iview paramvalidator (@ validate ({@ validaterule (requriedvalidator. name), @ validaterule (value = lengthvalidator. name, Params = {"min = 3", "max = 6"}) @ pathvariable string name, @ validate ({@ validaterule (requriedvalidator. name), @ validaterule (value = numericvalidator. name, Params = {"Min = 18 "," max = 20 "}) @ pathvariable string age) {return New textview (" hello, "+ name + ", you are "+ age +" years old! ");}

3. access through a browser:

After finishing, close the job!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.