spring-mvc 发送ajax路径不正确

哈雷路亚 发布于 2017/07/28 16:21
阅读 318
收藏 0

开源之夏第三届火热来袭,高校学生参与赢万元奖金!>>>

A界面通过提交 action转到B 界面,B界面发送ajax 时候路径就不对了 ,最终的路径是

:8081/cqpt/user/user/menu Failed to load resource: the server responded with a status of 404 (Not Found),端口前面的路径都没有了 

代码和配置如下

A.jsp中的内容

<form action="./user/forwordMain">
    <button type="submit">submit</button>
</form>

B.jsp发送的ajax

/**
 * 首页
 */
console.log("home");
var home = new Vue({
    el:'#home',
    data:{
        user :{
            iperson :1,
            imenup  :1
        }
    },
    created : function () {
        $.ajax({
            type: 'post',
            contentType: 'application/text;charset=utf-8',
            data: this.user,
            url: '/user/menu',
            success: function (data) {
                if (data != '') {
                    console.log(data);
                }
            }
        });
    }
    
});

spring 配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/mvc
       http://www.springframework.org/schema/mvc/spring-mvc.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd">

    <!--资源文件中的属性值可通过@Value加载到控制器中-->
    <bean id="configProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
        <property name="locations">
            <list>
                <value>classpath:properties/*.properties</value>
            </list>
        </property>
    </bean>
    <bean id="config" class="org.springframework.beans.factory.config.PreferencesPlaceholderConfigurer">
        <property name="properties" ref="configProperties" />
    </bean>

    <!--扫描控制器 被@Controller注解的类 base-package: 扫描什么包下的类-->
    <context:component-scan base-package="cqsoft.controller"/>
    <!--自动处理 不应该是请求的 资源 如访问图片  引入 css javascript 等-->
    <mvc:default-servlet-handler />
    <!--<mvc:resources mapping="/resources/**/" location="/resources/"/>-->
    <!--
        注解驱动
        会自动注册2个bean
        DefaultAnnotationHandlerMapping 处理在类级别上的@RequestMapping注解
        AnnotationMethodHandlerAdapter  处理方法级别上的@RequestMapping注解
    -->
    <mvc:annotation-driven>
        <!--
            处理表单请求的转换器
            配置一个过多个HttpMessageConverter来转换 @RequestBody方法参数 和 @ResponseBody的方法返回值,优先加载默认的HttpMessageConverter.
        -->
        <!--
        此段注释从 <mvc:message-converters> 源码摘录
        Configures one or more HttpMessageConverter types to use for converting
        @RequestBody method parameters and @ResponseBody method return values.
        Using this configuration element is optional.
        HttpMessageConverter registrations provided here will take precedence over HttpMessageConverter types registered
        by default. Also see the register-defaults attribute if you want to turn off default registrations entirely.
        -->
        <mvc:message-converters>
            <ref bean="jsonHttpMessageConverter"/>
            <ref bean="stringHttpMessageConverter"></ref>
            <ref bean="formHttpMessageConverter"/>
        </mvc:message-converters>
    </mvc:annotation-driven>

    <!--
        如果 controller 中使用 @RequestBody 注解function的参数 必须适用请求转换器类理请求
        实现了HttpMessageConverter的接口类如下
        ByteArrayHttpMessageConverter  converts byte arrays.
        StringHttpMessageConverter converts strings.
        FormHttpMessageConverter converts form data to/from a MultiValueMap<String, String>.
        SourceHttpMessageConverter converts to/from a javax.xml.transform.Sourc
    -->

    <!--
        application/json : 将表单当做 json 字符串
        如果设置请求头 'Content-Type': 'application/json' 必须启用 MappingJackson2HttpMessageConverter Bean
        导入2个jar包:
        Gradle 导入写法
            com.fasterxml.jackson.core:jackson-core:2.5.2
            com.fasterxml.jackson.core:jackson-databind:2.5.2
        缺少一个一项配置,就会导致 网页出现http 415 错误
    -->
    <bean id="jsonHttpMessageConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
        <property name="supportedMediaTypes">
            <list>
                <value>application/json;charset=UTF-8</value>
            </list>
        </property>
    </bean>
    <!--处理 "text/plain" -->
    <bean id="stringHttpMessageConverter"  class="org.springframework.http.converter.StringHttpMessageConverter">
        <constructor-arg value="UTF-8" index="0"></constructor-arg><!--
            避免出现乱码 -->
        <property name="supportedMediaTypes">
            <list>
                <value>text/plain;charset=UTF-8</value>
            </list>
        </property>
    </bean>
    <!--处理 application/x-www-form-urlencoded -->
    <bean id="formHttpMessageConverter" class="org.springframework.http.converter.FormHttpMessageConverter"></bean>


    <!--spring mvc 最常用的视图模式,可以通过前缀加后缀的方式直接定位到view -->
    <!--InternalResourceViewResolver 继承自 UrlBasedViewResolver  -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/view/"/>
        <property name="suffix" value=".jsp"></property>
    </bean>

    <!-- 配置数据源 -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
        <!-- 基础配置 -->
        <property name="driverClass" value="${driverClassName}" />
        <property name="jdbcUrl" value="${url}" />
        <!-- 用户名和密码加密 -->
        <property name="properties" ref="AccountDecrypt" />

        <!-- 关键配置 -->
        <!--初始化时获取三个连接,取值应在minPoolSize与maxPoolSize之间。Default: 3 -->
        <property name="initialPoolSize" value="${initialPoolSize}" />
        <!--连接池中保留的最小连接数。Default: 2 -->
        <property name="minPoolSize" value="${minPoolSize}" />
        <!--连接池中保留的最大连接数。Default: 15 -->
        <property name="maxPoolSize" value="${maxPoolSize}" />
        <!--当连接池中的连接耗尽的时候c3p0一次同时获取的连接数。Default: 3 -->
        <property name="acquireIncrement" value="${acquireIncrement}" />

        <!-- 性能配置 -->
        <!-- 控制数据源内加载的PreparedStatements数量。如果maxStatements与maxStatementsPerConnection均为0,则缓存被关闭。Default: 0 -->
        <property name="maxStatements" value="${maxStatements}" />
        <!--最大空闲时间,1800秒内未使用则连接被丢弃。若为0则永不丢弃。Default: 0 -->
        <property name="maxIdleTime" value="${maxIdleTime}" />

        <property name="idleConnectionTestPeriod" value="${idleConnectionTestPeriod}" />
        <property name="acquireRetryAttempts" value="${acquireRetryAttempts}" />
        <property name="breakAfterAcquireFailure" value="${breakAfterAcquireFailure}" />
        <property name="testConnectionOnCheckout" value="${testConnectionOnCheckOut}" />
    </bean>

    <!-- 解密账号与密码 -->
    <bean id="AccountDecrypt" class="cqsoft.util.AccountDecryptUtil">
        <property name="properties">
            <props>
                <prop key="username">${username}</prop>
                <prop key="password">${password}</prop>
            </props>
        </property>
    </bean>

    <!-- spring和MyBatis完美整合,不需要mybatis的配置映射文件 -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <!-- 自动扫描mapping.xml文件 -->
        <property name="mapperLocations" value="classpath:sqlmap/*.xml"></property>
    </bean>

    <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
        <constructor-arg index="0" ref="sqlSessionFactory"/>
    </bean>

    <bean id="BaseDao" class="cqsoft.dao.base.BaseDao">
    </bean>

    <!--加载资源文件-->
    <import resource="beans.xml"/>

    <!--文件上传-->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!--maxUploadSize可上传多少字节 (53000000=50mb)-->
        <property name="maxUploadSize" value="53000000" />
        <property name="maxInMemorySize" value="4096" />
        <property name="defaultEncoding" value="UTF-8"></property>
    </bean>

