Implementing login Validation in Nutz

Source: Internet
Author: User

First, What is Nutz?

Nutz is a lightweight Web -side development framework. The homepage is as follows:http://www.nutzam.com/core/nutz_preface.html

Second, thesession Simple Introduction

we all know that.httpis stateless: Multiple requests are sent from the same browser, and the server does not know that the requests are from the same browser. So in order for the server to know that these requests are from the same browser, use theSessiontechnology. That is, when the browser sends the request to the server for the first time, the server generates asessionId, put thesessionIdback to the browser, the browser willsessionIdinCookiesis saved in the client, the next time the server is requested, thesessionIdwith the past, the server can be based on thesessionIdfound in thisSessionSave the value, and use theSessionA series of operations on the values saved in the

the session-related connections are as follows:http://www.cnblogs.com/sharpxiajun/p/3395607.html

Iii. How to implement login verification inNutz

1. Preparatory work

The following preparations are required: /tologin point to the login page; /login Click to log in after the method of processing login; /logout point to Logout; /test points to a general business processing method. / home points to the main page of the jump after a successful login.

among them: /tologin and the /login is not required for login verification.

/logout,/test,/ Home are required for login verification.

the results to be achieved are as follows:

             click Login /login / password is verified, and if the login is successful, the user Save to session /home homepage; If the login fails, jump to /tologin

for other methods of login verification, implement a filter in which the filter is based on the Session in the User object exists, is validated, if present, jumps to /Home home, otherwise jump /tologin page.

The class code that is responsible for logging in, logging out, and logging on to the home page is as follows:

 PackageXxx.xxx.module;ImportJavax.servlet.http.HttpServletRequest;ImportJavax.servlet.http.HttpSession;ImportOrg.nutz.ioc.loader.annotation.IocBean;ImportOrg.nutz.mvc.annotation.At;ImportOrg.nutz.mvc.annotation.Filters;Importorg.nutz.mvc.annotation.Ok; @IocBeanpublicclassLogindemo {/*** This method points to the login page*/@Filters//This method will not execute a filter after configuring filters@At ("/tologin") @Ok ("")//the path to the login page is configured here     Public voidTologin () {}/*** This method is used for the process of log on * results are redirected to the way to jump. * If login is successful, skip to/home. If login fails, jump to/tologin *@paramreq *@paramSession *@return     */@At ("/login") @Ok ("Redirect:${obj==true?" /home ': '/tologin '} ") @Filters Public BooleanLogin (HttpServletRequest req,httpsession session) {String UserName=req.getparameter ("name"); String pwd=req.getparameter ("pwd"); Booleanresult=false;//The result of the login success or not. Default is False                if(!isblank (userName) &&!IsBlank (PWD)) {            /*** This is a database query verification based on the username and password entered, to see if the user exists. * The password is usually encrypted when the user registers or adds the user.             Or you could encrypt the password and save it to the database by adding a user name of salt. * The user name and password need to be encrypted at this time.             And the user name, encrypted password as a condition, from the database to query the user.             * If present, the login is successful. */                        /*** Here the user simulates objects queried from the database*/User User=NewUser (); if(user!=NULL) {result=true;//Login Successful at this timeSession.setattribute ("user", user);//Save the user to the session. }        }                returnresult; }            /*** Log Out *@paramSession*/@At ("/logout") @Ok ("Redirect:/tologin")     Public voidLogout (HttpSession session) {session.invalidate ();//the session is destroyed}            /*** Determine if str is empty or "" If yes, returns TRUE. Otherwise returns false *@paramSTR *@return     */    Private  BooleanIsBlank (String str) {if(str==NULL|| "". Equals (Str.trim ())) {            return true; }Else{            return false; }    }}
View Code

2. Using the checksession.class filter with its own

need to be Indexmodule Configure the filter in the main entry class as follows:

 Package Xxx.xxx.module; Import org.nutz.mvc.annotation.By; Import org.nutz.mvc.annotation.Filters; Import org.nutz.mvc.filter.CheckSession; // Where: "User" is the name of the attribute in the session. "/tologin" is the processing if the property does not exist. Jump to the sign-in page here. @Filters (@By (type = checksession.  Class, args={"user", "/tologin"}))publicclass  initmodule {}
View Code

the checksession.class Source code in Nutz is as follows:

 PackageOrg.nutz.mvc.filter;ImportJavax.servlet.http.HttpSession;ImportOrg.nutz.mvc.ActionContext;ImportOrg.nutz.mvc.ActionFilter;ImportOrg.nutz.mvc.Mvcs;ImportOrg.nutz.mvc.View;ImportOrg.nutz.mvc.view.ServerRedirectView;/*** Check the current Session, if there is a property and is not NULL, pass <br> * Otherwise, return a serverrecirectview to the corresponding path * <p> * constructor requires two parameters * < ;ul> * <li> First is the name of the property that needs to be checked. If this attribute is present in the session, it is indicated by checking that * <li> second is, if not checked, where the current request is being diverted. A path similar to/yourpath/xxx.xx * </ul> * *@authorZozoh ([email protected])*/ Public classChecksessionImplementsActionfilter {PrivateString name; PrivateString Path;  Publicchecksession (string name, string path) { This. Name =name;  This. Path =path; }     PublicView Match (Actioncontext context) {HttpSession session= Mvcs.gethttpsession (false); if(Session = =NULL||NULL==Session.getattribute (name))return NewServerredirectview (path); return NULL; }}
View Code

3. Custom Filters

The following is a custom filter Myfilter The code implementation:

 PackageXxx.xxx.filters;ImportJavax.servlet.http.HttpSession;ImportOrg.nutz.ioc.loader.annotation.IocBean;ImportOrg.nutz.mvc.ActionContext;ImportOrg.nutz.mvc.ActionFilter;ImportOrg.nutz.mvc.View;ImportOrg.nutz.mvc.view.ServerRedirectView;/*** Custom Login verification! * @author  * */@IocBeanpublicclassMyfilterImplementsactionfilter{@Override PublicView Match (Actioncontext Actioncontext) {HttpSession session=actioncontext.getrequest (). GetSession (); if(Session.getattribute ("user")! =NULL){            return NULL;//Execute Method}//Verify that you skip to other pages when you don't pass!         return NewServerredirectview ("/tologin.html"); }}
View Code

In fact, the implementation of Checksession is very similar.

Custom Filter the configuration and built -in Checksession.class configuration is similar, configured as follows:

@Filters (@By (type = myfilter.  Class , args={"Ioc:myfilter"}))
View Code

Iv. Considerations and References

1. precautions

was IOC the classes that you manage need to be added before the class name @IocBean .

If you are logged in, you need to Session To save multiple properties in the "User", user The properties used for login validation are placed last to prevent the issue of various null pointers. Reference:http://wendal.net/399.html

2. References

Filter Related: http://www.nutzam.com/core/mvc/action_filter.html

The entry function returns the View Related: http://www.nutzam.com/core/mvc/view.html

Http://wendal.net/436.html

===============================================================================================

Above only for my personal beginner Nutz A little bit of experience, if there is not correct and inappropriate place, please point out a lot, common progress!

If reproduced, please specify the source. Thank you!

Implementing login Validation in Nutz

Related Article

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.