• java web开发入门十二(idea创建maven SSM项目需要解决的问题)基于intellig idea(2019-11-09 11:23)


    一、spring mvc action返回string带双引号问题

    解决方法:

    在springmvc.xml中添加字符串解析器

        <!-- 注册string和json解析适配器 -->
        <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
            <property name="messageConverters">
                <list>
    
                    <bean class="org.springframework.http.converter.StringHttpMessageConverter"/>
                    <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"/>
                </list>
            </property>
        </bean>

    二、css文件中引用的img url写法

    暂未解决

    三、action请求去掉.action

     1.web.xml配置

     <!-- 注册springmvc核心控制器-->
        <servlet>
            <!--servlet-name的值对应一个文件:/WEB-INF/DispatcherServlet-servlet.xml   -->
            <servlet-name>springmvc</servlet-name>
            <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
            <init-param>
                <!-- 指定application.xml文件 -->
                <param-name>contextConfigLocation</param-name>
                <param-value>classpath:springmvc.xml</param-value>
            </init-param>
            <load-on-startup>1</load-on-startup>
        </servlet>
        <servlet-mapping>
            <servlet-name>springmvc</servlet-name>
            <!--  <url-pattern>*.action</url-pattern>-->
            <!--默认匹配所有请求-->
            <!--Spring MVC将捕获Web容器所有的请求,包括静态资源的请求,Spring MVC会将它们当成一个普通请求处理-->
            <url-pattern>/</url-pattern>
        </servlet-mapping>

    2.修改spring.xml文件,让静态文件交给servlet处理 

    参考:https://www.cnblogs.com/jdbn/p/11020374.html

    <!-- 配置SpringMVC -->
        <!-- 1.开启SpringMVC注解模式 -->
        <!-- 简化配置:
            (1)自动注册DefaultAnootationHandlerMapping,AnotationMethodHandlerAdapter
            (2)提供一些列:数据绑定,数字和日期的format @NumberFormat, @DateTimeFormat, xml,json默认读写支持
        -->
        <mvc:annotation-driven/>
    
        <!--
        静态资源交给servlet处理,
        在springMVC-servlet.xml中配置<mvc:default-servlet-handler />后,
        会在Spring MVC上下文中定义一个org.springframework.web.servlet.resource.DefaultServletHttpRequestHandler,
        它会像一个检查员,对进入DispatcherServlet的URL进行筛查,
        如果发现是静态资源的请求,就将该请求转由Web应用服务器默认的Servlet处理,
        如果不是静态资源的请求,才由DispatcherServlet继续处理。
        -->
        <mvc:default-servlet-handler/>

    四、登录拦截器

    1.编写LoginInterceptor

    package com.eggtwo.euq.interceptor;
    
    import com.eggtwo.euq.dto.CurrentSysUser;
    import com.eggtwo.euq.utils.CacheUtil;
    import com.eggtwo.euq.utils.ConfigUtil;
    import com.eggtwo.euq.utils.CookieUtil;
    import org.springframework.web.servlet.HandlerInterceptor;
    import org.springframework.web.servlet.ModelAndView;
    
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import java.io.IOException;
    import java.io.PrintWriter;
    
    public class LoginInterceptor implements HandlerInterceptor {
        private boolean isAjaxRequest(HttpServletRequest request) {
            if (request.getHeader("x-requested-with") != null && request.getHeader("x-requested-with").equalsIgnoreCase("XMLHttpRequest")) {
                //如果是ajax请求响应头会有,x-requested-with
                System.out.print("发生ajax请求...");
                return true;
    
            }
            return false;
        }
    
    
        @Override
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    
            String requestUri = request.getRequestURI(); //请求完整路径,可用于登陆后跳转
            String contextPath = request.getContextPath();  //项目下完整路径
            String url = requestUri.substring(contextPath.length()); //请求页面
            System.out.print("发生拦截...");
            System.out.println("来自:" + requestUri + "的请求");
    
            //拿到cookie
            //也就是获取session里的登录状态值
            String cookieKey = ConfigUtil.getBossCookieKey();
            String cookieValue = CookieUtil.getByName(request, cookieKey);
            CurrentSysUser currentSysUser =null;
            String errorMsg=null;
            if (cookieValue == null) {
                errorMsg="no login,please login";
            }else{
                currentSysUser = CacheUtil.getT(cookieValue);
                if (currentSysUser == null) {
                    errorMsg="no login,please login";
                }
            }
            if (errorMsg!=null){
                if (isAjaxRequest(request)) {
                    response.setContentType("application/json; charset=utf-8");
                    PrintWriter writer = response.getWriter();
                    writer.print("{type:0,msg:'"+errorMsg+"'}");
                    writer.close();
                    response.flushBuffer();
                } else {
                    String basePath= request.getContextPath();
                    response.sendRedirect(basePath+"/account/login?error="+errorMsg);
                }
                return false;//返回false不走下面的方法
            }
            //更新缓存过期时间
            CacheUtil.remove(cookieValue);
            CacheUtil.set(cookieValue, currentSysUser, ConfigUtil.getBossCookieTimeoutSecond());
            //更新cookie过期时间--覆盖原有的cookie
            CookieUtil.deleteCookie(response, cookieKey);
            //写入cookie
            CookieUtil.addCookie(response, cookieKey, cookieValue, ConfigUtil.getBossCookieTimeoutSecond());
    
    
    
            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 {
    
        }
    }

    2.spring mvc中配置要拦截的action

     <!--配置拦截器, 多个拦截器,顺序执行 -->
        <mvc:interceptors>
            <mvc:interceptor>
                <!-- 先匹配所有路径,然后排除不需要检查的路径 -->
                <mvc:mapping path="/**"/>
    
    
                <!--不拦截的action-->
                <mvc:exclude-mapping path="/account/login"/>
                <mvc:exclude-mapping path="/account/logout"/>
    
                <!-- 网站的登录路径是 "http://localhost:8080/cultivate-job/"
                    路径path="/"表示的路径就是网站入口路径,
                    也就是说拦截器只方向两种请求:
                    1. 错误页面,直接访问jsp页面,这些页面不在WEB-INF目录下,可以直接访问
                    2. 网站入口请求,检查到没有登录,会重定向到网站入口路径,再被定向到登录页面
                -->
                <mvc:exclude-mapping path="/"/>
                <!-- 以下是静态资源 -->
                <mvc:exclude-mapping path="/content/**" />
                <mvc:exclude-mapping path="/images/**" />
                <mvc:exclude-mapping path="/js/**" />
                <mvc:exclude-mapping path="/css/**" />
                <mvc:exclude-mapping path="/upload/**" />
                <mvc:exclude-mapping path="/download/**" />
    
                <!-- 自定义拦截器路径 -->
                <bean class="com.eggtwo.euq.interceptor.LoginInterceptor"></bean>
            </mvc:interceptor>
            <!-- 当设置多个拦截器时,先按顺序调用preHandle方法,然后逆序调用每个拦截器的postHandle和afterCompletion方法 -->
        </mvc:interceptors>

    五:异常拦截器

    LoginInterceptor
  • 相关阅读:
    MVC3的零散记录 EF常见的转换规则
    MVC3的零散记录 设置区域(Areas)后遭遇IE浏览器 jQuery未定义错误
    Visual Studio 2010 选中高亮插件 Highlight all occurrences of selected word
    asp.net mvc 在表单中输入html标记
    实验818 报数 (20 分)
    关于SQL SERVER中获取表的主键名
    MVC4的新增功能之前端优化
    winform中实现不重复创建窗体
    微盘产品分析(零):时代向前走了一步
    网络相册产品分析(一):十年需求变迁
  • 原文地址:https://www.cnblogs.com/eggTwo/p/11826280.html
Copyright © 2020-2023  润新知