美文网首页
二、账号和个人页面的实现

二、账号和个人页面的实现

作者: 薛定谔的猫_1406 | 来源:发表于2018-06-09 17:10 被阅读0次

    一、 个人注册功能实现

    用户注册流程
    • java8 Map的遍历
    Map<String,String> newMap =Maps.newHashMap();
            newMap.put("1", "python");
            newMap.put("2", "java");
            newMap.put("3", "pythoner");
            newMap.put("4", "lll");
            newMap.forEach((key,value) ->{if(value != null) newMap.put(key, value+"===");});
            newMap.forEach((key,value) -> System.out.println(value));
    //所有的Entry用&进行连接,key - value之间用=分割
            System.out.println(Joiner.on("&").useForNull("").
                  withKeyValueSeparator("=").
                  join(newMap));
            
    
    • 并保存文件
    package com.imooc.web.controller;
    
    import java.io.File;
    import java.io.IOException;
    import java.time.Instant;
    import java.util.List;
    
    import org.apache.commons.lang.StringUtils;
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.web.multipart.MultipartFile;
    
    import com.google.common.collect.Lists;
    import com.google.common.io.Files;
    
    public class FileSaveService {
        
        @Value("${file.path}")
        private String filePath;
        
        public List<String> getImgPath(List<MultipartFile> fileList){
            List<String> paths = Lists.newArrayList();
            //遍历当前的MultiPartFileList,然后依次保存
            fileList.forEach(file -> 
            {
                File localFile = null;
                if(!file.isEmpty()) {
                    try {
                        localFile = saveToLocal(file,filePath);
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    //最终保存的是文件剔除前面绝对路径的相对路径
                    String path =StringUtils.substringAfterLast(localFile.getAbsolutePath(), filePath);
                    paths.add(path);
                }
            }
                    );
            return paths;
            
        }
        
        private File saveToLocal(MultipartFile file,String filePath) throws IOException {
            File newFile = new File(filePath+"/"+Instant.now().getEpochSecond()+file.getOriginalFilename());
            if(!newFile.exists()) {
                //创建父级目录
                newFile.getParentFile().mkdirs();
                //创建文件
                newFile.createNewFile();
            }
            //Guava里的工具类
            Files.write(file.getBytes(),newFile);
            return newFile;
            
        }
        
        
    }
    
    

    1.2 发送邮件过程中生成key并且绑定email,并且缓存key,value,然后发送邮件,并且发送邮件是一个缓慢的过程,所以需要将key-value缓存起来。

    package com.imooc.web.controller;
    
    import java.util.concurrent.TimeUnit;
    
    import org.apache.commons.lang3.RandomStringUtils;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.mail.SimpleMailMessage;
    import org.springframework.mail.javamail.JavaMailSender;
    import org.springframework.scheduling.annotation.Async;
    
    import com.google.common.cache.Cache;
    import com.google.common.cache.CacheBuilder;
    import com.google.common.cache.RemovalListener;
    import com.google.common.cache.RemovalNotification;
    
    /**
     * 用户发送邮件激活 1、缓存key -email 2、使用spring mail发送邮件 3、借助异步框架进行异步操作
     * 
     * @author zhouzhouseela
     *
     */
    public class RegisterNotify {
    
        // 使用起步依赖spring-properties
        @Autowired
        private JavaMailSender mailSender;
    
        // 借助guava生成缓存。最大空间100,过期时间15分钟,超过15分钟未激活链接则删除该注册记录
        private final Cache<String, String> registerCache = CacheBuilder.newBuilder().maximumSize(100)
                .expireAfterAccess(15, TimeUnit.MINUTES).removalListener(new RemovalListener<String, String>() {
                    // 超过15分钟删除该用户的注册记录
                    @Override
                    public void onRemoval(RemovalNotification<String, String> arg0) {
                        // TODO Auto-generated method stub
                        userMapper.delete(arg0.getValue());
    
                    }
    
                }).build();
    
        // 加上@Async注解表示异步执行,并且要在启动类上添加EnableAsync注解才行。并且要注意 ** 调用方所在的类和方法定义所在的类必须是两个不同的类 **
        @Async
        public void registerNotify() {
            // 生成10位的随机字符串
            String randomKey = RandomStringUtils.randomAlphabetic(10);
            // 借助guava生成本地缓存
            String email = "xxxxx";
            registerCache.put(randomKey, email);
            String url = "http://127.0.0.1:8090/accounts/verify?key=" + randomKey;
            // 发送邮件
            sendMail("房产平台注册激活邮件", url, email);
        }
    
        private void sendMail(String title, String url, String email) {
            /**
             * 需要在application.properties设置一些属性,这里为了方便我直接写死
             * 
             */
            String spring_mail_host = "";
            String spring_mail_username = "";
            String spring_mail_password = "";
            boolean spring_mail_properties_mail_smtp_atuh = true;
            boolean spring_mail_properties_mail_smtp_enable = true;
            boolean spring_mail_properties_mail_smtp_required = true;
            SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
            simpleMailMessage.setFrom(spring_mail_username);
            simpleMailMessage.setTo(url);
            simpleMailMessage.setText(url);
            // 发送邮件
            mailSender.send(simpleMailMessage);
    
        }
    
    }
    
    

    1.3 Nginx静态文件转发

    Nginx静态文件转发

    二、登陆实现

    登陆实现

    三、鉴权实现

    鉴权实现
    • AuthInterceptor
    package com.mooc.house.web.interceptor;
    
    import java.util.Map;
    
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import javax.servlet.http.HttpSession;
    
    import org.springframework.stereotype.Component;
    import org.springframework.web.servlet.HandlerInterceptor;
    import org.springframework.web.servlet.ModelAndView;
    
    import com.google.common.base.Joiner;
    import com.mooc.house.common.constants.CommonConstants;
    import com.mooc.house.common.model.User;
    
    @Component
    public class AuthInterceptor implements HandlerInterceptor{
    
        @Override
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
                throws Exception {
            
            Map<String, String[]> map = request.getParameterMap();
            map.forEach((k,v) -> {
                if (k.equals("errorMsg") || k.equals("successMsg") || k.equals("target")) {
                    request.setAttribute(k, Joiner.on(",").join(v));
                }
            });
            String reqUri = request.getRequestURI();
            if (reqUri.startsWith("/static") || reqUri.startsWith("/error") ) {
                return true;
            }
            HttpSession session = request.getSession(true);
            User user =  (User)session.getAttribute(CommonConstants.USER_ATTRIBUTE);
            if (user != null) {
                UserContext.setUser(user);
            }
            return true;
        }
    
        @Override
        public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                ModelAndView modelAndView) throws Exception {
            
        }
    
        @Override
        public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
                throws Exception {
            UserContext.remove();
        }
        
    
    }
    
    
    • AuthActionInterceptor
    package com.mooc.house.web.interceptor;
    
    import java.net.URLEncoder;
    
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import org.springframework.stereotype.Component;
    import org.springframework.web.servlet.HandlerInterceptor;
    import org.springframework.web.servlet.ModelAndView;
    
    import com.mooc.house.common.model.User;
    
    @Component
    public class AuthActionInterceptor implements HandlerInterceptor {
    
        @Override
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
                throws Exception {
            User user = UserContext.getUser();
            if (user == null) {
                String msg = URLEncoder.encode("请先登录","utf-8");
                String target = URLEncoder.encode(request.getRequestURL().toString(),"utf-8");
                if ("GET".equalsIgnoreCase(request.getMethod())) {
                    response.sendRedirect("/accounts/signin?errorMsg=" + msg + "&target="+target);
                    return false;//修复bug,未登录要返回false
                }else {
                    response.sendRedirect("/accounts/signin?errorMsg="+msg);
                    return false;//修复bug,未登录要返回false
                }
            }
            return true;
        }
    
        @Override
        public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                ModelAndView modelAndView) throws Exception {
    
        }
    
        @Override
        public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
                throws Exception {
    
        }
    
    }
    
    
    • 注册两个拦截器的执行顺序
    package com.mooc.house.web.interceptor;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
    import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
    
    @Configuration
    public class WebMvcConf extends WebMvcConfigurerAdapter {
    
        @Autowired
        private AuthActionInterceptor authActionInterceptor;
        
        @Autowired
        private AuthInterceptor authInterceptor;
        
        @Override
        public void addInterceptors(InterceptorRegistry registry){
             registry.addInterceptor(authInterceptor).excludePathPatterns("/static").addPathPatterns("/**");
                registry
                    .addInterceptor(authActionInterceptor).addPathPatterns("/house/toAdd")
                    .addPathPatterns("/accounts/profile").addPathPatterns("/accounts/profileSubmit")
                    .addPathPatterns("/house/bookmarked").addPathPatterns("/house/del")
                    .addPathPatterns("/house/ownlist").addPathPatterns("/house/add")
                    .addPathPatterns("/house/toAdd").addPathPatterns("/agency/agentMsg")
                    .addPathPatterns("/comment/leaveComment").addPathPatterns("/comment/leaveBlogComment");
                super.addInterceptors(registry);
        }
    
        
    }
    
    

    相关文章

      网友评论

          本文标题:二、账号和个人页面的实现

          本文链接:https://www.haomeiwen.com/subject/zdjteftx.html