java自动登录

温故而知新。从其他页面访问时,如直接访问index页面,勾选过自动登录,从session/cookie获取用户信息,没有勾选,从session中获取用户信息,需要使用filter过滤器

工程结构,采用gradle构建:

public class User {

    private String username;
    private String password;

    public User() {
    }

    public User(String username, String password) {
        this.username = username;
        this.password = password;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    @Override
    public String toString() {
        return "User{" +
                "username='" + username + '\'' +
                ", password='" + password + '\'' +
                '}';
    }
}
import com.yz.filter.LoginFilter;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @description: springboot 登录拦截器配置
 * @author: yz
 * @create: 2018/11/7 18:11
 */
@Configuration
public class LoginFilterConfig {

    @Bean
    public FilterRegistrationBean registrationBean(){
        FilterRegistrationBean bean = new FilterRegistrationBean();
        bean.setFilter(new LoginFilter());
        bean.addUrlPatterns("/*");
        return bean;
    }
}
import com.yz.bean.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @description: 自动登录
 * @author: yz
 * @create: 2018/11/7 16:07
 */
@Controller
public class UserController {

    @GetMapping("login")
    public String login(){
        return "login";
    }

    @GetMapping("index")
    public String index(){
        return "index";
    }

    /**
     * @param request
     * @param response
     * @param user
     * @param auto
     * @return
     */
    @PostMapping("user_login")
    public ModelAndView userLogin(HttpServletRequest request,HttpServletResponse response,User user, String auto){
        ModelAndView mv = new ModelAndView("redirect:login");
        HttpSession session = request.getSession();
        // 登录成功
        if("admin".equals(user.getUsername()) && "123456".equals(user.getPassword())){
            // 存值
            session.setAttribute("user",user);
            // 判断是否勾选自动登录
            if("on".equals(auto)){
                System.out.println("有勾选自动登录");
                // 将用户账号密码保存到cookie中
                Cookie cookie = new Cookie("account",user.getUsername()+"#"+user.getPassword());
                cookie.setMaxAge(60*60*24*7);
                response.addCookie(cookie);
            }
            // 跳转
            mv.setViewName("redirect:index");
            return mv;
        }
        // 登录失败
        session.setAttribute("msg","用户名或者密码错误!");
        // 跳转到登录页面,显示数据
        return mv;
    }
}
import com.yz.bean.User;

import javax.servlet.*;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @description: 登录拦截器
 * 单独使用时,放开注解;使用拦截器配置时注掉注解
 * @author: yz
 * @create: 2018/11/7 17:34
 */
//@WebFilter("/*")
//@Component
//@Order
public class LoginFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    /**
     * 有登录(session or cookie中有用户数据)放行,没有登录就去登录页面
     * @param request
     * @param response
     * @param chain
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

        System.out.println("来到过滤器了。~!~开始拦截请求");
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        // 如果是登录有关操作的,不拦截
        String path = req.getRequestURI();
        System.out.println("path:"+path);
        if (path.contains("login") || path.endsWith(".ico")){
            // 放行
            chain.doFilter(request,response);
            return;
        }

        boolean isLogin = false;

        // 1. session还有效
        HttpSession session = req.getSession();
        User user = (User) session.getAttribute("user");
        if(user != null){
            isLogin = true;
        }else{
            // 2.session失效,看cookie
            // 获取cookie,遍历cookie,拿到账号密码进行判断,对了放行,并将用户对象存储到session中
            Cookie[] cookies = req.getCookies();
            if(cookies !=null){
                for (Cookie cookie : cookies) {
                    // account=admin#123456;
                    if("account".equals(cookie.getName())){
                        String[] accountArray = cookie.getValue().split("#");
                        if("admin".equals(accountArray[0]) && "123456".equals(accountArray[1])){
                            // 登录成功 , 将用户对象保存到session中,以便在会话有效期内访问,都会放行。
                            user = new User(accountArray[0], accountArray[1]);
                            req.getSession().setAttribute("user" , user);
                            isLogin = true;
                        }
                    }
                }
            }
        }

        // 统一对isLogin判断
        if(isLogin){
            chain.doFilter(request,response);
        }else{
            resp.sendRedirect("login");
        }
    }

    @Override
    public void destroy() {

    }
}
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
 * @description:
 * @author: yz
 * @create: 2018/11/7 16:07
 */
@SpringBootApplication
public class LoginApp {

    public static void main(String [] args){

        SpringApplication.run(LoginApp.class , args);
    }

}

index.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" >
<head>
    <meta charset="UTF-8"/>
    <title>Title</title>
</head>
<body>

    <h2>欢迎您,<span th:text="${session.user.username}"></span></h2>

</body>
</html>

login.html

<!DOCTYPE html>
<html xmlns:th="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="UTF-8"/>
    <title>Title</title>
</head>
<body>

    <h2>登录页面</h2>

    <form action="user_login" method="post">

        用户名:&nbsp;<input type="text" name="username"/><br/>
        密&emsp;码:&nbsp;<input type="password" name="password"/><br/>
        <input type="checkbox" name="auto"/>自动登录<br/>
        <input type="submit" value="登录"/>
        <!--用户名或者密码错误!!!-->
        <span style="color:red" th:text="${session.msg}"></span>
    </form>

</body>
</html>

application.properties

server.port=8089

build.gradle

plugins {
    id 'java'
}

group 'com.yz'
version '1.0-SNAPSHOT'

sourceCompatibility = 1.8

repositories {
    mavenCentral()
}

dependencies {
    testCompile group: 'junit', name: 'junit', version: '4.12'
    compile("org.springframework.boot:spring-boot-starter-web:1.5.10.RELEASE")
    compile("org.thymeleaf:thymeleaf-spring4:2.1.4.RELEASE")
}
Java自动登录是指在网站或应用程序中使用Java语言编写代码,实现用户账户的自动登录功能。以下是一个简单的Java自动登录案例: 假设有一个网站,网站在登录页面上有用户名和密码的输入框,并有一个登录按钮,当用户输入正确的用户名和密码后点击登录按钮,网站会验证用户的身份,并跳转到用户的个人主页。现在我们使用Java语言编写代码,实现自动登录功能。 首先,我们需要导入需要的Java类库,如`java.net.URL`、`java.net.HttpURLConnection`等。然后创建一个`URL`对象,传入网站登录页面的URL地址。 接下来,我们创建一个`HttpURLConnection`对象,并使用`openConnection()`方法建立与URL的连接。 然后,我们设置连接的一些属性,如请求方法为POST、设置请求头部(Content-Type为application/x-www-form-urlencoded等)等。 接着,我们构建一个字符串,将用户名和密码以POST请求的格式(如username=value&password=value)放入请求体中,并将请求体写入到连接的输出流中。 然后,我们调用`getInputStream()`方法获取连接的输入流,并读取服务器的响应。如果响应中包含了登录成功的标志(如用户个人主页的URL),则表示登录成功。 最后,我们关闭连接。 以上就是一个简单的Java自动登录案例。需要注意的是,实际中还可能需要处理一些异常、添加验证码处理、保存登录状态等,具体实现方法会因网站的不同而有所不同。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值