`

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
分享到:
评论

相关推荐

    IDEA SpringMVC HelloWorld 实例

    对于初学者来说,使用 IDEA 创建一个简单的 SpringMVC HelloWorld 示例是一个很好的起点,能够快速熟悉这两个工具的使用。 首先,让我们了解 SpringMVC 的核心组件和工作流程: 1. **DispatcherServlet**:这是 ...

    SpringMVC-Helloworld

    通过这个HelloWorld实例,开发者可以逐步了解SpringMVC的基本工作流程,包括请求的接收、控制器的调用、数据的传递以及视图的渲染。掌握这些基础知识后,可以进一步学习更复杂的应用场景,如表单处理、文件上传下载...

    springmvc_helloWorld

    通过这个"springmvc_helloWorld"项目,你可以学习到Spring MVC的基本架构、控制器的编写、视图的创建以及数据绑定等核心概念。这将为你后续深入学习Spring MVC框架以及开发复杂的Web应用奠定基础。

    SpringMVC HelloWorld

    这个“SpringMVC HelloWorld”项目为我们展示了Spring MVC的基本工作流程:从HTTP请求到达DispatcherServlet,通过处理器映射器找到对应的Controller方法,执行业务逻辑后,返回视图名,最后由视图解析器定位并渲染...

    springmvc-helloworld

    本教程将通过 "springmvc-helloworld" 这个示例项目,帮助你了解如何搭建 SpringMVC 环境以及其工作原理。 ### 一、SpringMVC 架构 SpringMVC 的核心组件包括 DispatcherServlet、Model、ViewResolver 和 ...

    Maven+SpringMVC的入门级HelloWorld实例

    例如,在创建一个简单的HelloWorld项目时,我们会在pom.xml中声明SpringMVC的依赖: ```xml &lt;groupId&gt;org.springframework &lt;artifactId&gt;spring-webmvc &lt;version&gt;5.3.22 ``` **SpringMVC简介** SpringMVC...

    SpringMVC HelloWorld Restfull 项目

    【SpringMVC HelloWorld Restful 项目详解】 SpringMVC 是 Spring 框架的一个模块,主要负责处理 Web 请求。它是一个轻量级的、模型-视图-控制器(MVC)架构的实现,广泛应用于现代 Java Web 开发。在本项目中,...

    SpringMVC 3.0 HelloWorld 源码 (Maven)

    在本项目“SpringMVC 3.0 HelloWorld”中,我们将深入探讨如何使用Maven构建一个简单的Spring MVC应用。Maven是一个项目管理和综合工具,它帮助开发者管理依赖、构建项目并遵循标准的开发过程。 首先,我们需要了解...

    springmvc项目helloworld

    在这个"springmvc项目helloworld"中,我们将深入理解Spring MVC的基本概念、工作原理以及如何创建一个简单的Hello World应用程序。 1. **Spring MVC 概述** - Spring MVC 是 Spring 框架为Web开发提供的模块,它...

    SpringMVC HelloWorld工程源码

    这个“SpringMVC HelloWorld工程源码”是一个基础教程,旨在帮助初学者理解SpringMVC的工作原理和基本配置。让我们深入探讨其中涉及的关键概念和知识点。 1. **MVC架构模式**:MVC模式将应用程序分为三个主要组件...

    springmvc入门helloworld

    在"springmvc入门helloworld"这个主题中,我们将探讨如何从零开始搭建一个简单的Spring MVC项目,展示其基本工作流程和关键组件。以下是详细的知识点讲解: 1. **Spring MVC 概述** - Spring MVC 是Spring框架的一...

    SpringMvc HelloWorld

    在创建一个 Spring MVC 的 "Hello, World!" 程序时,通常需要以下步骤: 1. **环境准备**:确保已安装 JDK 和 Apache Maven 或 Gradle,这两个是构建工具,用来管理项目的依赖。 2. **创建 Maven 项目**:使用 IDE...

    SpringMVC------从HelloWorld开始

    让我们从一个简单的"HelloWorld"示例开始,深入了解SpringMVC的工作原理。 首先,创建一个`HelloWorld`控制器是开始任何SpringMVC项目的第一步。在Java中,我们通常会创建一个继承自`org.springframework....

    SpringMVC HelloWorld程序

    7. **运行并测试**:启动Tomcat服务器,通过浏览器访问`http://localhost:8080/HelloWorld/hello`(假设你的请求映射为"/hello"),如果一切配置正确,你应该能看到“Hello World”显示在页面上。 通过这个简单的...

    springmvc注解版 helloworld

    在这个"springmvc注解版 helloworld"项目中,我们将深入探讨如何使用注解来配置和实现一个简单的Hello World应用。这个项目特别适合初学者入门,因为每个步骤都有详细的注释,确保你能理解每一行代码的作用。 首先...

    SpringMVC Helloworld AbstractController 实例

    SpringMVC是Spring框架的一个模块,专为构建Web应用程序提供模型-视图-控制器(MVC)架构。在本实例中,我们关注的是`AbstractController`,这是一个在早期Spring MVC版本中使用的基类,用于简化控制器的实现。然而...

    SpringMVC跑Hello World

    在“Springmvc_1_helloworld”这个项目中,我们可以找到上述所有配置和代码的示例。通过运行这个项目,我们可以验证SpringMVC如何处理一个简单的“Hello World”请求,并了解其背后的机制。这只是一个起点,...

Global site tag (gtag.js) - Google Analytics