springmvc中controller和前端jsp页面的交互问题

时间:2021-07-28 21:12:26
先上代码段
@RequestMapping(value = "/userLogin", method = RequestMethod.POST)
public String userLogin(@RequestParam("userName") String userName,
@RequestParam("password") String password,
HttpServletRequest request, Model model) {
System.out.println(userName);
System.out.println(password);
User user = userBasic.getUserByName(userName);
if (user != null) {
if (user.getPassword().equals(password)) {
HttpSession session = request.getSession();
session.setAttribute("userName", userName);
model.addAttribute("state", "success");
model.addAttribute("message", "登录成功!");
return "user_project";
} else {
model.addAttribute("failure", "用户名或密码错误!");
return "error";
}
} else {
model.addAttribute("state", "failure");
model.addAttribute("message", "该用户不存在!");
return "error";
}
}

在这个方法所在类上有@RequestMapping("/user")
我想要的是调用这个登录函数后如果密码正确就跳转到user_project.jsp这个页面
下面是我的index.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/xhtml/DTD/xhtml-transitional.dtd">
<html lang="zh-CN">
  <head>
    <base href="<%=basePath%>">
    
    <title>登录系统</title>
    
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">    
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->

  </head>
  
  <body>
   <form  id="form_login">
              用户名:<input type="text" name="userName" id="userName"/>
              密码:<input type="password" name="password" id="password"/>
              <button type="button" value="登录" onclick="toLogin()">登录</button>
       </form>    

      <script src="http://libs.baidu.com/jquery/1.9.0/jquery.js" type="text/javascript"></script>
      <script>
       function toLogin(){
       $.ajax({
       url:"<%=basePath%>user/userLogin",
       data:{"userName":"brianzhuang","password":"124652"},
       type:"POST",
       dataType:"html",
       success: function(data,textstatus){
       alert(textstatus);
       },
       error:function(jqxhr,textstatus,error){
       alert(jqxhr);
       alert(error);
       alert(textstatus);
       }
       });
              }
      
      </script>
  </body>
</html>


1,我想要利用jquery对ajax的封装来实现,ajax是异步的请求,是不是不支持跳转页面?
2,index页面中点击登录按钮后走的是error的处理方法,三个alert,为什么?调用不到controller的方法???
我快受不了这个了,求大神帮我解决!!!

7 个解决方案

#1


在浏览器的开发者工具里看看发出去的请求与响应的什么

#2



                  $.ajax({
                      url:"<%=basePath%>user/userLogin",
                      data:{"userName":"brianzhuang","password":"124652"},
                      type:"POST",
                      dataType:"json",
                      success: function(msg){
                          if(msg.success){
window.location = "要跳转的地址";
}
                      },
                      error:function(msg){
                          
                      }
                  });

#3


后端加上@ResponseBody注解返回json格式的数据

#4


@RequestMapping(value = "/userLogin", method = RequestMethod.POST)
public @ResponseBody Map<String, Object> userLogin(@RequestParam("userName") String userName,
@RequestParam("password") String password,
HttpServletRequest request){
Map<String, Object> map = new HashMap<String, Object>();
System.out.println(userName+"  "+password);
User user = userBasic.getUserByName(userName);
//System.out.println(user.getUserName());
if(user!=null){
//System.out.println(user.getPassword());
if(user.getPassword().equals(password)){
map.put("userID", user.getId());
} else {
System.out.println("wrong password");
}
}
//System.out.println(map.get("userID"));
return map;
}

<script type="text/javascript">
       $(function(){
       $("#btnbutton").bind("click",function(){
       $.ajax({
       url:"<%=basePath%>user/userLogin",
       type:'post',
       data:{"userName":$("#userName").val(),"password":$("#password").val()},
       dataType:"json",
       success: function(data,textstatus){
       alert(JSON.stringify(data));
       alert(textstatus);},
       error:function(jqxhr,textstatus,error){
       alert(textstatus);
       console.log(jqxhr);}
              });
             });
              });
      </script>

我现在把controller的这个方法改成这样,前端页面url为localhost:8080/项目名/user/userLogin/,点击登录后执行了这两条语句:alert(JSON.stringify(data));  alert(textstatus);},然后url跳转到了localhost:8080/项目名/?userName=brianzhuang&password=124652。。。。我真是晕了,怎么办?

#5


只是跳转页面的话为啥要用ajax呢,正常将form表单提交后台,然后controller用你最开始写的不挺好的么,前台一提交,后台经过判断就能跳转到相应页面就完事了。登录用ajax这样处理。。。。。前台提交,然后后台判断,最后前台还得手动写js让页面跳转,不觉得麻烦么,而且ajax注重的是局部刷新页面,你这个完全没这个需求

#6


ajax本来就是用来做局部刷新的,你这要进行页面跳转还要用ajax跟它本身的定位就相悖啊,不合理

