如何使用Ajax响应修改现有的URL在Spring MVC项目?如何使用、项目、Ajax、URL

2023-09-11 00:58:50 作者:沉睡

我工作的一个Spring MVC的项目中,网页有两个输入字段。这两个输入栏的字符串类型。但REGNO字段获取号码,并且如果用户输入了REGNO它应采取在控制器中的相应的方法。如果用户输入的名称,它应采取在控制器中的相应的方法。

的web.xml

 < web-app的版本=2.2ID =WebApp_ID>

    <! - <显示-名称>原型创建Web应用程序和LT; /显示-名称> - >

    <的context-param>
        <参数 - 名称>&contextConfigLocation的LT; /参数 - 名称>
        &LT;参数值&GT; /WEB-INF/spring/appContext.xml< /参数值&GT;
    &LT; /的context-param&GT;

    &LT;听者GT;
        &LT;监听级&GT; org.springframework.web.context.ContextLoaderListener
        &LT; /监听级&GT;
    &LT; /听者GT;

    &LT;的servlet&GT;
        &LT; servlet的名称&gt;分派器LT; / Servlet的名称&gt;
        &LT;的servlet类&GT; org.springframework.web.servlet.DispatcherServlet
        &LT; / Servlet的类&GT;
        &LT;初始化参数&GT;
            &LT;参数 - 名称&gt;&contextConfigLocation的LT; /参数 - 名称&gt;
            &LT;参数值&GT; /WEB-INF/spring/dispatcher-servlet.xml< /参数值&GT;
        &LT; /初始化参数&GT;
        &所述;负载上启动→1&其中; /负载上启动&GT;
    &LT; / servlet的&GT;

    &LT; Servlet映射&GT;
        &LT; servlet的名称&gt;分派器LT; / Servlet的名称&gt;
        &LT; URL模式&GT; / MVC / *&LT; / URL模式&GT;
    &LT; / Servlet映射&GT;
    &LT;欢迎-文件列表&gt;
        &LT;欢迎-文件&gt; /WEB-INF/jsp/template.jsp< /欢迎-文件&gt;
    &LT; /欢迎-文件列表&gt;
&LT; / web-app的&GT;
 

1)什么是ID的目的=WebApp_ID?

tiles.xml

 &LT; XML版本=1.0编码=UTF-8&GT?;

&LT;!DOCTYPE瓷砖,定义PUBLIC
   -  // Apache软件基金会// DTD瓷砖配置2.1 // EN
     http://tiles.apache.org/dtds/tiles-config_2_1.dtd">


&LT;瓷砖 - 定义&GT;
    &LT;定义名称=模板模板=/ WEB-INF / JSP / template.jsp&GT;
        &LT;把属性名称=称号值=/&GT;
        &LT;把属性名=标头值=/ WEB-INF / JSP / header.jsp中/&GT;
        &LT;把属性名=身体的价值=/ WEB-INF / JSP / ads.jsp/&GT;
        &LT;把属性名=中心的价值=/ WEB-INF / JSP / ads.jsp/&GT;
        &LT;把属性名=页脚值=/ WEB-INF / JSP / footer.jsp中/&GT;
    &LT; /定义&GT;

    &LT;定义名称=标题扩展=模板&GT;
        &LT;把属性名称=称号值=/&GT;
        &LT;把属性名=身体的价值=/ WEB-INF / JSP / ads.jsp/&GT;
    &LT; /定义&GT;

    &LT;定义名称=numberResult扩展=模板&GT;
        &LT;把属性名称=称号值=/&GT;
        &LT;把属性名=身体的价值=/ WEB-INF / JSP / nResult.jsp/&GT;
    &LT; /定义&GT;

    &LT;定义名称=nameResult扩展=模板&GT;
        &LT;把属性名称=称号值=/&GT;
        &LT;把属性名=身体的价值=/ WEB-INF / JSP / neResult.jsp/&GT;
    &LT; /定义&GT;
 

调度 - servlet.xml中

 &LT; XML版本=1.0编码=UTF-8&GT?;

