SpringMVC 自定义视图

一、为什么使用自定义视图

SpringMVC如果使用Excel视图等,必须使用自定义视图。

二、如何使用自定义视图

1、自定义一个实现View接口的类,添加@Component注解,将其放入SpringIOC容器,如下所示:

package com.jd.view;

import java.util.Map;

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

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.View;

@Component // 将自定义视图放入IOC容器中
public class ToView implements View{
	
	public String getContentType() {
		return "text/html";
	}
	
	public void render(Map<String, ?> model, HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		response.getWriter().print("Hello World.");
	}
}

2、配置视图解析器,使用视图名字解析视图,如下所示:


<bean class="org.springframework.web.servlet.view.BeanNameViewResolver">
	
	<property name="order" value="0">property>
bean>

① 从发布Java Web项目—>执行DispatcherServlet类onRefresh(ApplicationContext context)方法—>执行DispatcherServlet类initStrategies(ApplicationContext context)方法—>执行DispatcherServlet类initViewResolvers(ApplicationContext context)方法,该方法实例化Spring配置文件中配置的ViewResolver并将其赋值给viewResolvers成员变量。

② BeanNameViewResolver 的源代码如下:

package org.springframework.web.servlet.view;

import java.util.Locale;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.core.Ordered;
import org.springframework.web.context.support.WebApplicationObjectSupport;
import org.springframework.web.servlet.View;
import org.springframework.web.servlet.ViewResolver;

public class BeanNameViewResolver extends WebApplicationObjectSupport implements ViewResolver, Ordered {//实现了ViewResolver接口
	
	private int order = Integer.MAX_VALUE;  // default: same as non-Ordered
	
	public void setOrder(int order) {
		this.order = order;
	}
	
	@Override
	public int getOrder() {
		return this.order;
	}
	
	@Override
	public View resolveViewName(String viewName, Locale locale) throws BeansException {// 解析视图
		ApplicationContext context = getApplicationContext();
		if (!context.containsBean(viewName)) {
			if (logger.isDebugEnabled()) {
				logger.debug("No matching bean found for view name '" + viewName + "'");
			}
			// Allow for ViewResolver chaining...
			return null;
		}
		if (!context.isTypeMatch(viewName, View.class)) {
			if (logger.isDebugEnabled()) {
				logger.debug("Found matching bean for view name '" + viewName +
						"' - to be ignored since it does not implement View");
			}
			// Since we're looking into the general ApplicationContext here,
			// let's accept this as a non-match and allow for chaining as well...
			return null;
		}
		return context.getBean(viewName, View.class);// 根据视图名直接从IOC容器中获取视图对象
	}
}

BeanNameViewResolver的resolveViewName方法被DispatcherServlet内如下方法调用:

protected View resolveViewName(String viewName, Map<String, Object> model, Locale locale,
			HttpServletRequest request) throws Exception {
	
	for (ViewResolver viewResolver : this.viewResolvers) {
		View view = viewResolver.resolveViewName(viewName, locale);
		if (view != null) {
			return view;
		}
	}
	return null;
}

3、Controller定义Handler方法,该方法返回自定义视图的名字(默认情况下为首字母小写的类名),如下所示:

package com.jd.userinfo;

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

@Controller
@RequestMapping("/userinfo")
public class UserInfoController {
     
	@RequestMapping("/toView.do")
	public String toView() {
		System.out.println("Handler Methods");
		return "toView";// toView是自定义视图类ToView在IOC容器中默认的名字
	}
}

执行步骤:
发送/userinfo/toView.do请求——>执行Handler方法,返回toView——>依据名字从Spring IoC容器获取ToView对象——>执行ToView对象render方法——>页面显示Hello World。

三、自定义Excel视图

1、添加jar包,如下所示:

<dependency>
	<groupId>org.apache.poigroupId>
       	<artifactId>poiartifactId>
       	<version>3.11version>
dependency>

2、自定义Excel视图,如下所示:

package com.jd.view;

