首页 > 代码库 > spring登陆验证注解区分登陆角色
spring登陆验证注解区分登陆角色
先上拦截器代码
import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.method.HandlerMethod; import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; import com.tutor.normal.entity.TutorUser; import com.tutor.normal.service.ITutorUserService; import com.tutor.normal.status.UserType; import com.tutor.tool.util.ResultUtil; public class TutorLoginFilter extends HandlerInterceptorAdapter { private static Logger log = LoggerFactory.getLogger(TutorLoginFilter.class); @Resource(name = "tutorUserService") private ITutorUserService tutorUserService; @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { log.info(handler.getClass().toString()); String token = request.getParameter("token"); TutorUser user = null; try { HandlerMethod method = (HandlerMethod) handler; TutorLoginAnnotation annotation = method.getMethodAnnotation(TutorLoginAnnotation.class); if(annotation == null) { return true; } else { user = tutorUserService.validUser(token, annotation.type().getValue()); log.info("用户user=" + user); } } catch (Exception e) { log.error(e.getMessage()); response.setContentType("text/html;charset=utf-8"); response.getWriter().write(ResultUtil.returnJson(e)); response.getWriter().flush(); response.getWriter().close(); return false; } return true; } }
这个是我的注解
package com.tutor.normal.filter; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import com.tutor.normal.status.UserType; @Documented @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.METHOD}) public @interface TutorLoginAnnotation { public UserType type() default UserType.ALL; }
这个是枚举
package com.tutor.normal.status; public enum UserType { STUDENT("学生", 1), TEACHER("老师", 2), ALL("全部", 0); private String name; private int value; private UserType(String name, int value) { this.name = name; this.value = value; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getValue() { return value; } public void setValue(int value) { this.value = value; } }
注解用法
@TutorLoginAnnotation(type = UserType.TEACHER) @RequestMapping("/tea/search/{v}") @ResponseBody public ResultBean myfun() { ... }
最后spring中拦截器的配置
<mvc:interceptors> <mvc:interceptor> <mvc:mapping path="/stu/**" /> <mvc:mapping path="/tch/**" /> <mvc:mapping path="/ord/**" /> <bean class="com.tutor.normal.filter.TutorLoginFilter" /> </mvc:interceptor> </mvc:interceptors>
spring登陆验证注解区分登陆角色
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。