qq_35161159
Dw_Qin
采纳率66.7%
2018-12-14 06:44 阅读 1.5k
已采纳

post提交form表单到springMVC,不能跳转问题

5

**项目结构: **

图片说明

  1. jsp页面

index.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>首页</title>
</head>
<body>
    <a href="/sdkapp/init">去往登录页</a>
</body>
</html>

login.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>登录页</title>
    <script src="<%=request.getContextPath()%>/js/jquery-1.7.2.js" type="text/javascript"></script>
</head>
<body>
    <form id="frm">
        用户id: <input type="text" name="uid"><br><br>
        用户名: <input type="text" name="username"><br><br>
        密  码: <input type="password" name="password"><br><br>
        <input type="submit" id="btn" value="登录">
    </form>
    <script type="text/javascript">
        $("#btn").click(function () {
            console.log(getFormJson(frm));
            $.ajax({
                url: "${pageContext.request.contextPath}/sdkapp/login",
                type:"POST",
                data: getFormJson(frm),
                contentType:"application/json;charset=utf-8",
                success:function(data){
                    console.log(data)
                },
                error:function(data){
                    console.log(data)
                }
            });
        })

        function getFormJson(frm) {   //frm:form表单的id
            var o = {};
            var a = $("#"+frm).serializeArray();
            $.each(a, function() {
                if (o[this.name] !== undefined) {
                    if (!o[this.name].push) {
                        o[this.name] = [ o[this.name] ];
                    }
                    o[this.name].push(this.value || '');
                } else {
                    o[this.name] = this.value || '';
                }
            });
            return o;
        }
    </script>
</body>
</html>

success.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>登录成功页</title>
</head>
<body>
    <h1>登录成功</h1>
</body>
</html>

  1. 配置文件 springmvc.xml
<?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:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/mvc
       http://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <!--配置默认的servlet处理器,处理静态资源加载-->
    <mvc:default-servlet-handler/>
    <!--配置包扫描controller-->
    <context:component-scan base-package="controller"/>
    <mvc:annotation-driven/>

    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/pages/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>

</beans>

web.xml
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID" version="2.5">

<servlet>
    <servlet-name>springMvc</servlet-name>
    <!--加载前端控制器-->
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:spring/springmvc.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
    <servlet-name>springMvc</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>

3.java代码

Login.java

package controller;

import controller.vo.User;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@RestController
@RequestMapping(value = "/sdkapp")
public class Login {

    @RequestMapping(value = "/init")
    public ModelAndView casdkbindInput(){
        ModelAndView view = new ModelAndView("/login");
        return view;
    }

    @RequestMapping(value = "/login",method = {RequestMethod.POST},consumes = "application/json;charset=utf-8")
    public ModelAndView testJson(@RequestBody User user) throws Exception {
        System.out.println(user);
        ModelAndView view = new ModelAndView("/success");
        return view;
    }
}

vo/User.java

package controller.vo;
import java.io.Serializable;

public class User implements Serializable {
    private String uid;
    private String username;
    private String password;

    public String getUid() {
        return uid;
    }

    public void setUid(String uid) {
        this.uid = uid;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    @Override
    public String toString() {
        return "User{" +
                "uid='" + uid + '\'' +
                ", username='" + username + '\'' +
                ", password='" + password + '\'' +
                '}';
    }
}

问题是 jq post请求到后台,后台返回 view时,前端接收不到?
附上demo地址:百度云盘

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

4条回答 默认 最新

  • 已采纳
    q447552640 三阶魔方 2018-12-14 06:53

    你仔细看看你的浏览器控制台,你这段代码的success里面,已经把新界面的内容打印出来了。

    $.ajax({
                    url: "${pageContext.request.contextPath}/sdkapp/login",
                    type:"POST",
                    data: getFormJson(frm),
                    contentType:"application/json;charset=utf-8",
                    success:function(data){
                        console.log(data)
                    },
                    error:function(data){
                        console.log(data)
                    }
                });
    

    你需要注意的是,ajax取数据的时候,默认会把取到的内容当做xml来解析处理,跳转会被忽略掉,并解析成常规文本。

    如果你返回的内容想要在当前页显示,你可以直接jquer.load方法把返回的页面显示出来。

    点赞 评论 复制链接分享
  • kylin_bo kylin_bo 2018-12-14 06:53
     public ModelAndView testJson(@RequestBody User user) throws Exception {
            System.out.println(user);
            ModelAndView view = new ModelAndView("/success");
            return view;
        }
    

    改成

    @ResponseBody
     public Object testJson(@RequestBody User user) throws Exception {
            System.out.println(user);
            return user;
        }
    
    点赞 评论 复制链接分享
  • hao45e 神之浩 2018-12-14 06:55

    你登录时用的ajax提交的,success里的data就是返回的view,你可以在控制台的网络里看到发起post请求后返回的信息

    点赞 评论 复制链接分享
  • weixin_37139197 阿进的写字台 2018-12-14 07:24

    不要使用异步提交

     <form id="frm" action='${pageContext.request.contextPath}/sdkapp/login' method='post'>
            用户id: <input type="text" name="uid"><br><br>
            用户名: <input type="text" name="username"><br><br>
            密  码: <input type="password" name="password"><br><br>
            <input type="submit" id="btn" value="登录">
        </form>
    
    $("#btn").click(function () {
               $('#frm').submit();
            })
    
    点赞 评论 复制链接分享

相关推荐