spring boot示例学习

spring boot可以实现零xml来使用spring web框架。

下面是我自己写的示例:

1、下面这个类会被org.springframework.web.SpringServletContainerInitializer搜索到,加载上下文

下面三行是启动Tomcat打印的日志

十月 16, 2016 7:13:27 下午 org.apache.catalina.core.ApplicationContext log
信息: Spring WebApplicationInitializers detected on classpath: [com.nding.spring.boot.UserInitialize@16277983]
log4j:WARN No appenders could be found for logger (org.springframework.web.context.support.StandardServletEnvironment).
log4j:WARN Please initialize the log4j system properly.
十月 16, 2016 7:13:28 下午 org.apache.catalina.core.ApplicationContext log
信息: Initializing Spring root WebApplicationContext
十月 16, 2016 7:13:30 下午 org.apache.catalina.core.ApplicationContext log
信息: Initializing Spring FrameworkServlet 'dispatcher'


getServletMappings()是对DispatchServlet设置的url-pattern。

package com.nding.spring.boot;

import java.util.EnumSet;

import javax.servlet.DispatcherType;
import javax.servlet.Filter;
import javax.servlet.FilterRegistration;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.FilterRegistration.Dynamic;
import javax.servlet.annotation.HandlesTypes;

import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

/**
 * 查看spring源码了解到DispatchServlet注册在org.springframework.web.servlet.support.AbstractDispatcherServletInitializer.registerDispatcherServlet(ServletContext)
 * servlet name为dispatcher。
 * 若要添加过滤器,需要重写org.springframework.web.servlet.support.AbstractDispatcherServletInitializer.getServletFilters()
 * @author luoboge
 *
 */
public class UserInitialize extends
		AbstractAnnotationConfigDispatcherServletInitializer {

	@Override
	protected Class[] getRootConfigClasses() {
		
		return new Class[]{UserConfiguration.class};
	}

	@Override
	protected Class[] getServletConfigClasses() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	protected String[] getServletMappings() {
		
		return new String[]{"/"};
	}
	
	/**
	 * 添加过滤器。
	 * 由于org.springframework.web.servlet.support.AbstractDispatcherServletInitializer.registerServletFilter(ServletContext, Filter)
	 * registration.addMappingForServletNames(getDispatcherTypes(), false, getServletName());
	 * 使用的是根据servlet名字来设置过滤器,而servlet名字为dispatcher
	 */
	@Override
	protected Filter[] getServletFilters() {
		// 字符编码过滤器
		CharacterEncodingFilter characterEncodingFilter=new CharacterEncodingFilter();
		characterEncodingFilter.setEncoding("UTF-8");
		characterEncodingFilter.setForceEncoding(true);
		return new Filter[]{characterEncodingFilter};
	}
	
//	@Override
//	public void onStartup(ServletContext servletContext)
//			throws ServletException {
//		
//		super.onStartup(servletContext);
//		
//		// 添加过滤器
//		CharacterEncodingFilter characterEncodingFilter=new CharacterEncodingFilter();
//		characterEncodingFilter.setEncoding("UTF-8");
//		characterEncodingFilter.setForceEncoding(true);
//		FilterRegistration.Dynamic registration = servletContext.addFilter("characterEncodingFilter", characterEncodingFilter);
//		registration.setAsyncSupported(isAsyncSupported());
//		registration.addMappingForUrlPatterns(getDispatcherTypes(), false, "/*");
//	}


	private EnumSet getDispatcherTypes() {
		return isAsyncSupported() ?
			EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD, DispatcherType.INCLUDE, DispatcherType.ASYNC) :
			EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD, DispatcherType.INCLUDE);
	}
}

2、配置类。是通过上面类的getRootConfigClasses()关联的。


package com.nding.spring.boot;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;

@Configuration
@EnableWebMvc
@ComponentScan(basePackages="com.nding.spring.boot")
public class UserConfiguration {

}

3、Controller类,通过注解实现。


@RequestMapping中若不添加
 produces="text/plain;charset=utf-8"返回string会出现乱码。

而request.getCharacterEncoding();
response.getCharacterEncoding();这两行是对request传递的参数和response输出的流有效

package com.nding.spring.boot;

import java.io.IOException;
import java.io.PrintWriter;

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

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

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

	@RequestMapping(value="/sayhello", produces="text/plain;charset=utf-8")
	@ResponseBody
	public static String sayHello(String name, HttpServletRequest request, HttpServletResponse response){
		request.getCharacterEncoding();
		response.getCharacterEncoding();
		response.setContentType("text/plain;charset=utf-8");
		
//		response.setCharacterEncoding("utf-8"); // 仅对向response流中写入字符生效。Controller中返回string不生效
//		PrintWriter writer = null;
//		try {
//			writer = response.getWriter();
//			writer.write("中文");
//		} catch (IOException e) {
//			
//			e.printStackTrace();
//		}finally {
//			writer.close();
//		}
    	/**
    	 *   
			      
			      
			          
			                 
			                    
			                    text/plain;charset=UTF-8    
			                    text/html;charset=UTF-8    
			                    
			                
			          
			      
			  
    	 */
		return "Hello, " + name +"!";
	}
}


你可能感兴趣的:(J2EE)