自定义注解@interface

一下代码适用场景:1.表单 不确定那些需要做防止重复提交 2.Controller 需要传同一个值(不确定那些需要;PS:如果Controller链接地址有规律 可以用Filter统一直接刷到页面)

@interface

/**
 * 方法级 创建Token
 * User: Alec
 * Date: 13-3-15
 * Time: 下午2:16
 */
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Token {
}


/**
 * 方法级 检测重复提交
 * User: Alec
 * Date: 13-3-15
 * Time: 下午2:16
 */
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface CheckFormToken {
}


/**
 * 类级 右边栏
 * User: Alec
 * Date: 13-3-15
 * Time: 下午2:52
 */
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface RSidebar {
}


Interceptor

/**
 * Created with IntelliJ IDEA.
 * User: Alec
 * Date: 13-3-15
 * Time: 下午2:21
 * To change this template use File | Settings | File Templates.
 */
public class RenderInterceptor implements HandlerInterceptor {

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private TagService tagService;

    @Autowired
    private MenuQueryService menuQueryService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (handler.getClass().isAssignableFrom(HandlerMethod.class)) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            Object target = handlerMethod.getBean();

            Token token= handlerMethod.getMethodAnnotation(Token.class);
            if(token != null ){
                this.generateFormToken(request);
            }

            CheckFormToken checkFormToken = handlerMethod.getMethodAnnotation(CheckFormToken.class);
            if (checkFormToken != null) {
                if (!checkFormToken(request)) {
                    throw new DuplicateSubmitFormException("表单重复提交!");
                } else {
                    generateFormToken(request);
                }
            }

            if (target.getClass().isAnnotationPresent(RSidebar.class)) {
                pageAddRightSidebar(request);
            }

        }
        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 {
    }


    private boolean checkFormToken(HttpServletRequest request) {
        String token = request.getParameter(SessionConstants.TOKEN);
        HttpSession session = request.getSession();
        String oldToken = (String) session.getAttribute(SessionConstants.TOKEN);
        return token.equals(oldToken);
    }

    private void generateFormToken(HttpServletRequest request) {
        String sessionId = request.getSession().getId();
        String hashString = MD5.getHashString(System.currentTimeMillis() + sessionId);
        request.getSession().setAttribute(SessionConstants.TOKEN, hashString);
    }


    /**
     * 页面右侧栏
     *
     * @return
     */
    private void pageAddRightSidebar(HttpServletRequest request) {
        //加入顶级类目
        List<Category> categoryBanner = categoryService.querySubCategories(0);
        request.setAttribute("categoryBanner", categoryBanner);

        //加入标签
        List<Tag> tags = tagService.queryAllTag();
        request.setAttribute("tags", tags);

        //加入一周推荐
        List<Menu> menuRecommend = menuQueryService.queryMenuRecommendList();
        request.setAttribute("menuRecommend", getMenuListWithMainPicture(menuRecommend));
    }

}

DuplicateSubmitFormException 自定义表单重复提交异常

/**
 * 表单重复提交异常
 * User: Alec
 * Date: 13-3-15
 * Time: 下午2:49
 */
public class DuplicateSubmitFormException extends RuntimeException {

    private String message;

    public DuplicateSubmitFormException(String msg){
        this.message = message;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    @Override
    public Throwable fillInStackTrace() {
        return this;
    }
}

表单提交重复提交异常 页面

/**
 * 表单提交重复提交异常 页面
 * User: Alec
 * Date: 13-3-15
 * Time: 下午2:52
 */
public class SnsExceptionResolver implements HandlerExceptionResolver {

    private final Log logger = LogFactory.getLog(HandlerExceptionResolver.class);

    private String pagePath = "error/default";

    private boolean developModel = false;

    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        logger.error("发生一个系统异常", ex);
        ModelAndView modelAndView = new ModelAndView();
        //这里是在发文章的时候
        if (ex instanceof DuplicateSubmitFormException) {
            modelAndView.setViewName("addArticle");
        } else {
            modelAndView.addObject("msg", ExceptionUtils.getFullStackTrace(ex));
            modelAndView.addObject("developModel", developModel);
            modelAndView.setViewName(pagePath);
        }

        return modelAndView;
    }

    public String getPagePath() {
        return pagePath;
    }

    public void setPagePath(String pagePath) {
        this.pagePath = pagePath;
    }

    public boolean isDevelopModel() {
        return developModel;
    }

    public void setDevelopModel(boolean developModel) {
        this.developModel = developModel;
    }
}


xml 

<bean class="com.sns.web.utils.SnsExceptionResolver">
        <property name="developModel">
            <value>${develop}</value>
        </property>
    </bean>

    <mvc:interceptors>
        <mvc:interceptor>
            <mvc:mapping path="/**"/>
            <bean class="com.sns.web.utils.RenderInterceptor"></bean>
        </mvc:interceptor>
    </mvc:interceptors>

Controller

使用就不写了


----------------------------------------------风骚的分割线--------------------------------------------

如需转载请注明出处  






你可能感兴趣的:(java,注解,自定义)