&LT;豆类的xmlns =htt​​p://www.springframework.org/schema/beans
的xmlns:XSI =htt​​p://www.w3.org/2001/XMLSchema-instance
的xmlns:MVC =htt​​p://www.springframework.org/schema/mvc
的xmlns:TX =htt​​p://www.springframework.org/schema/tx
的xmlns:上下文=htt​​p://www.springframework.org/schema/context
的xmlns:P =htt​​p://www.springframework.org/schema/p
XSI:的schemaLocation =htt​​p://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
                    http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
                    http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
                    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd">

    &LT;背景:组件扫描基封装=com.ProjectCtxt.www.controller/&GT;

    &LT; MVC:注解驱动/&GT;

    &LT; MVC:资源映射=/资源/ **位置=/资源//&GT;

  &LT;! - &LT;豆ID =jspViewResolver
          类=org.springframework.web.servlet.view.InternalResourceViewResolver
          电话号码:preFIX =/ WEB-INF / JSP /
          电话号码:JSP后缀= /&GT; - &GT;

      &LT; bean类=org.springframework.web.servlet.view.tiles2.TilesConfigurer&GT;
            &LT;属性名=定义&GT;
                &LT;列表&gt;
                    &LT;价值&GT; /WEB-INF/tiles.xml< /值GT;
                &LT; /列表&gt;
            &LT; /性&gt;
        &LT; /豆&GT;

       &LT; bean类=org.springframework.web.servlet.view.tiles2.TilesViewResolver/&GT;

        &LT;豆ID =tilesViewResolver级=org.springframework.web.servlet.view.UrlBasedViewResolver&GT;
            &LT;属性名=viewClass类&GT;
                &LT;值GT;
                    org.springframework.web.servlet.view.tiles2.TilesView
                &LT; /值GT;
            &LT; /性&gt;
        &LT; /豆&GT;

&LT; /豆&GT;
 
Springmvc2 Springmvc项目搭建步骤 String类型 ModelAndView类型 Void类型 的返回值 RequestParam注解 Ajax注解

ProjectController.java

  @Controller(resultController)
公共类ResultController {

    私人最终ResultService resultService;

    @Autowired
    公共ResultController(ResultService resultService){
        this.resultService = resultService;
    }


    @RequestMapping(值=/模板,方法= RequestMethod.GET)
    公共字符串getPersonList(ModelMap模型){
        的System.out.println(我们来到这个地方);
        返回头;
    }


    @RequestMapping(值=/搜索/秒,方法= RequestMethod.GET,则params = {REGNO})
    公共字符串getStudentResult(@RequestParam(值=REGNO,要求= TRUE)字符串REGNO,ModelMap模型){
        的System.out.println(我来到这里时,我进入REGNO和AJAX的作品);
        model.addAttribute(studentResult,resultService.getStudentResult(REGNO));
        返回numberResult;
    }


    @RequestMapping(值=/搜索/ L / studentName = {studentName},方法= RequestMethod.GET,则params = {studentName})
    公共字符串anotherMethod(字符串studentName,ModelMap模型){

        返回nameResult;
    }
}
 

header.jsp中

 &LT;%@页面语言=Java的的contentType =text / html的;字符集= UTF-8
    的pageEncoding =UTF-8%&GT;


 &LT; HEAD&GT;
 &所述;脚本的src =的http://$c$c.jquery.com/jquery.min.js&GT;&所述; /脚本&GT;

 &LT; /头&GT;


      &LT;形式方法=GET&GT;
                &LT;输入类型=文本ID =REGNONAME =REGNO大小=30最大长度=50占位符=请输入注册号为&GT;&LT; /输入&GT;
                &LT;输入类型=文本ID =studentNameNAME =studentName大小=30最大长度=50占位符=请输入学生姓名&GT;&LT; /输入&GT;

                &LT;按钮的onclick =的ProcessInput();&GT;搜索
                &LT; /按钮&GT;
    &LT; /形式GT;

