`

springMvc helloworld及springMvc多种视图

 
阅读更多

使用eclipse maven 构建springMvc helloworld项目

忘记怎么建的话看看

http://limingnihao.iteye.com/blog/830409

写得非常好,需要注意的是

项目-->properties-->Deployment Assembly--> add --> java Build path entry -->把maven加上去

如果不选择这个的话,maven管理的jar包,发布的时候不能发布到tomcat里面去

 

 

maven: pom.xml内容

 

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>SpringMvcHelloWorld</groupId>
  <artifactId>SpringMvcHelloWorld</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>SpringMvcHelloWorld Maven Webapp</name>
  <url>http://maven.apache.org</url>
  <dependencies>
	   <dependency>
	      <groupId>org.springframework</groupId>
	      <artifactId>spring-context</artifactId>
	      <version>${spring.version}</version>
	   </dependency>
	   <dependency>
	      <groupId>org.spriengframework</groupId>
	      <artifactId>spring-context-support</artifactId>
	      <version>${spring.version}</version>
	   </dependency>
	   <dependency>
	      <groupId>org.springframework</groupId>
	      <artifactId>spring-core</artifactId>
	      <version>${spring.version}</version>
	   </dependency>
	   <dependency>
	      <groupId>org.springframework</groupId>
	      <artifactId>spring-orm</artifactId>
	      <version>${spring.version}</version>
	   </dependency>
	   <dependency>
	      <groupId>org.springframework</groupId>
	      <artifactId>spring-oxm</artifactId>
	      <version>${spring.version}</version>
	      <exclusions>
	      	<exclusion>
	      		<artifactId>commons-lang</artifactId>
	      		<groupId>commons-lang</groupId>
	      	</exclusion>
	      </exclusions>
	   </dependency>
	   <dependency>
	      <groupId>org.springframework</groupId>
	      <artifactId>spring-asm</artifactId>
	      <version>${spring.version}</version>
	   </dependency>
	    <dependency>
	      <groupId>org.springframework</groupId>
	      <artifactId>spring-jdbc</artifactId>
	      <version>${spring.version}</version>
	   </dependency>
	   <dependency>
	      <groupId>org.springframework</groupId>
	      <artifactId>spring-beans</artifactId>
	      <version>${spring.version}</version>
	   </dependency>
	   <dependency>
	      <groupId>org.springframework</groupId>
	      <artifactId>spring-tx</artifactId>
	      <version>${spring.version}</version>
	   </dependency>
	   <dependency>
	      <groupId>org.springframework</groupId>
	      <artifactId>spring-web</artifactId>
	      <version>${spring.version}</version>
	   </dependency>
	   <dependency>
	      <groupId>log4j</groupId>
	      <artifactId>log4j</artifactId>
	      <version>${log4j.version}</version>
	   </dependency>
      <dependency>
      	<groupId>org.springframework</groupId>
      	<artifactId>spring-webmvc</artifactId>
      	<version>${spring.version}</version>
      </dependency>
      <!-- spring oxm 返回 转换xml  -->
      <dependency>
      	<groupId>com.thoughtworks.xstream</groupId>
      	<artifactId>xstream</artifactId>
      	<version>${xstream.version}</version>
      </dependency>
      <dependency>
      	<groupId>net.sf.kxml</groupId>
      	<artifactId>kxml2</artifactId>
      	<version>${kxml2.version}</version>
      </dependency>
      <!-- spring oxm 返回 转换json  -->
      <dependency>
      	<groupId>org.codehaus.jackson</groupId>
      	<artifactId>jackson-core-asl</artifactId>
      	<version>${jackson.version}</version>
      </dependency>
      <dependency>
      	<groupId>org.codehaus.jackson</groupId>
      	<artifactId>jackson-mapper-asl</artifactId>
      	<version>${jackson.version}</version>
      </dependency>
      
      <dependency>
		 	<groupId>jstl</groupId>
		    <artifactId>jstl</artifactId>
	      <version>${jstl.version}</version>
	   </dependency> 
	  <dependency>
		    <groupId>javax.servlet</groupId>
		    <artifactId>servlet-api</artifactId>
		    <version>${servlet.version}</version>
		    <scope>provided</scope>
	   </dependency>
	    
	     <!--                      javaee                   -->
	      <dependency>
	       <groupId>javaee</groupId>
	       <artifactId>javaee-api</artifactId>
	       <version>${javaee.version}</version>
	    </dependency>
	    <dependency>
	       <groupId>commons-beanutils</groupId>
	       <artifactId>commons-beanutils-core</artifactId>
	       <version>${commons-beanutils.version}</version>
	    </dependency>
	    <dependency>
	       <groupId>org.apache.commons</groupId>
	       <artifactId>commons-lang3</artifactId>
	       <version>${commons-lang3.version}</version>
	    </dependency>
	    <dependency>
	       <groupId>net.sourceforge.jexcelapi</groupId>
	       <artifactId>jxl</artifactId>
	       <version>${jxl.version}</version>
	    </dependency>
	    <dependency>
	       <groupId>org.apache.poi</groupId>
	       <artifactId>poi</artifactId>
	       <version>${poi.version}</version>
	    </dependency>
	    <dependency>
	       <groupId>com.lowagie</groupId>
	       <artifactId>itext</artifactId>
	       <version>${itext.version}</version>
	    </dependency>
	    <dependency>
	       <groupId>com.lowagie</groupId>
	       <artifactId>iTextAsian</artifactId>
	       <version>${iTextAsian.version}</version>
	    </dependency>
	    <dependency>
	       <groupId>org.freemarker</groupId>
	       <artifactId>freemarker</artifactId>
	       <version>${freemarker.version}</version>
	    </dependency>
	 </dependencies>
	
  
    <repositories>
	   <repository>
	      <id>com.springsource.repository.maven.release</id>
	      <url>http://maven.springframework.org/release/</url>
	      <snapshots><enabled>false</enabled></snapshots>
	   </repository>	
	   <repository>
		   <id>JBoss repository</id>
		   <url>http://repository.jboss.org/nexus/content/groups/public/</url>
		</repository>
		<repository>
            <id>maven</id>
            <name>maven repository</name>
            <url>http://search.maven.org/#browse</url>
        </repository>
        <repository>
            <id>maven2-all</id>
            <name>maven2-all</name>
            <url>http://repo.fusesource.com/maven2-all</url>
        </repository>
	</repositories>
  		<properties>
  			<spring.version>3.1.2.RELEASE</spring.version>
  			<jstl.version>1.2</jstl.version>
  			<java-version>1.6</java-version>
  			<hibernate.version>4.0.0.Final</hibernate.version>
  			<mysql.version>5.1.21</mysql.version>
  			<jtds.version>1.2</jtds.version>
  			<slf4j.version>1.5.2</slf4j.version>
  			<javaee.version>5</javaee.version>
  			<jxl.version>2.6.12</jxl.version>
  			<poi.version>3.8</poi.version>
  			<itext.version>2.1.7</itext.version>
  			<iTextAsian.version>1.4.2</iTextAsian.version>
  			<freemarker.version>2.3.19</freemarker.version>
  			<proxool.version>0.9.1</proxool.version>
  			<aspectj.version>1.7.0</aspectj.version>
  			<cglib.version>2.2.2</cglib.version>
  			<xstream.version>1.4.3</xstream.version>
  			<log4j.version>1.2.14</log4j.version>
  			<kxml2.version>2.3.0</kxml2.version>
  			<jackson.version>1.7.3</jackson.version>
  			<servlet.version>2.5</servlet.version>
  			<commons-beanutils.version>1.8.3</commons-beanutils.version>
  			<commons-lang3.version>3.1</commons-lang3.version>
    		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		</properties>
  <build>
    <finalName>SpringMvcHelloWorld</finalName>
  </build>
</project>



 里面的repositories有几个常用的 maven仓库地址

 一般找jar包可以先去这几个地址里找到相应的

用得比较多的是 http://search.maven.org/#browse  这个 maven的中心仓库

有些时候通过maven下载下来的jar包是不正确的,如一个包应该是400k,下载下来的才20几k,用不了,这种情况的话就可以直接手动去下载了,然后放到你的仓库 对应的包里面去

如果是这个包有问题:

<dependency>
	       <groupId>net.sourceforge.jexcelapi</groupId>
	       <artifactId>jxl</artifactId>
	       <version>${jxl.version}</version>
</dependency>

就到相应maven仓库目录 D:\maven\local\repo  (我的)\net\sourceforge\jexcelapi\jxl\版本号

 

web.xml

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


	<!-- 中文乱码过滤器 -->
	<filter>
		<filter-name>encoding</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>encoding</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>
	
	<!-- SPRING配置 -->
	<context-param>
		<param-name>log4jConfigLocation</param-name>
		<param-value>classpath:log4j.properties</param-value>
	</context-param>
	<context-param>
		<param-name>contextConfigLocation</param-name>  
	    <param-value>
	   		classpath:applicationContext.xml
	    </param-value> 
	</context-param>
	<listener>
		<listener-class>
			org.springframework.web.context.ContextLoaderListener
		</listener-class>
	</listener>
	
	 
	<listener>
        <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
    </listener>
    
    <servlet>
        <servlet-name>spring</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <!--     
    	<init-param>  
	        <param-name>contextConfigLocation</param-name>  
	        <param-value>/WEB-INF/spring-Servlet.xml</param-value>  
    	</init-param>  
    --> 
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>spring</servlet-name>
        <url-pattern>*.do</url-pattern>
    </servlet-mapping>
	<!-- Spring 刷新Introspector防止内存泄露 -->
	<listener>
		<listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
	</listener>
    
    <!-- session有效时间 -->
	<session-config>
		<session-timeout>30</session-timeout>
	</session-config>
	  
	<welcome-file-list>
		<welcome-file>index.jsp</welcome-file>
	</welcome-file-list>
</web-app>

 

编写Spring配置文件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:p="http://www.springframework.org/schema/p" 
    xmlns:context="http://www.springframework.org/schema/context"
    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" >

   <context:component-scan base-package="com.loushi135.controller"/>
    
   <!-- 视图解释类org.springframework.web.servlet.view.InternalResourceViewResolver -->  
   <bean class="org.springframework.web.servlet.view.UrlBasedViewResolver">  
    <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />  
    <property name="prefix" value="/WEB-INF/jsp/"/>  
    <property name="suffix" value=".jsp"/><!--可为空,方便实现自已的依据扩展名来选择视图解释类的逻辑  -->  
   </bean>  
</beans>

 

编写HelloWorldController

 

package com.loushi135.controller;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;


@Controller
@RequestMapping("/hello")
public class HelloWorldController {
	
	@RequestMapping("/helloWorld")
    public ModelAndView helloWorld(ModelAndView mv) {
        String message = "Hello World, Spring 3.0!";
        mv = new ModelAndView("hello", "message", message);
       return mv;
    }
	 
    @RequestMapping("/helloWorld1")
    public String helloWorld1(HttpServletRequest request) {
        String message = "Hello World1111, Spring 3.0!";
        System.out.println(message);
        request.setAttribute("message", message);
       return "hello";//返回视图名hello 将会去找jsp/hello.jsp
    }
	   
    @RequestMapping("/helloWorld2")
    public String helloWorld2(ModelMap mm){
    	String message = "Hello World22222222, Spring 3.0!";
    	mm.addAttribute("message",message);
    	return "hello";
    }
    
}

    编写 view (hello.jsp)

 

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
    <title>${message}</title>
    <link rel="stylesheet" type="text/css" href="./xmlhttp/css/rime/rime.css" />
  </head>
  <body>
    ${message}  
  </body>
</html>

 效果:

分别请求

http://localhost:8080/SpringMvcHelloWorld/hello/helloWorld.do

http://localhost:8080/SpringMvcHelloWorld/hello/helloWorld1.do

http://localhost:8080/SpringMvcHelloWorld/hello/helloWorld2.do




其他视图: 返回 json,xml,excel,pdf,模板视图等

使用到了 返回json的话 需要加上spring orm包

<dependency>
	      <groupId>org.springframework</groupId>
	      <artifactId>spring-orm</artifactId>
	      <version>${spring.version}</version>
</dependency>
 

单独返回json的话:

<bean id="listJson" class="org.springframework.web.servlet.view.json.MappingJacksonJsonView" p:renderedAttributes="jsonData" />

 定义一个listJson  bean视图   返回"listJson"的都是,p:renderedAttributes="jsonData" 这个表示 通过modelMap 放进去的attributeName 是这个

json数据是{jsonData:{name:'123'}}  通过jquery请求时 var name = data.jsonData.name;

 

 

单独返回xml的话

 

<bean class="org.springframework.web.servlet.view.xml.MarshallingView"  p:marshaller-ref="xmlMarshaller"></bean> 
<bean id="xmlMarshaller" class="org.springframework.oxm.xstream.XStreamMarshaller">
		<property name="streamDriver">
			<bean class="com.thoughtworks.xstream.io.xml.StaxDriver"></bean>
		</property>
		<property name="annotatedClasses">
			<list>
				<value>com.loushi135.model.User</value>
			</list>
		</property>
		<!-- 指定使用xstream注解类,在类里设别名  -->
</bean>

 

使用注解 给User类加别名

 

package com.loushi135.model;

import com.thoughtworks.xstream.annotations.XStreamAlias;
@XStreamAlias("User")
public class User {
	/**
	 *  @XStreamAlias  为别名注解 作用于类或字段
	 *  @XStreamImplicit 隐藏集合类型
	 *  @XStreamOmitField 注解标志java对象的属性不出现在xml中
	 *  @XStreamAsAttribute设置为xml属性
	 *  @XStreamConverter(DateConverter.class) 注入日期转换器
	 */
	@XStreamAlias("name")
	private String name;
	private String password;
	
	public User() {
		super();
		// TODO Auto-generated constructor stub
	}

	public User(String name, String password) {
		super();
		this.name = name;
		this.password = password;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getPassword() {
		return password;
	}

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

 

混合多种视图技术

   以不同的MIME格式获取不同资源

 

 <bean class="org.springframework.web.servlet.view.BeanNameViewResolver" p:order="0" ></bean> 
<!-- 混合多种视图技术 -->
	<bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver"
		  p:order="1"
		  p:defaultContentType="text/html"
		  p:ignoreAcceptHeader="true"
		  p:favorPathExtension="false"
		  p:favorParameter="true"
		  p:parameterName="content"
	>
		<property name="mediaTypes">
			<map>
				<entry key="html" value="text/html"></entry>
				<entry key="xml" value="application/xml"></entry>
				<entry key="json" value="application/json"></entry>
			</map>
		</property>
		<property name="defaultViews">
			<list>
				<bean class="org.springframework.web.servlet.view.json.MappingJacksonJsonView" p:renderedAttributes="jsonData"></bean>
				<bean class="org.springframework.web.servlet.view.xml.MarshallingView" p:modelKey="xmlData" p:marshaller-ref="xmlMarshaller"></bean> 
				<!-- <bean class="com.loushi135.view.UserListExcelView"></bean> -->
			</list>
		</property>
	</bean>
	<bean id="xmlMarshaller" class="org.springframework.oxm.xstream.XStreamMarshaller">
		<property name="streamDriver">
			<bean class="com.thoughtworks.xstream.io.xml.StaxDriver"></bean>
		</property>
		<property name="annotatedClasses">
			<list>
				<value>com.loushi135.model.User</value>
			</list>
		</property>
		<!-- 指定使用xstream注解类,在类里设别名  -->
	</bean>
   <!-- 视图解释类org.springframework.web.servlet.view.InternalResourceViewResolver -->  
    <bean class="org.springframework.web.servlet.view.UrlBasedViewResolver"  p:order="100" >  
    	<property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />  
    	<property name="prefix" value="/WEB-INF/jsp/"/>  
    	<property name="suffix" value=".jsp"/><!-- 可为空,方便实现自已的依据扩展名来选择视图解释类的逻辑  -->  
    </bean> 
    <bean id="userListExcelView" class="com.loushi135.view.UserListExcelView"></bean>
    <bean id="userListPoiExcelView" class="com.loushi135.view.UserListPoiExcelView"></bean>
    <bean id="userListPdfView" class="com.loushi135.view.UserListPdfView"></bean>
    <!-- 使用 BeanNameViewResolver  返回视图'userListExcelView'就进入userListExcelView处理 --> 

 BeanNameViewResolver 使用bean id作为视图解析器 如上面的 userListExcelView等

  p:order  这是给视图解析设置排序的,值小的先匹配

 p:parameterName="content" 设置前台请求传过来的mime类型的参数 如'url?content=json'

 property mediaTypes里的 key是content=json里的json.  value是'application/json' 在相应的视图解析器里都有对应的

  如AbstractExcelView,AbstractJExcelView 里对应的是"application/vnd.ms-excel" 返回excel的视图

     AbstractPdfView则对应的是"application/pdf"

     MappingJacksonJsonView对应的是"application/json"

    MarshallingView对应的是"application/xml"

 SpringMvc官方文档: http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/mvc.html#mvc-viewresolver-resolver

 导出excel ,pdf参考:http://liuzidong.iteye.com/blog/1071823

UserController类

 

package com.loushi135.controller;

import java.util.ArrayList;
import java.util.List;

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

import com.loushi135.model.User;

@Controller
@RequestMapping("/user")
public class UserController {

	private List<User> userList = new ArrayList<User>();

	public UserController() {
		super();
		for(int i = 0;i<5;i++){
			User user = new User();
			user.setName("loushi"+i);
			user.setPassword("password"+i);
			userList.add(user);
		}
	}
	@RequestMapping("/userIndex")
	public String toUserIndex(){
		return "userIndex";
	}
	/**
	 * 返回json数据
	 * @param mm
	 * @return
	 */
	@RequestMapping("/getJson")
	public String getJson(ModelMap mm){
		mm.addAttribute("jsonData", userList);
		return "listJson";
	}
	
	/**
	 * 返回xml数据
	 * @param mm
	 * @return
	 */
	@RequestMapping("/getXml")
	public String getXml(ModelMap mm){
		mm.addAttribute("xmlData", userList);
		return "listXml";
	}
	/**
	 * 返回excel数据
	 * @param mm
	 * @return
	 */
	@RequestMapping("/getExcel")
	public String getExcel(ModelMap mm){
		mm.addAttribute("userList",userList);
		return "userListExcelView";
	}
	
	/**
	 * 返回excel数据
	 * @param mm
	 * @return
	 */
	@RequestMapping("/getPoiExcel")
	public String getPoiExcel(ModelMap mm){
		mm.addAttribute("userList",userList);
		return "userListPoiExcelView";
	}
	/**
	 * 返回pdf数据
	 * @param mm
	 * @return
	 */
	@RequestMapping("/getPdf")
	public String getPdf(ModelMap mm){
		mm.addAttribute("userList",userList);
		return "userListPdfView";
	}
}

 

 jxl返回Excel视图

UserListExcelView.java

 

package com.loushi135.view;

import java.util.List;
import java.util.Map;

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

import jxl.WorkbookSettings;
import jxl.format.Alignment;
import jxl.format.VerticalAlignment;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
import jxl.write.biff.RowsExceededException;

import org.apache.commons.beanutils.PropertyUtils;
import org.springframework.web.servlet.view.document.AbstractJExcelView;

import com.loushi135.model.User;

public class UserListExcelView extends AbstractJExcelView {
	
	private String[] columnNames = new String[] {"姓名","密码"};  
	private String[] dbColumnNames = new String[] {"name","password"};  
	private Integer[] columnWidths = new Integer[] { 40, 40 }; 
	@Override
	protected void buildExcelDocument(Map<String, Object> model,
			WritableWorkbook workbook, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		// TODO Auto-generated method stub
		try { 
			response.setCharacterEncoding("UTF-8");
			response.setContentType("application/ms-excel");
			String fileName = "用户列表excel.xls";
//			response.setContentType("APPLICATION/OCTET-STREAM");  
	        response.setHeader("Content-Disposition", "inline; filename="+new String(fileName.getBytes(),"iso8859-1"));  
	        String sheetName = "用户信息";
	        // 全局设置  
	        WorkbookSettings setting = new WorkbookSettings();  
	        java.util.Locale locale = new java.util.Locale("zh", "CN");  
	        setting.setLocale(locale);  
	        setting.setEncoding("UTF-8");  
	        // 创建工作薄  
//	        workbook = Workbook.createWorkbook(os); // 建立excel文件  
	        // 创建第一个工作表  
	        jxl.write.WritableSheet ws = workbook.createSheet(sheetName, 1); // sheet名称  
			List<User> userList = (List<User>)model.get("userList");
			 // 添加标题  
	        addColumNameToWsheet(ws);
	        writeContext(ws, userList);  
		} catch (Exception e) {  
	        e.printStackTrace();  
	    } 
//		finally {  
	        // 写入文件  
//	        try {  
//	        	workbook.write();  
//	        	workbook.close();  
//	            os.flush();  
//	            os.close();  
//	        } catch (WriteException e) {  
//	            e.printStackTrace();  
//	        } catch (IOException e) {  
//	            e.printStackTrace();  
//	        }  
//	    }  
	}  
	
    private <T> void writeContext(WritableSheet wsheet, List<T> list) {  
        jxl.write.Label wlabel = null;  
        jxl.write.WritableCellFormat wcf = getFormat();  
        int rows = list.size();  
        int cols = dbColumnNames.length;  
        String columnName = null;  
        Object value = null;  
        try {  
            for (int i = 0; i < rows; i++) {  
                T t = (T) list.get(i);                
                for (int j = 0; j < cols; j++) {  
                    columnName = dbColumnNames[j].toLowerCase();  
                    value = PropertyUtils.getProperty(t, columnName);  
                    wlabel = new jxl.write.Label(j, (i + 1), value + "", wcf);  
                    wlabel = new jxl.write.Label(j, (i + 1), value + "");  
                    wsheet.addCell(wlabel);  
                }
            }  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
  
    }  
  
    // 添加标题样式  
    private void addColumNameToWsheet(jxl.write.WritableSheet wsheet)  
            throws RowsExceededException, WriteException {  
  
        // 设置excel标题  
        jxl.write.WritableFont wfont = getFont();  
        if (null == wfont) {  
            wfont = new WritableFont(WritableFont.ARIAL,  
                    WritableFont.DEFAULT_POINT_SIZE, WritableFont.BOLD);  
  
        }  
        jxl.write.WritableCellFormat wcfFC = getFormat();  
        if (null == wcfFC) {  
            wcfFC = new jxl.write.WritableCellFormat(wfont);  
            try {  
                wcfFC.setWrap(true);// 自动换行  
                wcfFC.setAlignment(Alignment.CENTRE);  
                wcfFC.setVerticalAlignment(VerticalAlignment.CENTRE);// 设置对齐方式  
            } catch (WriteException e) {  
                e.printStackTrace();  
            }  
        }  
  
        jxl.write.Label wlabel1 = null;  
        String[] columNames = columnNames;  
        if (null == columNames)  
            return;  
        int colSize = columNames.length;  
  
        Integer[] colsWidth = columnWidths;  
        if (null == colsWidth) {  
            colsWidth = new Integer[colSize];  
            for (int i = 0; i < colSize; i++) {  
                colsWidth[i] = 20;  
            }  
        }  
  
        int temp = 0;  
        String colName = null;  
        for (int i = 0; i < colSize; i++) {  
            colName = columNames[i];  
            if (null == colName || "".equals(colName))  
                colName = "";  
            wlabel1 = new jxl.write.Label(i, 0, colName, wcfFC);  
            wsheet.addCell(wlabel1);  
            temp = colsWidth[i].intValue();  
            // 默认设置列宽  
            temp = temp == 0 ? 20 : temp;  
            wsheet.setColumnView(i, temp);  
        }  
  
    }  
  
    // 设置格式  
    private WritableCellFormat getFormat() {  
  
        jxl.write.WritableFont wfont = getFont();  
        jxl.write.WritableCellFormat wcfFC = new jxl.write.WritableCellFormat(  
                wfont);  
        try {  
            wcfFC.setWrap(true);  
            wcfFC.setAlignment(Alignment.CENTRE);  
            wcfFC.setVerticalAlignment(VerticalAlignment.CENTRE);  
        } catch (WriteException e) {  
            e.printStackTrace();  
        }  
        return wcfFC;  
    }  
  
    // 设置字体  
    private WritableFont getFont() {  
        return new WritableFont(WritableFont.ARIAL,  
                WritableFont.DEFAULT_POINT_SIZE, WritableFont.BOLD);  
    }  
  
}

 

 

Poi返回excel

UserListPoiExcelView.java

 

package com.loushi135.view;

import java.util.List;
import java.util.Map;

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

import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.web.servlet.view.document.AbstractExcelView;

import com.loushi135.model.User;

public class UserListPoiExcelView extends AbstractExcelView {

	@Override
	protected void buildExcelDocument(Map<String, Object> model,
			HSSFWorkbook workbook, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		// TODO Auto-generated method stub
		String fileName = "用户列表excel.xls";
        // 设置response方式,使执行此controller时候自动出现下载页面,而非直接使用excel打开  
        response.setContentType("APPLICATION/OCTET-STREAM");  
        response.setHeader("Content-Disposition", "inline; filename="+new String(fileName.getBytes(),"iso8859-1"));  
        List<User> userList = (List<User>) model.get("userList");     
        // 产生Excel表头  
        HSSFSheet sheet = workbook.createSheet("用户列表");  
        HSSFRow header = sheet.createRow(0); // 第0行  
        // 产生标题列  
        header.createCell((short) 0).setCellValue("name");  
        header.createCell((short) 1).setCellValue("password");  
        HSSFCellStyle cellStyle = workbook.createCellStyle();  
  
        // 填充数据  
        int rowNum = 1;  
        for (User user:userList) {  
            HSSFRow row = sheet.createRow(rowNum++);  
            row.createCell((short) 0)  
                    .setCellValue(user.getName().toString());  
            row.createCell((short) 1).setCellValue(user.getPassword());  
        }  
  
//        // 列总和计算  
//        HSSFRow row = sheet.createRow(rowNum);  
//        row.createCell((short) 0).setCellValue("TOTAL:");  
//        String formual = "SUM(D2:D" + rowNum + ")"; // D2到D[rowNum]单元格起(count数据)  
//        row.createCell((short) 3).setCellFormula(formual);  
	}


}

 

返回pdf视图

UserListPdfView.java

 

package com.loushi135.view;

import java.awt.Color;
import java.util.List;
import java.util.Map;

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

import org.springframework.web.servlet.view.document.AbstractPdfView;

import com.loushi135.model.User;
import com.lowagie.text.Document;
import com.lowagie.text.Paragraph;
import com.lowagie.text.pdf.BaseFont;
import com.lowagie.text.pdf.PdfPCell;
import com.lowagie.text.pdf.PdfPTable;
import com.lowagie.text.pdf.PdfWriter;

public class UserListPdfView extends AbstractPdfView {

	@Override
	protected void buildPdfDocument(Map<String, Object> model,
			Document document, PdfWriter writer, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		// TODO Auto-generated method stub
		String fileName = "用户列表pdf.pdf";
        // 设置response方式,使执行此controller时候自动出现下载页面,而非直接使用excel打开  
        response.setContentType("APPLICATION/OCTET-STREAM");  
        response.setHeader("Content-Disposition", "inline; filename="+new String(fileName.getBytes(),"iso8859-1"));    
        List<User> userList = (List<User>) model.get("userList");            
        //显示中文  
        BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);   
        com.lowagie.text.Font FontChinese = new com.lowagie.text.Font(bfChinese, 12, com.lowagie.text.Font.NORMAL );          
    
        //创建一个有2列的表格
        PdfPTable table = new PdfPTable(2);
        //定义一个表格单元
        PdfPCell cell = new PdfPCell(new Paragraph("header with colspan 2"));
        //定义一个表格单元的跨度
        cell.setColspan(2);
        //定义单元格的背景颜色
        cell.setBackgroundColor(new Color(0xC0, 0xC0, 0xC0));
        table.addCell(cell);
        PdfPCell headName = new PdfPCell(new Paragraph("姓名",FontChinese));
        //定义单元格的框颜色
        headName.setBorderColor(new Color(255, 0, 0));
        PdfPCell headPassword = new PdfPCell(new Paragraph("密码",FontChinese));
        headPassword.setBorderColor(new Color(255, 0, 0));
        table.addCell(headName);
        table.addCell(headPassword);
        for (User user:userList) {   
        	 PdfPCell name = new PdfPCell(new Paragraph(user.getName(),FontChinese));
        	 PdfPCell password = new PdfPCell(new Paragraph(user.getPassword(),FontChinese));
        	 table.addCell(name);
        	 table.addCell(password);
        }  
        document.add(table);
	}

}

 

 

userIndex.jsp页面

 

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
    <title>视图</title>
<script type="text/javascript"
	src="${pageContext.request.contextPath}/js/jquery-1.8.1.js"></script>
<script type="text/javascript">
    	var _ctx="${pageContext.request.contextPath}";
	  	$(document).ready(function(){
	  	   $("#json").click(function(event){
	  	       $.post(
	  	    		   _ctx+"/user/getJson.do?content=json",//请求使用content=?来实现restful风格,来选择进入什么视图
	  	    		   {},
	  	    		   function(data){
	  	    			   var jsonData = data.jsonData;
	  	    			   var message = "";
	  	    			   $(jsonData).each(function(i,item){//解析json
	  	    				 message +=" 用户名:"+item.name+"  密码:"+item.password;
	  	    			  });
	  	    			   alert(message);
	  	    		   },
	  	    		   'json'
	  	    		   );
	  	   });
	  	   
	  	 $("#xml").click(function(event){
	  	       $.post(
	  	    		   _ctx+"/user/getXml.do?content=xml",
	  	    		   {},
	  	    		   function(data){
	  	    			 var message = "";
	  	    			$(data).find("User").each(function(i,item){//解析xml
	  	    					var name = $(item).children('name').text();
	  	    					var password = $(item).children('password').text();
	  	    					message +=" 用户名:"+name+"  密码:"+password;
	  	    			   });
		  	    		alert(message);
	  	    		   },
	  	    		   'xml'
	  	    		   );
	  	   });
	  	 
	  	 });
  	</script>
  </head>
  <body>
     <input type="button" value="请求返回json" id="json"/>
     <br/>
     <input type="button" value="请求返回xml" id="xml"/>
     <br>
     <input type="button" value="请求jxl返回excel" id="jxlExcel" onclick="location='${pageContext.request.contextPath}/user/getExcel.do'"/>
     <br/>
     <input type="button" value="请求poi返回excel" id="poiExcel" onclick="location='${pageContext.request.contextPath}/user/getPoiExcel.do'"/>
     <br/>
     <input type="button" value="请求返回pdf" id="pdf" onclick="location='${pageContext.request.contextPath}/user/getPdf.do'"/>
     <br/>
     <input type="button" value="请求返回模板" id="template"/>
  </body>
</html>

 

 

通过http://localhost:8080/SpringMvcHelloWorld/user/userIndex.do 进入 userIndex.jsp


请求Json

请求xml

请求excel


 

 

 

  • 大小: 58.4 KB
  • 大小: 16.8 KB
  • 大小: 15.5 KB
  • 大小: 16.3 KB
  • 大小: 21.4 KB
  • 大小: 26.7 KB
  • 大小: 38.9 KB
  • 大小: 32.3 KB
  • lib.zip (7.1 MB)
  • 下载次数: 75
分享到:
评论

相关推荐

    SpringMVC_HelloWorld:SpringMVC的一个hello world的demo,开启学习SpringMVC的大门

    SpringMVC_HelloWorld SpringMVC的一个hello world的demo,开启学习SpringMVC的大门。 SpringMVC 框架提供了一个DispatchServlet作为前端控制器来分派请求,同时提供灵活的配置处理程序映射,视图解析,语言环境和...

    SpringMVC概述与HelloWorld实现

    SpringMVC的具体实现步骤:加入Spring所依赖的jar包、在web.xml文件中配置DispatcherServlet、加入SpringMVC的配置文件,并配置视图解析器、创建请求处理器类和处理器,并标识为处理器、编写视图页面……

    SpringMVC-1 概述与HelloWorld实现

    SpringMVC的具体实现步骤:加入Spring所依赖的jar包、在web.xml文件中配置DispatcherServlet、加入SpringMVC的配置文件,并配置视图解析器、创建请求处理器类和处理器,并标识为处理器、编写视图页面……

    SpringMVC4超权威教程

    2.SpringMVC 的 HelloWorld 3.使用 @RequestMapping 映射请求 • 4.映射请求参数 & 请求头 • 5.处理模型数据 • 6.视图和视图解析器 7.RESTful CRUD • 8.SpringMVC 表单标签 &处理静态资源 • 9.数据转换 & 数据...

    0325_SpringMVC.html

    HelloWorld细节: 一:运行流程; * 1)、客户端点击链接会发送 http://localhost:8080/springmvc/hello 请求 * 2)、来到tomcat服务器; * 3)、SpringMVC的前端控制器收到所有请求; * 4)、来看请求地址和...

    SpringMvc的HelloWord简单完整的项目源码

    这边基于springframework4.1.4的注释@RequestMapping、@Controller方式mvc实现,通过简单helloworld例子完整全面的将整个配置过程及相关细节,同时关于freemarker视图简单整合

    SpringMVC ModelAttribute详解.docx

    被@ModelAttribute注释的方法会在此...在这个代码中,访问控制器方法helloWorld时,会首先调用populateModel方法,将页面参数abc(/helloWorld.ht?abc=text)放到model的attributeName属性中,在视图中可以直接访问。

    Spring MVC 入门实例

    jsp 文件只作为渲染(或称为视图 View)模板使用. 好了, 我们开始吧. 首先我们需要一个放在 WEB-INF 目录下的 web.xml 文件: web.xml: 1 2 3 4 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" ...

    SpringBoot新手学习手册

    2.3、编写HelloWorld服务 3 2.4、@RestController 4 2.5、@EnableAutoConfiguration 4 2.6 SpringApplication.run(HelloController.class, args); 4 2.7、SpringBoot启动方式1 4 2.8、SpringBoot启动方式2 4 ...

Global site tag (gtag.js) - Google Analytics