Annotation(注解)代替web.xml完成servlet配置

一般我们新建一个servlet总要完成对应的环境配置,我们先来看看一个简单得web.xml配置servlet:


    FindAllProvinceServlet
    com.canyugan.web.servlet.FindAllProvinceServlet
 
 
    FindAllProvinceServlet
    /FindAllProvinceServlet
 

对的你没看错,类路径稍微写错或者copy少了字母你就蒙蔽了...所以我们的超人Annotation来了!来看看同一个servlet我们的超人是怎么做的。

首先我们压迫了解一个机制(不是机智),Servlet注解技术:

@WebServlet   取代servlet配置
@WebFilter       取代filter配置
@WebInitParam    取代初始化参数配置(servlet、filter)
@WebListener      取代listener配置


然后我们来看看注解后的代码:

@WebServlet(urlPatterns={"/one","/two"})//{}里可以设置多个servlet名
public class HelloServlet extends HttpServlet 
{
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException 
	{
		response.getWriter().print("I am Annotation servlet build by 参与感");
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException 
	{
		doGet(request, response);
	}
}

@WebFilter(urlPatterns="/*")//多个servlet要拦截的话,加*
public class EncodingFilter implements Filter 
{

	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) 
			throws IOException, ServletException 
	{
		//编码
		response.setContentType("text/html;charset=utf-8");
		chain.doFilter(request, response);
	}

	
	public void init(FilterConfig fConfig) throws ServletException 
	{
		
	}

	@Override
	public void destroy() 
	{
		
	}
}



是不是感觉方便多了呢?


你可能感兴趣的:(JavaWeb,参与感Thinking,in,Java)