SpringMVC框架中,JSP页面刷新主要用到3种方法:
方法1.最简单的用<a>跳转
方法2.用AJAX异步刷新页面(画面部分刷新)
方法3.提交Form表单并刷新页面(画面全部刷新)

以下是例子:
方法1:在index.jsp用link跳转到downloadFromXml.jsp
方法2:downloadFromXml.jsp的download按钮是通过Ajax异步刷新页面
方法3:downloadFromXml.jsp的readXml按钮是直接submit Form表单

首先是配置文件:
先是web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
  <display-name>ProjectTest</display-name>

	<context-param>
	  <param-name>contextConfigLocation</param-name>
	  <param-value>classpath:spring/applicationContext-beans.xml</param-value>
	</context-param>
    
    <filter>
        <filter-name>encodingFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
        <init-param>
            <param-name>forceEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>

    <filter-mapping>
        <filter-name>encodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <!--hibernate -->
    <filter>
        <filter-name>openSessionInViewFilter</filter-name>
        <filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class>
        <init-param>
            <param-name>singleSession</param-name>
            <param-value>true</param-value>
        </init-param>
        <init-param>
            <param-name>sessionFactoryBeanName</param-name>
            <param-value>sessionFactory</param-value>
        </init-param>

    </filter>
    <filter-mapping>
        <filter-name>openSessionInViewFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    
    <!-- spring -->
	<servlet>
	  <servlet-name>springMVC</servlet-name>
	  <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
	  <init-param>
	    <param-name>contextConfigLocation</param-name>
	    <param-value>/WEB-INF/springmvc-servlet.xml</param-value>
	  </init-param>
	  <load-on-startup>2</load-on-startup>
	</servlet>
	<servlet-mapping>
	  <servlet-name>springMVC</servlet-name>
	  <url-pattern>/</url-pattern>
	</servlet-mapping>
  
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <welcome-file-list>
        <welcome-file>jsp/index.jsp</welcome-file>
    </welcome-file-list>
    
    <session-config>
        <session-timeout>30</session-timeout>
    </session-config>
</web-app>

然后是springmvc-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: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-3.0.xsd
                http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
                http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">

    <context:annotation-config/>
    
	<mvc:default-servlet-handler/>

    <!-- 默认访问跳转到登录页面 -->
    <mvc:view-controller path="/" view-name="redirect:/getData" />

    <!-- Scans the classpath of this application for @Components to deploy as beans -->
    <context:component-scan base-package="com.sun">
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>

    <!-- 静态资源访问 -->
    <mvc:resources mapping="/cms/**" location="/cms/" />
    <mvc:resources mapping="/images/**" location="/images/" />
    <mvc:resources mapping="/scripts/**" location="/scripts/" />
    <mvc:resources mapping="/styles/**" location="/styles/" />
    <mvc:resources mapping="/upload/**" location="/upload/" />

    <!-- 采用SpringMVC自带的JSON转换工具,支持@ResponseBody注解 -->
    <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
        <property name="messageConverters">
            <list>
                <ref bean="stringHttpMessageConverter" />
                <ref bean="jsonHttpMessageConverter" />
            </list>
        </property>
    </bean>

    <bean id="stringHttpMessageConverter" class="org.springframework.http.converter.StringHttpMessageConverter">
        <property name ="supportedMediaTypes">
            <list>
                <value>text/plain;charset=UTF-8</value>
            </list>
        </property>
    </bean>

    <!-- 避免IE执行AJAX时,返回JSON出现下载文件 -->
    <bean id="jsonHttpMessageConverter"
          class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
        <property name="supportedMediaTypes">
            <list>
                <value>text/html;charset=UTF-8</value>
            </list>
        </property>
    </bean>

    <!-- Application Message Bundle -->
    <bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
        <property name="basename" value="messages"/>
    </bean>

    <bean id="exceptionResolver" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
        <property name="exceptionMappings">
            <props>
                <prop key="org.springframework.dao.DataAccessException">dataAccessFailure</prop>
                <prop key="org.apache.shiro.authz.UnauthorizedException">authorizedFailure</prop>
            </props>
        </property>
    </bean>

    <!-- Configures the @Controller programming model -->
    <mvc:annotation-driven/>

    <!-- Configures Handler Interceptors -->
    <mvc:interceptors>
        <!-- Changes the locale when a 'locale' request parameter is sent; e.g. /?locale=de -->
        <bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor"/>
    </mvc:interceptors>

    <!-- Saves a locale change using a cookie -->
    <bean id="localeResolver" class="org.springframework.web.servlet.i18n.CookieLocaleResolver"/>

    <!-- Resolves view names to .jsp resources within the / directory -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>