</beans>

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         version="3.1">
    <!--加载spring 核心的 servlet-->
    <servlet>
        <servlet-name>dispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!--此参数必须有 ,配合多 spring.xml是当前这种写法,还可以指定加载某个spring.xml-->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value></param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>dispatcherServlet</servlet-name>
        <!--拦截所有请求,这样配置会把 访问图片,应用css js script 等都当做请求处理-->
        <!--避免 css js script 等都当做请求处理 ,需要在spring配置文件中加入 <mvc:resources/> 或 mvc:default-servlet-handler  标签 -->
        <url-pattern>/</url-pattern>
    </servlet-mapping>
    <!--多spring 配置文件-->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:spring/springContext.xml</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <!--字符编码过滤器-->
    <filter>
        <filter-name>springCharacterEncodingFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>forceEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>springCharacterEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    <!--log4j配置-->
    <servlet>
        <description></description>
        <display-name>InitLog4J</display-name>
        <servlet-name>InitLog4J</servlet-name>
        <servlet-class>cqsoft.servlets.InitLog4J</servlet-class>
        <init-param>
            <param-name>log4j</param-name>
            <param-value>WEB-INF\classes\properties\log4j.properties</param-value>
        </init-param>
        <load-on-startup>3</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>InitLog4J</servlet-name>
        <url-pattern>/InitLog4J</url-pattern>
    </servlet-mapping>

    <context-param>
        <param-name>log4jConfigLocation</param-name>
        <param-value>classpath:properties/log4j.properties</param-value>
    </context-param>



    <!-- 首页 -->
    <welcome-file-list>
        <welcome-file>submit.jsp</welcome-file>
    </welcome-file-list>

</web-app>
加载中
0
厚积薄发-laigous
厚积薄发-laigous

:8081/cqpt/user/user/menu   自已看看, 中间有两个user,是否正确,你的页面的url路径都是相对路径吗?

哈雷路亚
哈雷路亚
回复 @laigous : 换成..action的路径中就没有项目名了 http://localhost:8081/user/forwordMain?
哈雷路亚
哈雷路亚
我已经补充了配置文件和代码在上面
厚积薄发-laigous
厚积薄发-laigous
./表示是以当前路径为根路径的相对路径。就是你之前请求的后的路径,url最好都用绝对路径,你用../再试试吧
哈雷路亚
哈雷路亚
提交action 就很奇怪 ./user/forwordMain 前面多个点,B界面发送ajax 就更不对了
OSCHINA
登录后可查看更多优质内容
返回顶部
顶部
返回顶部
顶部