根据不同的请求后缀返回不同的View
例如:/test.xml 返回xml数据,/test.json 返回Json数据
package com.lss.web.controller;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import com.lss.web.viewresolver.MultipleViewResolver;
@Controller
public class ResolverController {
@Autowired
private MultipleViewResolver resolver;
@RequestMapping("/test")
public String test() {
return "test";
}
@RequestMapping("/test.json")
public String testJson() {
return "test.json";
}
@RequestMapping("/test.xml")
public String getSampleJsp() {
return "test.xml";
}
@RequestMapping(value = "/test1")
public ModelAndView test1(HttpServletRequest request, ModelAndView mv) {
mv.setViewName("test" + getPostfix(request));
return mv;
}
private String getPostfix(HttpServletRequest request) {
String uri = request.getRequestURI();
if (uri.indexOf(".") != -1) {
String postfix = uri.substring(uri.indexOf(".") + 1);
if (resolver.checkPostfix(postfix)) {
return "." + postfix;
}
}
return "";
}
}
package com.lss.web.view; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.web.servlet.view.AbstractUrlBasedView; public class GenericFileView extends AbstractUrlBasedView { // default content type private final static String CONTENT_TYPE = "text/plain"; // content of http response private String responseContent; public GenericFileView() { super(); setContentType(CONTENT_TYPE); } @Override public void setContentType(String contentType) { super.setContentType(contentType); } @Override protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) throws Exception { response.setContentType(getContentType()); response.getWriter().write(this.responseContent); response.getWriter().close(); } /** * Set http request content * * @param responseContent */ public void setResponseContent(String responseContent) { this.responseContent = responseContent; } }
package com.lss.web.viewresolver; import java.io.ByteArrayOutputStream; import java.io.InputStream; import java.util.Locale; import java.util.logging.Logger; import org.springframework.core.Ordered; import org.springframework.core.io.Resource; import org.springframework.web.servlet.View; import org.springframework.web.servlet.view.AbstractCachingViewResolver; import com.lss.web.view.GenericFileView; public class GenericFileViewResolver extends AbstractCachingViewResolver implements Ordered { private Logger logger = Logger.getLogger(GenericFileViewResolver.class.getName()); private int order = Integer.MIN_VALUE; // requested file location under web app private String location; private String viewName; public void setViewName(String viewName) { this.viewName = viewName; } public void setOrder(int order) { this.order = order; } public void setLocation(String location) { this.location = location; } public int getOrder() { return this.order; } @Override protected View loadView(String viewName, Locale locale) throws Exception { if (location == null) { throw new Exception("No location specified for GenericFileViewResolver."); } String requestedFilePath = location + viewName; Resource resource = null; // String url = ""; try { logger.finest(requestedFilePath); resource = getApplicationContext().getResource(requestedFilePath); // url = resource.getURI().toString(); } catch (Exception e) { // this exception should be catched and return null in order to call // next view resolver logger.finest("No file found for file: " + requestedFilePath); return null; } logger.info("Requested file found: " + requestedFilePath + ", viewName:" + viewName); // get view from application content, scope=prototype GenericFileView view = this.getApplicationContext().getBean(this.viewName, GenericFileView.class); view.setUrl(requestedFilePath); view.setResponseContent(inputStreamToString(resource.getInputStream(), "UTF-8")); return view; } final static int BUFFER_SIZE = 4096; /** * Convert Input to String based on specific encoding * * @param in * @param encoding * @return * @throws Exception */ public static String inputStreamToString(InputStream in, String encoding) throws Exception { ByteArrayOutputStream outStream = new ByteArrayOutputStream(); byte[] data = new byte[BUFFER_SIZE]; int count = -1; while ((count = in.read(data, 0, BUFFER_SIZE)) != -1) outStream.write(data, 0, count); data = null; return new String(outStream.toByteArray(), encoding); } }
package com.lss.web.viewresolver; import java.util.Locale; import java.util.Map; import org.springframework.core.Ordered; import org.springframework.util.StringUtils; import org.springframework.web.servlet.View; import org.springframework.web.servlet.ViewResolver; import org.springframework.web.servlet.view.AbstractCachingViewResolver; public class MultipleViewResolver extends AbstractCachingViewResolver implements Ordered { private int order = Integer.MIN_VALUE; public int getOrder() { return order; } public void setOrder(int order) { this.order = order; } private Map<String, ViewResolver> resolvers; public void setResolvers(Map<String, ViewResolver> resolvers) { this.resolvers = resolvers; } @Override protected View loadView(String viewName, Locale locale) throws Exception { String fileExtension = StringUtils.getFilenameExtension(viewName); // return null to invoke next resolver if no extension found if (fileExtension == null) { return null; } // get resolver by extension ViewResolver resolver = resolvers.get(fileExtension); // return null to invoke next resolver if no resolver found return resolver == null ? null : resolver.resolveViewName(viewName, locale); } public boolean checkPostfix(String postfix) { return resolvers.containsKey(postfix); } }
将以下配置假如到Servlet.XML
<!-- Customized View Resolver to resolve .json, .xml and .properties files -->
<bean id="viewResolver"
class="com.lss.web.viewresolver.MultipleViewResolver" p:order="0">
<property name="resolvers">
<map>
<entry key="json">
<bean class="com.lss.web.viewresolver.GenericFileViewResolver"
p:location="/WEB-INF/json/" p:cache="false">
<property name="viewName" value="jsonFileView"/>
</bean>
</entry>
<entry key="xml">
<bean class="com.lss.web.viewresolver.GenericFileViewResolver"
p:location="/WEB-INF/xml/" p:cache="false">
<property name="viewName" value="xmlFileView"/>
</bean>
</entry>
</map>
</property>
</bean>
<!-- View Resolver for JSP files -->
<bean id="jspViewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:order="1">
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
<bean id="xmlFileView" class="com.lss.web.view.GenericFileView"
p:contentType="text/xml" p:url="" scope="prototype"/>
<bean id="jsonFileView" class="com.lss.web.view.GenericFileView"
p:contentType="application/json" p:url="" scope="prototype"/>