</beans>
注意上面最后那段bean,
JSP文件可以放在WebRoot或者WEB-INF下面。
放在WebRoot下面任何人都可以访问,如果要控制访问则需要加过滤器。
放在WEB-INF下面的话,一般不能访问,需要在后台控制页面跳转。
有了上面那段bean的话,比如后台
<pre name="code" class="java">return "/downloadFromXml";

则直接会跳转到/WEB-INF/jsp/downloadFromXml.jsp这个页面。最后还有一个applicationContext-beans.xml:

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

<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:p="http://www.springframework.org/schema/p"
	xmlns:jee="http://www.springframework.org/schema/jee"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.0.xsd
		http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
		http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
		

	<context:property-placeholder location="classpath:config/jdbc.properties,classpath:config/hibernate.properties"/>
	
	<bean id="dataSource"
		class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    	<property name="driverClassName" value="${jdbc.driverClassName}"/>
    	<property name="url" value="${jdbc.url}"/>
    	<property name="username" value="${jdbc.username}"/>
    	<property name="password" value="${jdbc.password}"/>
	</bean>
	
	<bean id="sessionFactory"
		class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
		<property name="dataSource" ref="dataSource" />
		<property name="hibernateProperties">
			<props>
			
				<prop key="hibernate.dialect">${hibernate.dialect}</prop>
				<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
				<prop key="hibernate.format_sql">${hibernate.format_sql}</prop>
				<prop key="hibernate.generate_statistics">${hibernate.generate_statistics}</prop>
				<prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
				<prop key="hibernate.max_fetch_depth">${hibernate.max_fetch_depth}</prop>
				<prop key="c3p0.acquire_increment">${c3p0.acquire_increment}</prop>
				<prop key="c3p0.idle_test_period">${c3p0.idle_test_period}</prop>
				<prop key="c3p0.max_size">${c3p0.max_size}</prop>
				<prop key="c3p0.max_statements">${c3p0.max_statements}</prop>
				<prop key="c3p0.min_size">${c3p0.min_size}</prop>
				<prop key="c3p0.timeout">${c3p0.timeout}</prop>
				<prop key="javax.persistence.validation.mode">${javax.persistence.validation.mode}</prop>
				
			</props>
		</property>		
		<property name="packagesToScan">
			<list>
                <!--*********************************************************************************-->
				<!-- Important -->
				<!-- Here must be modified,you should include all the packages that contains 'impl' in your EDL-->
  				<value>com.sun</value>
			</list>
		</property>
	</bean>

	<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
		<property name="sessionFactory" ref="sessionFactory" />
        <property name="dataSource" ref="dataSource" />
	</bean>
		
 	<context:annotation-config />
    <!--*********************************************************************************-->
	<!-- Important  -->
	<!-- Here should be modified,you should assign to your basic package in your EDL-->
	<context:component-scan base-package="com.sun" />

	<tx:annotation-driven transaction-manager="transactionManager" />

</beans>

这里需要注意的也是最后一段

<context:component-scan base-package="com.sun" />

在使用spring组件注解的时候,context:component-scan扫描器可以实现bean的自动载入。

其他配置文件及Jar包略。
接下来是页面:

index.jsp:

