Teach you to use JavaWeb achieve ubiquitous Log in Register

Log in Register is basically open to all that the app needs to do, in this era of big data, landing registration is the most basic but most important user data. Taught you how to make today:
a user logs
in major information management system, the login function is essential, his role is to verify the user's identity, to determine whether the user is a member of this site, only members can access the current system
login implementation steps:
1. users fill in account number and password, submit to the background
2. background to obtain account and password, send it to the database query
3. If the query result is null, describes the user to fill in the account number or password is incorrect , should go back to the login page and prompts the user to re-enter
4. If the query result is not null, describes the user to fill in the account number and password are correct, will share the account information corresponding to the session (in the back of the request, we also need to continue to use the current the registered user information), then jumps to the main page of the site
in accordance with the above steps, we use the following code accomplishes a function
1. Log in page
<form class = "form-horizontal " action = "/ login" method = " POST ">
<div class =" form-Group ">
<label for =" inputEmail3 "class =" COL-SM-. 3 Control-label "> username </ label>
<div class =" COL-SM-. 9 " >
<the INPUT of the type = "text" name = "name" class = "



<label for = "inputPassword3" class = "col-sm-3 control-label"> Password </ label>
<div class = "COL-SM-. 9">
<INPUT type = "password" name = "password" class = "form-Control" ID = "inputPassword3">
</ div>
</ div>
<div class = "form-Group">
<label for = "inputPassword3" class = "COL-SM-. 3 Control-label"> </ label>
<div class = "COL-SM-9">
<the Button of the type = "the Submit" class = "btn btn-default"> Log </ the Button> br /> </ div>
</ div>
page There are many layout related code, you can skip directly, look at the focus of the label form elements related to
the LoginServlet
the @WebServlet ( "/ the Login")
public class LoginServlet extends HttpServlet {
private IEmployeeService service = new EmployeeServiceImpl();

protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String name = req.getParameter("name");
    String password = req.getParameter("password");
    Employee currentUser = service.login(name, password);
    if(currentUser==null){
        //登录失败
        req.setAttribute("errorMsg","亲,账户或者密码错误");
        req.getRequestDispatcher("/login.jsp").forward(req,resp);
        return;
    }else{
        //登录成功
        req.getSession().setAttribute("USER_IN_SESSION",currentUser);
        resp.sendRedirect("/employee");
        return;
    }

SQL:
the SELECT * the FROM the Employee the WHERE name = the AND password =??
Logon failure effect

Teach you to use JavaWeb achieve ubiquitous Log in Register

Login successful results

Teach you to use JavaWeb achieve ubiquitous Log in Register

User logs br /> The main function of the role is to protect the user logs off the user's account safe, secure user clicks to exit, we will need this session related to the session information Delete
to delete the following two ways:
1. Delete the currently logged user information
there is a problem: For additional information this session or stored in memory, there is no time to clean up
the @WebServlet ( "/ Zimbabwe Logout")
public class LogoutServlet the extends HttpServlet {
Private IEmployeeService Service = new new EmployeeServiceImpl ();
protected void Service (REQ the HttpServletRequest , HttpServletResponse resp) throws ServletException, IOException {
resp.sendRedirect ( "/ the login.jsp");
}
}
2. destruction of the entire session (recommended)
@WebServlet ( "/ Zimbabwe Logout")
br /> the req.getSession () removeAttribute ( "USER_IN_SESSION");.
resp.sendRedirect ( "/login.jsp");
}
}
2. destruction of the entire session (recommended)
@WebServlet ( "/ Zimbabwe Logout")
public class LogoutServlet the extends the HttpServlet {
Private IEmployeeService new new EmployeeServiceImpl-Service = ();
protected void-Service (the HttpServletRequest REQ, the HttpServletResponse RESP ) throws ServletException, IOException {
the req.getSession () the invalidate ();.
resp.sendRedirect ( "/ the login.jsp");
}
}
codes
authentication code is essential to the function of each system, the system is intended to prevent malicious invasion, if not have this feature, so our system is like an unlocked door, like a thief can come in at any time to do bad things
So let's look at how to use this code at login, if you want to use other modules, the same principle

Teach you to use JavaWeb achieve ubiquitous Log in Register

