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>
本文由用户 jopen 自行上传分享,仅供网友学习交流。所有权归原作者,若您的权利被侵害,请联系管理员。
转载本站原创文章,请注明出处,并保留原始链接、图片水印。
本站是一个以用户分享为主的开源技术平台,欢迎各类分享!