<pre name="code" class="html"><pre name="code" class="html"><%@ page contentType="text/html;charset=UTF-8" language="java" %>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>Index</title>
  </head>
  
  <body>
  	<div>
  		<a target="_self" href="downloadpage.do">DownloadFromXml</a>
  	</div>
    <div id='divContext'>
    </div>
  </body>
</html>

由于我的index.jsp放在WebRoot下,而跳转的目标downloadFromXml.jsp放在WEB-INF下,所以需要downloadpage.do走一下后台跳转。如果都是放在WebRoot下的话,直接写downloadFromXml.jsp跳过去就可以了。

index的后台index.java代码如下:

package com.sun.index;

import java.util.LinkedList;
import java.util.List;

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

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class index{
	
    @RequestMapping("/downloadpage.do")
    public String downloadpage(HttpServletRequest request,HttpServletResponse response,ModelMap modelMap){   	
        return "/downloadFromXml";
    }
}

接下来是downloadFromXml.jsp:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ include file="../jsp/include/taglibs.jsp"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>    
    <title>Download From XML</title>
	
	<script src="./scripts/jquery-1.8.3.min.js" type="text/javascript"></script>
	<script type="text/javascript">
		$(function(){
  			$('#readXml').click(function(event){
                            $("#form").submit();
			});
		
  			$('#download').click(function(event){
	  		    document.getElementById("message").innerHTML = "";

	                    $.ajax({
	                        type: "POST",
	                        url: "download.do",
	                        data: {"cms":document.getElementById("cms").value},
	                        success: function(msg){
	                	    if(msg.status=="SUCCESS"){
	                	        //SUCCESS
	  			        document.getElementById("message").innerHTML = msg.value;
                    	            }else{
                    		        //FAILURE
	  				document.getElementById("message").innerHTML = msg.value;
	  			    }
	                        },
	                        error: function(msg){
	                	    //ERROR
	  			    document.getElementById("message").innerHTML = msg.value;
	                        }
            	            });
			});
		});
	</script>
  </head>
  
  <body>
  	<form:form id="form" name="copyrightList" modelAttribute="copyrightList" action="readxml.do" method="post" >
            <div>
                XML Root:<input name="xml" type="text" value="<c:url value='/cms/bq.xml'/>"><br>
                CMS Root:<input id="cms" name="cms" type="text" value="http://Test/ProjectTest/cms/123456wsxcde/esdgc56732/1.pdf"><br>
                <input type="button" id="readXml" value="Read XML">
                <input type="button" id="download" value="Download">
	  	<label id="message"></label>
            </div>
	    <div id='divContext'>
	        <c:forEach items="${copyrightList}" var="cr">
	        	<th>ID:${cr.ID}</th><br>
	        	<th>isActive:${cr.active}</th><br>
	        	<th>prdid:${cr.prdid}</th><br>
	        	<th>--------------------------------</th><br>
	        </c:forEach>
	    </div>
  	</form:form>
  </body>
</html>

注意,readXml按钮不在javascript里面用submit方法,而是把input的type改成submit也可以直接提交表单。

downloadFromXml的后台download.java代码如下:

package com.sun.xmldownload;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import com.sun.util.AjaxResult;
import com.sun.util.AjaxResultStatus;


@Controller
public class download{
	
    @RequestMapping("/readxml.do")
    public String readxml(HttpServletRequest request,HttpServletResponse response,ModelMap modelMap){
    	//Read XML
    	DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();  
        try  
        {  
            DocumentBuilder db = dbf.newDocumentBuilder();  
            Document doc = db.parse("http://localhost:8080" + request.getParameter("xml"));  
            
            NodeList bqinfoList = doc.getElementsByTagName("bqinfo");
        	
        	List<copyright> crList = new ArrayList<copyright>();
        	
        	for(int i=0; i<bqinfoList.getLength(); i++)
        	{
    	        copyright cr = new copyright();
    	        cr.setID(i);
    	        cr.setActive(true);
    	        
                Node bqinfo = bqinfoList.item(i);
                for (Node node = bqinfo.getFirstChild(); node != null; node = node.getNextSibling())  
                {  
                    if (node.getNodeType() == Node.ELEMENT_NODE)  
                    {  
                        String name = node.getNodeName();  
                        String value = node.getFirstChild().getNodeValue();

                        switch(name){
	                        case "prdid":
	                        	cr.setPrdid(value);
	                        	break;
                        }
                    }  
                }
    	        
    	        crList.add(cr);
        	}
        	
            modelMap.addAttribute("copyrightList", crList);
        }  
        catch (Exception e)  
        {  
            e.printStackTrace();  
        }  
        
        return "/downloadFromXml";
    }