1. First, you need to show verification code image on the login page, the user can fill in the text according to the picture
2. Meanwhile, when generating code, we need to save the correct code in the session for later school use test
3. after the user fill in the verification code, submit the form, the background check
Note: the generated code verification code is not our focus here in the future, if needed, in the online search a basket, so I will not put out a
check code
// check whether the correct verification code
String randomcode_in_session = (String) the req.getSession () the getAttribute ( "RANDOMCODE_IN_SESSION");.
String randomCode = req.getParameter ( "randomCode");
! iF (StringUtils.isNullOrEmpty (randomCode) && ! StringUtils.isNullOrEmpty (randomcode_in_session)) {
(! randomCode.equals (randomcode_in_session) IF) {
cookies nameCookie = new new cookies ( "name", name);
cookies passwordCookie = new new cookies ( "password", password);
resp.addCookie ( nameCookie);
resp.addCookie (passwordCookie);
the handleError (REQ, RESP, "Pro, verification code error ");
return;
}
} {the else
the handleError (REQ, RESP, "codes can not be empty or expired codes");
return;
}

void the handleError Private (the HttpServletRequest REQ, the HttpServletResponse RESP, String errorMsg)
throws ServletException, IOException
the req.getSession () the setAttribute ( "errorMsg", errorMsg);.
resp.sendRedirect ( "/ the login.jsp");
}
When the user authentication is not filled the session code or code failures, should give an error message
if the saved user session and fill in verification code does not match, an error message will
so, when the code is not correct, we will not continue to do Login check, must wait for the user to fill in the correct validation code before they can, and this machine can not be done
to remember the account
purpose of this function is mainly to after the user once logged in, you can no longer re-fill the next account, increase the user experience
you want to achieve this, we need to share the user's account information in the background
, however, what we should use it to complete the share?
to think about our needs, our ten o'clock this morning, the first landing system, after use, close the browser, the afternoon also need to visit a few times, tomorrow, day after tomorrow ...
so I think this demand can not fill No.
In such a demand, I believe that we can think of an answer the cookie ---
Cookie data is stored in the browser, and we can save the settings of the time, you can still be able to continue to use after you close your browser
so, Cookie is our best solution in this demand in
Add the following code business logic logged in to save the account information to use to save Cookie
// Remember me
String rememberMe = req.getParameter ( "rememberMe");
(! StringUtils.isNullOrEmpty (rememberMe)) IF {
// will user information stored in the Cookie
Cookie nameCookie = new new Cookie ( "name", name);
nameCookie.setMaxAge (60 60 24);

        Cookie rememberMeCookie = new Cookie("rememberMe", rememberMe);
        rememberMeCookie.setMaxAge(60 * 60 * 24);
        resp.addCookie(nameCookie);
        resp.addCookie(rememberMeCookie);
    } else {
        //将用户信息从Cookie中移除
        Cookie[] cookies = req.getCookies();
        for (Cookie cookie : cookies) {
            if ("name".equals(cookie.getName())  || "rememberMe".equals(cookie.getName())) {
                cookie.setMaxAge(0);
                resp.addCookie(cookie);
            }
        }
    }

Then, the data acquired in the login page to the Cookie
<div class = "form-Group">
<label for = "inputEmail3" class = "COL. 3-SM-Control-label"> username </ label>
< class = div ". 9-COL-SM">
<INPUT type = "text" name = "name" class = "form-Control" ID = "inputEmail3"
value = "$ {} cookie.name.value">
</ div>
</ div>

<label>
<the INPUT of the type = "the CheckBox" name = "rememberMe"
$ {empty cookie.rememberMe.value "?": "the checked = 'the checked'"}> Remember Me
</ label>
When I chose to remember, Login error back to the login page, then automatically obtain the account information of the last

