1. 程式人生 > >Annotation(註解)代替web.xml完成servlet配置

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

一般我們新建一個servlet總要完成對應的環境配置,我們先來看看一個簡單得web.xml配置servlet:

<servlet>
    <servlet-name>FindAllProvinceServlet</servlet-name>
    <servlet-class>com.canyugan.web.servlet.FindAllProvinceServlet</servlet-class>
 </servlet>
 <servlet-mapping>
    <servlet-name>FindAllProvinceServlet</servlet-name>
    <url-pattern>/FindAllProvinceServlet</url-pattern>
 </servlet-mapping>

對的你沒看錯,類路徑稍微寫錯或者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() 
	{
		
	}
}
是不是感覺方便多了呢?