JSP頁面刷新與參數傳遞的幾種方法

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包略。
詳細可以參照sample:
代碼Sample

接下來是頁面:

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文件夾下面,並將結果返回給頁面,頁面部分刷新。

代碼可以參照:
代碼Sample

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章