    @Transactional
    @RequestMapping("/download.do")
    @ResponseBody
    public AjaxResult downloadFile(HttpServletRequest request,
            @RequestParam("cms") String cms){

        try {
            String filePath = "D:/apache-tomcat-7.0.26/webapps/ProjectTest/upload";   
            URL url = new URL(cms);   
            downloadFile(url,filePath);
        	
	    } catch (Exception e) {
	        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
	        return new AjaxResult(AjaxResultStatus.FAILURE,e.getMessage());
	    }
        
        return new AjaxResult(AjaxResultStatus.SUCCESS, "下载成功:" + cms);
    }
    
    public static void downloadFile(URL theURL, String filePath) throws IOException {  
    	File dirFile = new File(filePath);
    	
    	//文件路径不存在时,自动创建目录
    	if(!dirFile.exists()){
    		dirFile.mkdir();
    	}
    	
    	//从服务器上获取文件并保存
        URLConnection connection = theURL.openConnection();
        InputStream in = connection.getInputStream();  
        FileOutputStream os = new FileOutputStream(filePath+"\\1.pdf"); 
        byte[] buffer = new byte[4 * 1024];  
        int read;  
        while ((read = in.read(buffer)) > 0) {  
        	os.write(buffer, 0, read);  
        }  
        os.close();  
        in.close();
     }   
}

还用到了copyright.java

package com.sun.xmldownload;

import java.util.Date;

public class copyright{
	
	private long ID;
	private boolean isActive;
	private String prdid;
	
	public long getID() {
		return ID;
	}
	public void setID(long iD) {
		ID = iD;
	}
	public boolean getActive() {
		return isActive;
	}
	public void setActive(boolean isActive) {
		this.isActive = isActive;
	}
	public String getPrdid() {
		return prdid;
	}
	public void setPrdid(String prdid) {
		this.prdid = prdid;
	}
}

AjaxResult.java

package com.sun.util;

public class AjaxResult {


    AjaxResultStatus status;

    Object value;

    public AjaxResult(AjaxResultStatus status, Object value) {

        this.status = status;
        this.value = value;
    }
    public AjaxResult(AjaxResultStatus status) {

        this.status = status;
        this.value = null;
    }

    public AjaxResultStatus getStatus() {
        return status;
    }

    public void setStatus(AjaxResultStatus status) {
        this.status = status;
    }

    public Object getValue() {
        return value;
    }

    public void setValue(Object value) {
        this.value = value;
    }
}

AjaxResultStatus.java:

package com.sun.util;

public enum AjaxResultStatus {

    SUCCESS,FAILURE
}

主要实现了以下功能:

1.在index.jsp点击link,进入后台index.java的downloadpage方法,跳转到/WEB-INF/jsp/downloadFromXml.jsp页面

2.在downloadFromXml.jsp页面,点击ReadXML按钮,进入后台download.java的readxml方法,读取画面上XML Root下的XML文件,并把XML的内容显示到画面上,页面全部刷新。

3.在downloadFromXml.jsp页面,点击Download按钮,用AJAX方法异步刷新页面,进入后台download.java的downloadFile方法,从CMS Root路径(服务器路径)下,下载文件并保存到本地项目的upload文件夹下面,并将结果返回给页面,页面部分刷新。