关闭

用Springmvc做一个小小的登录检测

标签: spring mvc
154人阅读 评论(0) 收藏 举报
分类:

首先是一个Action,也就是控制类,里面有一个拦截去a页面的方法“/ToA”,一个跳转到a页面的方法“ToA1”,目的是只有登陆后点击按钮才会跳转到a页面,否则会跳转到登陆页面


package com.action;
import java.util.List;
import net.sf.json.JSON;
import net.sf.json.JSONArray;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.bind.support.SessionStatus;
import org.springframework.web.servlet.ModelAndView;
import com.DaoAndEntity.User;
import com.DaoAndEntity.UserDAO;
import com.interpoter.Token;
@Controller
@SessionAttributes("user")//定义一个名为user的sessionattributes
public class Action {   
        @RequestMapping("/ToRegister")//去注册页面
        @Token(save=true)//获取token之存入attribute
        public String register(){
            return "register";
        }
        @RequestMapping("/ToA")//拦截a页面
        public String toa(){
            return "login";
        }
        @RequestMapping("/ToA1")//去a页面
        public String toa1(){
            return "a";
        }
        @RequestMapping("/tosport")//去首页
        public String Index(){
            return "sport";
        }
        @RequestMapping({ "/", "" })//启动时打开主页
        public String tosport(){
            return "sport";
        }
        @RequestMapping("/tologin")//跳转至登录页面
        @Token(save=true)//这里的token是为了防止注册后刷新导致表单重复提交
        public String login(){      
            return "login";
        }
        @RequestMapping("/Register")//注册方法
        @Token(remove=true)//清除token值
        public String register(User user){
            UserDAO userdao = new UserDAO();            
            if(userdao.findbyname(user.getUserName()).size()==0){               
                userdao.save(user);//将user对象添加至数据库
                System.out.println("添加成功!!!"+user.getUserNickname());               
            }
            return "success";
        }
        @RequestMapping("/findname")//注册检测,判断用户名是否重复
        public @ResponseBody JSON findname(String name){        
            JSONArray jsonarray = new JSONArray();
            UserDAO u = new UserDAO();
            List list = u.findbyname(name);
            System.out.println(list.size());
            jsonarray.add(list.size());         
            ModelAndView mv = new ModelAndView();           
            mv.setViewName("register");
            return jsonarray;
        }
        @RequestMapping("/findname1")//登陆检测,判断用户名是否注册
        public @ResponseBody JSON findname1(String name){
            //User user = new User();           
            JSONArray jsonarray = new JSONArray();
            UserDAO u = new UserDAO();
            List list = u.findbyname(name);
            System.out.println(list.size());
            jsonarray.add(list.size());         
            ModelAndView mv = new ModelAndView();           
            mv.setViewName("/tologin");
            return jsonarray;
        }
        @RequestMapping("/out")//注销用户
        public String Out(SessionStatus sessionStatus){
            sessionStatus.setComplete();
            return "redirect:/tosport";
        }
        @RequestMapping("/login")//登陆方法
        @Token(save=true)
        public ModelAndView login(User user, Model model1,String preurl){
            UserDAO u = new UserDAO();
            System.out.println(user.getUserNickname()+"bbbbbbbbb");
            System.out.println(user.getUserName()+"bbbbbbbbb");
            ModelAndView model = new ModelAndView();
            model.addObject(user);
            model1.addAttribute("user", user);
            List list = u.findbyname(user.getUserNickname());
            int flag=0;
            System.out.println(list.size()+"     aaaaaaaaaa"+user.getUserNickname());
            System.out.println(user.getUserName()+"1212121212121");
            for(int i =0;i<list.size();i++){
                System.out.println(list.get(i));
                if(((List) list.get(i)).get(1).equals(user.getUserPassword()))
                    flag=i+1;
            }
            if(list.isEmpty()||flag==0){
                System.out.println(user.getUserNickname());
                System.out.println(user.getUserPassword());
                model.setViewName("error");
                System.out.println(list);
                model.addObject("error", "用户名或密码错误");           
            }else{
                model.addObject("name", ((List) list.get(flag-1)).get(3));
                model.addObject("password", ((List) list.get(flag-1)).get(1));
                model.addObject("phone", ((List) list.get(flag-1)).get(2));
                model.setViewName("sport");
            }
            return model;
        }   
    }

接下来就要写拦截器类了
这里我们选择重写HanderInterceptor接口里面preHandle的方法
在预处理之前我们通过判断SessionAttributes里面的user对象是否为空
如果为空则拦截返回false若不为空则重定向到a页面返回true


package com.interpoter;

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

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

public class Interptor implements HandlerInterceptor{

    @Override
    public void afterCompletion(HttpServletRequest arg0,
            HttpServletResponse arg1, Object arg2, Exception arg3)
            throws Exception {
        // TODO Auto-generated method stub      
    }
    @Override
    public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1,
            Object arg2, ModelAndView arg3) throws Exception {
        // TODO Auto-generated method stub      
    }
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
            Object arg2) throws Exception {
        System.out.println("处理之前");
        // TODO Auto-generated method stub
        String url = request.getRequestURI();//获取地址栏uri     
        //toA
        String preurl=request.getServletPath().substring(1);
    /////////////   
        if (!url.isEmpty()) {
            if (request.getSession() != null && request.getSession().getAttribute("user") != null) {                
                response.sendRedirect(request.getContextPath() + "/ToA1");//重定向至页面a
                System.out.println("1111111");
            } else {
                System.out.println("null");
                return true;
            }
        }
///////////
        if (request.getSession() != null && request.getSession().getAttribute("user") != null) {

            System.out.println("2222222");
            return true;
        }
        System.out.println("3333333");
        return false;   
}
}

最后则是拦截器的配置

<mvc:interceptors>
 <mvc:interceptor>
 <mvc:mapping path="/ToA"/> <!-- 指定拦截ToA方法-->
 <bean class="com.interpoter.Interptor"></bean>
 </mvc:interceptor>
 </mvc:interceptors>
0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:5864次
    • 积分:293
    • 等级:
    • 排名:千里之外
    • 原创:21篇
    • 转载:1篇
    • 译文:0篇
    • 评论:4条
    最新评论