&LT;脚本&GT;
 传播的ProcessInput(){
     如果(的document.getElementById('REGNO)。值!=){

          $阿贾克斯({
                键入:GET,
                网址:搜索/秒,
                数据:{REGNO:$(#REGNO)VAL()},
                成功:函数(studentResult){
                    //显示你的结果
                   //警报(价值);
                    $('#displayArea)HTML(studentResult); }
            });
        }否则,如果(的document.getElementById('studentName)。值!=){
            $阿贾克斯({
                键入:GET,
                网址:搜索/ L,
                数据:{studentName:$(#studentName)VAL()
                成功:函数(结果){
                    //显示你的结果
                }}
            });
        }
}
 &LT; / SCRIPT&GT;
 

template.jsp

 &LT;%@页面语言=Java的的contentType =text / html的;字符集= UTF-8
    的pageEncoding =UTF-8%&GT;
   &LT;%@标签库的uri =htt​​p://tiles.apache.org/tags-tilespreFIX =砖%&GT;

&LT;!DOCTYPE HTML&GT;
&LT; HTML&GT;
&LT; HEAD&GT;
&LT; META HTTP-当量=Content-Type的CONTENT =text / html的;字符集= UTF-8&GT;

&LT; /头&GT;
&LT;中心&GT;
    &LT;表格的宽度=750的边界=0的cellpadding =2CELLSPACING =2ALIGN =中心&GT;
    &其中; TR&GT;
        &LT; TD&GT;&LT;地砖:insertAttribute名称=标题/&GT;
        &LT; / TD&GT;
    &LT; / TR&GT;
    &其中; TR&GT;
        &LT; TD&GT;&LT;地砖:insertAttribute名=体/&GT;&LT; / TD&GT;
    &LT; / TR&GT;
    &其中; TR&GT;
        &LT; TD高度=225&GT;&LT;地砖:insertAttribute名=页脚/&GT;
        &LT; / TD&GT;
    &LT; / TR&GT;
&LT; /表&gt;
&LT; /中心&GT;
&LT; / HTML&GT;
 

numberResult.jsp

 &LT;%@页面语言=Java的的contentType =text / html的;字符集= UTF-8
    的pageEncoding =UTF-8%&GT;



 &LT;%@ taglib伪preFIX =CURI =htt​​p://java.sun.com/jsp/jstl/core%&GT;
 c为C:超时值=这是工作/&GT;
  c为C:超时值=$ {studentResult.name}/&GT;&LT; BR /&GT;
  c为C:超时值=$ {studentResult.regNo}/&GT;&LT; BR /&GT;
    c为C:超时值=$ {studentResult.deptName}/&GT;&LT; BR /&GT;
      c为C:超时值=$ {studentResult.collName}/&GT;&LT; BR /&GT;

&LT; D​​IV ID =displayArea&GT;
 c为C:超时值=$ {studentResult.name}/&GT;&LT; BR /&GT;
  c为C:超时值=$ {studentResult.regNo}/&GT;&LT; BR /&GT;
    c为C:超时值=$ {studentResult.deptName}/&GT;&LT; BR /&GT;
      c为C:超时值=$ {studentResult.collName}/&GT;&LT; BR /&GT;

&LT; / DIV&GT;
 

2)用户进入REGNO在header.jsp中,和我想要的结果在numberResult.jsp显示

3)我的第一个URL 本地主机:8080 / ProjectCtxt / MVC /模板进入主页。当我在输入栏中输入REGNO,我的网址在浏览器中显示本地主机:8080 / ProjectCtxt / MVC /模板/ REGNO = 123安培; studentName = 。而且我到达getStudentResult方法,我可以看到我的System.out控制台,但我无法看到在浏览器的输出。

由于我使用的瓷砖,我不知道这个问题是瓷砖解析器或AJAX。请你帮助我好吗?谢谢你。

PS:请回答所有的问题,如果可能的数字,所以,这将帮助别人。谢谢你。

更新:我改变了我的header.jsp中,如下所示,现在我明白了numberResult的用户界面。但我没有看到numberResult JSP作为template.jsp的身体。我猜numberResult文本返回到了AJAX成功的一部分。

 &LT;输入类型=文本ID =REGNONAME =REGNO大小=30最大长度=50占位符=请输入注册号为&GT;&LT ; /输入&GT;
  &LT;输入类型=文本ID =studentNameNAME =studentName大小=30最大长度=50占位符=请输入学生姓名&GT;&LT; /输入&GT;
  &LT;输入ID =inputFields类型=按钮值=搜索/&GT;


&LT;脚本&GT;
$(文件)。就绪(函数(){
    $('#inputFields)。点击(函数(){
       的ProcessInput();
    });
  });


 传播的ProcessInput(){
     如果(的document.getElementById('REGNO)。值!=){

          $阿贾克斯({
                键入:GET,
                网址:搜索/秒,
                数据:{REGNO:$(#REGNO)VAL()},
                成功:函数(studentResult){
                    //显示你的结果
                    警报(价值);
                    $('#displayArea)HTML(studentResult); //此行显示的文字//numberResult。不过,这并不改变JSP以及网址。现在我的URL看起来//本地主机:8080 / MVC /模板和JSP的身体没有numberResult.jsp
                    }
            });
        }否则,如果(的document.getElementById('studentName)。值!=){
            $阿贾克斯({
                键入:GET,
                网址:搜索/ L,
                数据:{studentName:$(#studentName)VAL()
                成功:函数(结果){
                    //显示你的结果
                }}
            });
        }
}
 &LT; / SCRIPT&GT;


&LT; D​​IV ID =displayArea&GT;
 c为C:超时值=$ {studentResult.name}/&GT;&LT; BR /&GT;
  c为C:超时值=$ {studentResult.regNo}/&GT;&LT; BR /&GT;
    c为C:超时值=$ {studentResult.deptName}/&GT;&LT; BR /&GT;
      c为C:超时值=$ {studentResult.collName}/&GT;&LT; BR /&GT;

&LT; / DIV&GT;
 

解决方案

修改

好吧,我想我误解了最初的问题和预期的结果。有几个问题,你的方法。

您试图附加一个AJAX事件,以一个按钮,在一个非异步的方式提交表单。 您试图显示从一个JSP标签AJAX请求的响应。

这两个问题是不兼容的组件的问题。当您在一个非异步的方式提交一个表单,您申请一个新的页面,浏览器加载,而JavaScript没有时间来完成并显示结果。 JSP标签不能被加载和异步显示,因为它们需要在服务器上进行处理。这使你有两个可能的解决方案:

1。使这一过程完全同步。

删除表单标签,并留下了输入和按钮:

 &LT;输入类型=文本ID =REGNONAME =REGNO大小=30最大长度=50占位符=请输入注册号为&GT;&LT ; /输入&GT;
&LT;输入类型=文本ID =studentNameNAME =studentName大小=30最大长度=50占位符=请输入学生姓名&GT;&LT; /输入&GT;
&LT;按钮ID =searchButton&GT;搜索&LT; /按钮&GT;
 

现在没有表单提交,所以您不必担心不小心覆盖你的AJAX功能。更新您的JavaScript来读取输入值,执行适当的AJAX请求,并显示结果:

  $(#searchButton)。在(点击,函数(){
   如果($('#REGNO)。VAL()!=){

      $阿贾克斯({
            键入:GET,
            网址:搜索/秒,
            数据:{REGNO:$(#REGNO)VAL()},
            成功:函数(studentResult){
                $('#displayArea')的HTML(&其中; P&gt;中+ stu​​dentResult.id +&所述; / P&GT;&其中; P&gt;中+ stu​​dentResult.name +&所述; / P&GT;&其中p为H.;等等。 &其中; / P&GT);}
        });
    }否则,如果(的document.getElementById('studentName)。值!=){
        $阿贾克斯({
            键入:GET,
            网址:搜索/ L,
            数据:{studentName:$(#studentName)VAL()
            成功:函数(结果){
                //显示你的结果
            }}
        });
    }
});
 

请确保该控制器处理您的AJAX方法设置为返回一个对象的JavaScript能够理解。春天应该可以,你给它序列化最对象:

  @RequestMapping(值=/搜索/秒,方法= RequestMethod.GET,则params = {REGNO})
公共@ResponseBody StudentResult getStudentResult(@RequestParam(值=REGNO)字符串REGNO){
    返回resultService.getStudentResult(REGNO);
}
 

2。使这一过程完全不同步

如果您在使用JSP标记来显示数据集,你就废了AJAX和以通常的方式提交表单:

 &LT;形式方法=POST&GT;
    &LT;输入类型=文本ID =REGNONAME =REGNO大小=30最大长度=50占位符=请输入注册号为&GT;&LT; /输入&GT;
    &LT;输入类型=文本ID =studentNameNAME =studentName大小=30最大长度=50占位符=请输入学生姓名&GT;&LT; /输入&GT;
    &LT;按钮ID =searchButton&GT;搜索&LT; /按钮&GT;
&LT; /形式GT;
 

您可以提供一个动作属性,如果你想的形式发布或执行GET不同的URL。创建一个控制器方法来处理提交:

  @RequestMapping(值=/ someUrl,方法= RequestMethod.POST)
公共字符串getStudentResult(@RequestParam(值=REGNO,要求= FALSE)字符串REGNO,@RequestParam(值=studentName,要求= FALSE)字符串studentName,ModelMap模型){
    如果(REGNO =空&安培;!&安培;!regNo.equals()){
        model.addAttribute(studentResult,resultService.getStudentResult(REGNO));
        返回numberResult;
    }否则,如果(studentName = NULL和放大器;!&安培;!studentName.equals()){
        model.addAttribute(nameResult,someOtherObject);
        返回nameResult;
    } 其他 {
        model.addAttribute(的errorMessage,无形式的数据提供!);
        返回someOtherView;
    }
}
 

现在,只要你有你的观点成立,接受返回的对象,并将它们映射在你的JSTL,你的标签应该只是罚款。

I am working on a Spring MVC project where the homepage has two input fields. Both input fields are of String type. But the regNo field gets number and if the user enters the regNo it should be taken to the corresponding method in controller. If the user enters the name, it should be taken to the corresponding method in controller.

web.xml

<web-app version="2.2" id="WebApp_ID">

    <!-- <display-name>Archetype Created Web Application</display-name> -->

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/spring/appContext.xml</param-value>
    </context-param>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener
        </listener-class>
    </listener>

    <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet
        </servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/spring/dispatcher-servlet.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>/mvc/*</url-pattern>
    </servlet-mapping>
    <welcome-file-list>
        <welcome-file>/WEB-INF/jsp/template.jsp</welcome-file>  
    </welcome-file-list>
</web-app>

1) What is the purpose of id="WebApp_ID"?

tiles.xml

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE tiles-definitions PUBLIC    
  "-//Apache Software Foundation//DTD Tiles Configuration 2.1//EN"   
     "http://tiles.apache.org/dtds/tiles-config_2_1.dtd">


<tiles-definitions>
    <definition name="template" template="/WEB-INF/jsp/template.jsp">
        <put-attribute name="title" value=""/>
        <put-attribute name="header" value="/WEB-INF/jsp/header.jsp" />
        <put-attribute name="body" value="/WEB-INF/jsp/ads.jsp  "/>
        <put-attribute name="center" value="/WEB-INF/jsp/ads.jsp" />
        <put-attribute name="footer" value="/WEB-INF/jsp/footer.jsp" /> 
    </definition>

    <definition name="header" extends="template">
        <put-attribute name="title" value="" />  
        <put-attribute name="body" value="/WEB-INF/jsp/ads.jsp" />  
    </definition>

    <definition name="numberResult" extends="template">
        <put-attribute name="title" value="" />  
        <put-attribute name="body" value="/WEB-INF/jsp/nResult.jsp" />  
    </definition>

    <definition name="nameResult" extends="template">
        <put-attribute name="title" value="" />  
        <put-attribute name="body" value="/WEB-INF/jsp/neResult.jsp" />  
    </definition>

dispatcher-servlet.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:mvc="http://www.springframework.org/schema/mvc"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
                    http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd     
                    http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
                    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd">

    <context:component-scan base-package="com.ProjectCtxt.www.controller"/>

    <mvc:annotation-driven />

    <mvc:resources mapping="/resources/**" location="/resources/" />

  <!--   <bean id="jspViewResolver"
          class="org.springframework.web.servlet.view.InternalResourceViewResolver"
          p:prefix="/WEB-INF/jsp/"
          p:suffix=".jsp" /> -->

      <bean class="org.springframework.web.servlet.view.tiles2.TilesConfigurer">
            <property name="definitions">
                <list>
                    <value>/WEB-INF/tiles.xml</value>                       
                </list>
            </property>        
        </bean>

       <bean class="org.springframework.web.servlet.view.tiles2.TilesViewResolver"/>

        <bean id="tilesViewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver">
            <property name="viewClass">
                <value>
                    org.springframework.web.servlet.view.tiles2.TilesView
                </value>
            </property>
        </bean>  

</beans>

ProjectController.java

@Controller("resultController")
public class ResultController {

    private final ResultService resultService;

    @Autowired
    public ResultController(ResultService resultService) {
        this.resultService = resultService;
    }


    @RequestMapping(value ="/template", method = RequestMethod.GET)
    public String getPersonList(ModelMap model) {
        System.out.println("We are coming into this place");
        return   "header";
    }


    @RequestMapping(value = "/search/s", method = RequestMethod.GET, params = { "regNo" })
    public String getStudentResult(@RequestParam(value = "regNo", required = true) String regNo, ModelMap model){
        System.out.println("I am coming here when I enter regNo and AJAX works");
        model.addAttribute("studentResult",resultService.getStudentResult(regNo));      
        return "numberResult";
    }


    @RequestMapping(value = "/search/l/studentName={studentName}", method = RequestMethod.GET, params = { "studentName" })
    public String anotherMethod(String studentName, ModelMap model){

        return "nameResult";
    }
}

header.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>


 <head>
 <script src="http://code.jquery.com/jquery.min.js"></script>

 </head>


      <form method="GET" >
                <input  type="text" id="regNo" name="regNo" size="30" maxLength="50" placeholder="Enter Register Number"></input>      
                <input  type="text" id="studentName" name="studentName" size="30" maxLength="50" placeholder="Enter Student Name"></input>

                <button onclick="processInput();">Search
                </button>
    </form>

<script>
 function processInput(){  
     if (document.getElementById('regNo').value !=""){

          $.ajax({  
                type : 'GET',  
                url : "search/s",  
                data : { "regNo":$("#regNo").val()},
                success : function(studentResult) {  
                    //show your result
                   // alert("Value");
                    $('#displayArea').html(studentResult);  }  
            });  
        }else if (document.getElementById('studentName').value !=""){
            $.ajax({  
                type : 'GET',  
                url : "search/l",  
                data : { "studentName":$("#studentName").val(),
                success : function(result) {  
                    //show your result
                }}  
            });
        }  
}  
 </script>

template.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
   <%@ taglib uri="http://tiles.apache.org/tags-tiles" prefix="tiles"%>

<!DOCTYPE   html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

</head>
<center>
    <table width="750" border="0" cellpadding="2" cellspacing="2" align="center">
    <tr>
        <td><tiles:insertAttribute name="header" />
        </td>
    </tr>
    <tr>       
        <td><tiles:insertAttribute name="body" /></td>
    </tr>
    <tr>
        <td height="225"><tiles:insertAttribute name="footer" />
        </td>
    </tr>
</table>
</center>
</html>

numberResult.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>



 <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> 
 <c:out value="This is working"/>
  <c:out value="${studentResult.name}"/><br/>
  <c:out value="${studentResult.regNo}"/><br/>
    <c:out value="${studentResult.deptName}"/><br/>
      <c:out value="${studentResult.collName}"/><br/>

<div id="displayArea">
 <c:out value="${studentResult.name}"/><br/>
  <c:out value="${studentResult.regNo}"/><br/>
    <c:out value="${studentResult.deptName}"/><br/>
      <c:out value="${studentResult.collName}"/><br/>

</div>       

2) User enters the regNo in header.jsp,and I want the result to be shown in numberResult.jsp

3) My first url is localhost:8080/ProjectCtxt/mvc/template goes to homepage. When I enter regNo in the input field, my url in browser shows localhost:8080/ProjectCtxt/mvc/template/regNo=123&studentName= . And I am reaching the getStudentResult method as I could see my System.out in console, but I am not able to see the output in browser.

Since I am using tiles, I am not sure the problem is with tiles resolver or the AJAX. Could you please help me? Thanks.

PS: Please answer all questions if possible with numbers so that it will help others. Thanks.

UPDATE: I changed my header.jsp as follows and now I see "numberResult" in UI. But I don't see the numberResult jsp as body of template.jsp. I guess the "numberResult" text is returned to success part of AJAX.

  <input  type="text" id="regNo" name="regNo" size="30" maxLength="50" placeholder="Enter Register Number"></input>      
  <input  type="text" id="studentName" name="studentName" size="30" maxLength="50" placeholder="Enter Student Name"></input>
  <input id="inputFields" type="button" value="Search" />


<script>
$(document).ready(function(){
    $('#inputFields').click(function(){
       processInput();
    });
  });


 function processInput(){  
     if (document.getElementById('regNo').value !=""){

          $.ajax({  
                type : 'GET',  
                url : "search/s",  
                data : { "regNo":$("#regNo").val()},
                success : function(studentResult) {  
                    //show your result
                    alert("Value");
                    $('#displayArea').html(studentResult);  //this line displays text //"numberResult". But it doesn't change the jsp as well as the url. Now my url looks as //localhost:8080/mvc/template and the body of the jsp doesn't have numberResult.jsp
                    }  
            });  
        }else if (document.getElementById('studentName').value !=""){
            $.ajax({  
                type : 'GET',  
                url : "search/l",  
                data : { "studentName":$("#studentName").val(),
                success : function(result) {  
                    //show your result
                }}  
            });
        }  
}  
 </script>


<div id="displayArea">
 <c:out value="${studentResult.name}"/><br/>
  <c:out value="${studentResult.regNo}"/><br/>
    <c:out value="${studentResult.deptName}"/><br/>
      <c:out value="${studentResult.collName}"/><br/>

</div>  

解决方案

EDIT

Okay, I think I misunderstood the initial problem and the expected result. There are a couple problems with your approach.

You are trying to attach an AJAX event to a button that submits a form in a non-asynchronous manner. You are trying to display the response from the AJAX request in a JSP tag.

Both of these problems are issues of incompatible components. When you submit a form in a non-asynchronous manner, you are requesting a new page, which the browser loads, and your JavaScript does not have time to complete and display results. JSP tags can not be loaded and displayed asynchronously because they need to be processed on the server. This leaves you with two possible solutions:

1. Make the process completely asynchronous.

Remove the form tag, and leave the inputs and buttons:

<input  type="text" id="regNo" name="regNo" size="30" maxLength="50" placeholder="Enter Register Number"></input>      
<input  type="text" id="studentName" name="studentName" size="30" maxLength="50" placeholder="Enter Student Name"></input>
<button id="searchButton">Search</button>

Now there is no form to submit, so you don't have to worry about accidentally overriding your AJAX functionality. Update your JavaScript to read the input values, execute the proper AJAX request, and display the results:

$("#searchButton").on("click", function(){
   if ($('#regNo').val() !=""){

      $.ajax({  
            type : 'GET',  
            url : "search/s",  
            data : { "regNo":$("#regNo").val()},
            success : function(studentResult) {  
                $('#displayArea').html("<p>" + studentResult.id + "</p><p>" + studentResult.name + "</p><p>etc...</p>);  }  
        });  
    }else if (document.getElementById('studentName').value !=""){
        $.ajax({  
            type : 'GET',  
            url : "search/l",  
            data : { "studentName":$("#studentName").val(),
            success : function(result) {  
                //show your result
            }}  
        });
    }  
});

Make sure that the controller handling your AJAX method is set up to return an object JavaScript can understand. Spring should be able to serialize most objects you give it:

@RequestMapping(value = "/search/s", method = RequestMethod.GET, params = { "regNo" })
public @ResponseBody StudentResult getStudentResult(@RequestParam(value = "regNo") String regNo){
    return resultService.getStudentResult(regNo);
}

2. Make the process completely non-asynchronous

If you are set on using your JSP tag to display the data, you can scrap the AJAX and submit the form in the usual fashion:

<form method="POST">
    <input  type="text" id="regNo" name="regNo" size="30" maxLength="50" placeholder="Enter Register Number"></input>      
    <input  type="text" id="studentName" name="studentName" size="30" maxLength="50" placeholder="Enter Student Name"></input>
    <button id="searchButton">Search</button>
</form>

You can supply an action attribute if you would like the form to POST or perform a GET to a different URL. Create a single controller method to handle the submission:

@RequestMapping(value = "/someUrl", method = RequestMethod.POST)
public String getStudentResult(@RequestParam(value = "regNo", required = false) String regNo, @RequestParam(value = "studentName", required = false) String studentName, ModelMap model){
    if (regNo != null && !regNo.equals("")){
        model.addAttribute("studentResult",resultService.getStudentResult(regNo));      
        return "numberResult";
    } else if (studentName != null && !studentName.equals("")){
        model.addAttribute("nameResult", someOtherObject);
        return "nameResult";
    } else {
        model.addAttribute("errorMessage", "No form data supplied!");
        return "someOtherView";
    }
}

Now, as long as you have your views set up to accept the returned objects and map them in your JSTL, your tags should work just fine.