#7


@RequestMapping(value = "/userLogin", method = RequestMethod.POST)
@ResponseBody----这里要加个响应ajax数据的
    public String userLogin(@RequestParam("userName") String userName,
            @RequestParam("password") String password,
            HttpServletRequest request, Model model) {
        System.out.println(userName);
        System.out.println(password);
        User user = userBasic.getUserByName(userName);
        if (user != null) {
                    if (user.getPassword().equals(password)) {
                        HttpSession session = request.getSession();
                        session.setAttribute("userName", userName);
                        return "1";
                    } else {
                        return "-1";
                    }
        } else {
            return "0";
        }
    }


<script>
              function toLogin(){
                  $.ajax({
                      url:"<%=basePath%>user/userLogin",
                      data:{"userName":"brianzhuang","password":"124652"},
                      type:"POST",
                      dataType:"html",
                      success: function(data,textstatus){
                          alert(textstatus);
                          window.location.href=" 这里放跳转页面的链接"
                      },
                      error:function(jqxhr,textstatus,error){      
                          alert(error);
                      }
                  });
              }
               
      </script>

#1


在浏览器的开发者工具里看看发出去的请求与响应的什么

#2



                  $.ajax({
                      url:"<%=basePath%>user/userLogin",
                      data:{"userName":"brianzhuang","password":"124652"},
                      type:"POST",
                      dataType:"json",
                      success: function(msg){
                          if(msg.success){
window.location = "要跳转的地址";
}
                      },
                      error:function(msg){
                          
                      }
                  });

#3


后端加上@ResponseBody注解返回json格式的数据

#4


@RequestMapping(value = "/userLogin", method = RequestMethod.POST)
public @ResponseBody Map<String, Object> userLogin(@RequestParam("userName") String userName,
@RequestParam("password") String password,
HttpServletRequest request){
Map<String, Object> map = new HashMap<String, Object>();
System.out.println(userName+"  "+password);
User user = userBasic.getUserByName(userName);
//System.out.println(user.getUserName());
if(user!=null){
//System.out.println(user.getPassword());
if(user.getPassword().equals(password)){
map.put("userID", user.getId());
} else {
System.out.println("wrong password");
}
}
//System.out.println(map.get("userID"));
return map;
}

<script type="text/javascript">
       $(function(){
       $("#btnbutton").bind("click",function(){
       $.ajax({
       url:"<%=basePath%>user/userLogin",
       type:'post',
       data:{"userName":$("#userName").val(),"password":$("#password").val()},
       dataType:"json",
       success: function(data,textstatus){
       alert(JSON.stringify(data));
       alert(textstatus);},
       error:function(jqxhr,textstatus,error){
       alert(textstatus);
       console.log(jqxhr);}
              });
             });
              });
      </script>

我现在把controller的这个方法改成这样,前端页面url为localhost:8080/项目名/user/userLogin/,点击登录后执行了这两条语句:alert(JSON.stringify(data));  alert(textstatus);},然后url跳转到了localhost:8080/项目名/?userName=brianzhuang&password=124652。。。。我真是晕了,怎么办?

#5


只是跳转页面的话为啥要用ajax呢,正常将form表单提交后台,然后controller用你最开始写的不挺好的么,前台一提交,后台经过判断就能跳转到相应页面就完事了。登录用ajax这样处理。。。。。前台提交,然后后台判断,最后前台还得手动写js让页面跳转,不觉得麻烦么,而且ajax注重的是局部刷新页面,你这个完全没这个需求

#6


ajax本来就是用来做局部刷新的,你这要进行页面跳转还要用ajax跟它本身的定位就相悖啊,不合理

#7


@RequestMapping(value = "/userLogin", method = RequestMethod.POST)
@ResponseBody----这里要加个响应ajax数据的
    public String userLogin(@RequestParam("userName") String userName,
            @RequestParam("password") String password,
            HttpServletRequest request, Model model) {
        System.out.println(userName);
        System.out.println(password);
        User user = userBasic.getUserByName(userName);
        if (user != null) {
                    if (user.getPassword().equals(password)) {
                        HttpSession session = request.getSession();
                        session.setAttribute("userName", userName);
                        return "1";
                    } else {
                        return "-1";
                    }
        } else {
            return "0";
        }
    }


<script>
              function toLogin(){
                  $.ajax({
                      url:"<%=basePath%>user/userLogin",
                      data:{"userName":"brianzhuang","password":"124652"},
                      type:"POST",
                      dataType:"html",
                      success: function(data,textstatus){
                          alert(textstatus);
                          window.location.href=" 这里放跳转页面的链接"
                      },
                      error:function(jqxhr,textstatus,error){      
                          alert(error);
                      }
                  });
              }
               
      </script>