Teach you to use JavaWeb achieve ubiquitous Log in Register
Log in to check
if the user is not logged in, the system does not allow access to other modules except login, if access should be directed back to the login page
in javaweb, the best solution to this problem is to use a filter (Filter)
filter : Ability to request preprocessing before accessing the resources to reach the goal, before leaving the response to the response preprocessing
in our demand, before the need for pre-processing of requests to do, check the user requesting the current resource, whether already logged
Implementation steps:
1. define filter: CheckLoginFilter
public class CheckLoginFilter the implements the filter {
Private List <String> needCheckURIs;

public void init(FilterConfig filterConfig) throws ServletException {
    //获取到需要校验的资源名称(如果需要校验的资源较多,可以配置不需要校验的资源)
    String needCheckURI = filterConfig.getInitParameter("needCheckURI");
    String[] split = needCheckURI.split(",");
    //将所有的资源名存放到集合中,待后面进行校验
    needCheckURIs = Arrays.asList(split);
}

public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) 
            throws IOException, ServletException {

    HttpServletRequest req = (HttpServletRequest) request;
    HttpServletResponse resp = (HttpServletResponse) response;
    //获取当前请求的资源名
    String requestURI = req.getRequestURI();
    //如果当前请求的资源是不需要校验的,直接放行
    if(!needCheckURIs.contains(requestURI)){
        filterChain.doFilter(req, resp);
        return;
    }
    //如果需要校验,判断用户是否登录,是,则放行,反之回到登录页面
    Object currentUser = req.getSession().getAttribute("USER_IN_SESSION");
    if (currentUser == null) {
        resp.sendRedirect("/login.jsp");
        return;
    }
    filterChain.doFilter(req, resp);
}

public void destroy() {

}

}
2.将过滤器交给Tomcat服务器管理
<!--登录检查过滤器-->
<filter>
<filter-name>CheckLoginFilter</filter-name>
<filter-class>cn.wolfcode.javaweb.web.filter.CheckLoginFilter</filter-class>
<init-param>
<param-name>needCheckURI</param-name>
<param-value>/employee,/department</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CheckLoginFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
有了该过滤器,用户就不能再没有登录的时候,直接访问相关资源了,做到了一个基本的安全控制
生成系统账户
当系统启动后,我们需要在用户表中存在一个最起码的管理员账户,这样,用户才能登录进来来管理整个系统
那么,如何实现在启动服务器的时候,完成这个需求呢?
其实解决方案很多,大家也都应该能想到
1.Servlet
Servlet默认情况下是在第一次访问的时候执行初始化操作
但是也可以调整到启动服务器的时候,<load-on-startup>0</load-on-startup>
初始化Servlet的时候,会执行当前Servlet的init方法
所以,我们完全在该方法中来完成这个需求
2.Filter
过滤器的初始化就是在启动服务器的时候
和Servlet一样,初始化的时候会执行Filter的init方法
所以,也可以在Filter的init方法中完成该需求
3.Listener
前面学习过WEB中的监听器,知道他能够对作用域(创建/销毁)和作用域中的属性(添加/删除/修改)进行监听
我们的需求是,在启动服务器的时候创建默认账户
而在启动服务器的时候,application作用域对象会在这个时候创建
综上,我们可以创建一个application作用对象监听器,在创建该对象的时候,完成默认账户的创建
上面三种方式都能完成我们的需求,但最终从责任分离原则方面考虑,我们应该选择使用监听器,实现如下
创建监听器
public class SystemManagerCreaterListener implements ServletContextListener {
private IEmployeeService service = new EmployeeServiceImpl();
public void contextInitialized(ServletContextEvent servletContextEvent) {
// default account inquiry system exists, if does not exist, create a default account
the Employee Manager = service.selectSystemManager ();
IF (Manager == null) {
Manager = new new the Employee ();
manager.setName ( "ADMIN");
manager.setPassword ( ". 1");
manager.setAdmin (to true);
service.save (Manager);
}
}

public void contextDestroyed(ServletContextEvent servletContextEvent) {

}

}
Register the listener
<listener>
<listener-class> cn.wolfcode.javaweb.web.listener.SystemManagerCreaterListener </ listener-class>
</ listener>
so, start the server when the first will go to the Employees table query, there is a default administrator account.
Click JavaWeb other articles in this series
taught you how to do JavaWeb Project: The project needs analysis
taught you how to do JavaWeb project: front-end interface
taught you how to do JavaWeb items: multi-condition filter
go knock Ding wolf's official website for more technical video
so grounded gas demo, from now on you can implement your own login registration plate. What are you waiting for? Hurry up!

Guess you like

Origin blog.51cto.com/14598441/2454907
Recommended