import java.io.OutputStream;
import java.util.List;
import java.util.Map;

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

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.view.document.AbstractXlsView;

import com.jd.vo.UserInfo;

@Component
public class ExcelView extends AbstractXlsView {
     
	@Override
	protected void buildExcelDocument(Map<String, Object> model, Workbook workbook, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String fileName = "用户信息.xls";
		response.setCharacterEncoding("UTF-8");
		response.setContentType("application/ms-excel");
		response.setHeader("Content-Disposition", "inline; filename=" + new String(fileName.getBytes(), "iso8859-1"));
		OutputStream outputStream = response.getOutputStream();
         
		@SuppressWarnings("unchecked")
		List<UserInfo> userInfoes = (List<UserInfo>) model.get("userInfoes");
		// 产生Excel表头
		Sheet sheet = workbook.createSheet("基本信息");
		sheet.setColumnWidth(0, 35*256);//设置第一列列宽
		sheet.setColumnWidth(1, 10*256);//设置第二列列宽
		sheet.setColumnWidth(2, 15*256);//设置第三列列宽
		sheet.setColumnWidth(3, 30*256);//设置第四列列宽
		
		CellStyle cellStyle = workbook.createCellStyle();
		cellStyle.setAlignment(CellStyle.ALIGN_CENTER); // 水平布局:居中
		cellStyle.setVerticalAlignment(CellStyle.VERTICAL_CENTER);// 垂直布局:居中
		
		// 标题列
		Row header = sheet.createRow(0);
		header.setRowStyle(cellStyle);
		header.setHeightInPoints(20);// 设置行高
		Cell idCell = header.createCell(0);
		idCell.setCellStyle(cellStyle);//设置单元格样式
		idCell.setCellValue("ID");//设置单元格内容
		Cell nameCell = header.createCell(1);
		nameCell.setCellStyle(cellStyle);
		nameCell.setCellValue("姓名");
		Cell mobileCell = header.createCell(2);
		mobileCell.setCellStyle(cellStyle);
		mobileCell.setCellValue("手机号");
		Cell addressCell = header.createCell(3);
		addressCell.setCellStyle(cellStyle);
		addressCell.setCellValue("家庭地址");

		int rowNumber = 1;
		for (UserInfo userInfo : userInfoes) {
			Row row = sheet.createRow(rowNumber++);
			row.setHeightInPoints(18);// 设置行高
			row.createCell(0).setCellValue(userInfo.getId());
			row.createCell(1).setCellValue(userInfo.getName());
			row.createCell(2).setCellValue(userInfo.getMobile());
			row.createCell(3).setCellValue(userInfo.getAddress());
		}
		workbook.write(outputStream);
		outputStream.flush();
		outputStream.close();
	}
}

3、配置视图解析器,如下所示:


<bean class="org.springframework.web.servlet.view.BeanNameViewResolver">
	
	<property name="order" value="0">property>
bean>

4、Controller定义Handler方法,该方法中指定响应Excel视图,如下所示:

package com.jd.userinfo;

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

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

import com.jd.vo.UserInfo;

@Controller
@RequestMapping("/userinfo")
public class UserInfoController {
     
	@RequestMapping("/excel.do")
	public ModelAndView excel() {
		ModelAndView modelAndView = new ModelAndView("excelView");
		
		List<UserInfo> userInfoes = new ArrayList<UserInfo>();
		String id = UUID.randomUUID().toString();
		userInfoes.add(new UserInfo(id, "Lucy", "18898763401", "吉林省长春市宽城区"));
		id = UUID.randomUUID().toString();
		userInfoes.add(new UserInfo(id, "Kate", "17749219035", "河南省郑州市高新区升龙又一城"));
        	modelAndView.addObject("userInfoes", userInfoes);
		return modelAndView;
	}
}

执行步骤:
发送/userinfo/excel.do请求——>执行Handler方法,返回excelView——>依据名字从Spring IoC容器获取View对象——>执行ExcelView类中方法,导出Excel文件。

你可能感兴趣的:(SSM)