Login | Register   
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


advertisement
 

Servlet 3.0: A Sneak Preview : Page 2

Find out which features in the upcoming Servlet 3.0 specification will affect a major change in the way developers build Java web applications.


advertisement

Annotations in Servlet

One of the major changes in Servlet 3.0 is the support for annotations. Using annotations to define Servlets and filters eliminates the need for the Servlet/Filter entry in the web deployment descriptor (web.xml).

@WebServlet

To define a Servlet component in a web application, you use @WebServlet. You use it on a class that extends the javax.servlet.http.HttpServlet class. The @WebServlet annotation has many attributes, such as name, urlPatterns, and initParams, which you use to define the Servlet's behavior. For the url pattern, you must specify it either with the annotation itself or with an attribute of the annotation.

You can define a simple Servlet with @WebServlet as follows:



@WebServlet(name = "GetQuoteServlet", urlPatterns = {"/getquote"} ) public class GetQuoteServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out = response.getWriter(); try { String symbol = request.getParameter("symbol"); out.println("<h1>Stock Price is</h1>" + StockQuoteBean.getPrice(symbol); } finally { out.close(); } } } public class StockQuoteBean { private StockQuoteServiceEntity serviceEntity = new StockQuoteServiceEntity(); public double getPrice(String symbol) { if(symbol !=null ) { return serviceEntity.getPrice(symbol); } else { return 0.0; } } }

You can modify the same Servlet to address requests from multiple URLs with the annotation attributes.

@WebServlet(name = "GetQuoteServlet", urlPatterns = {"/getquote", "/stockquote"} ) public class GetQuoteServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out = response.getWriter(); try { String symbol = request.getParameter("symbol"); out.println("<h1>Stock Price is</h1>" + StockQuoteBean.getPrice(symbol); } finally { out.close(); } } }

@WebFilter

You use the @WebFilter annotation to define a filter. This annotation also has optional parameters. You can use @WebFilter on any class that implements the javax.servlet.Filter interface. Similar to the @WebServlet annotation, you must specify the url pattern on this annotation as well.

@WebFilter(filterName = "AuthenticateFilter", urlPatterns = {"/stock.jsp", "/getquote"}) public class AuthenticateFilter implements Filter { public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { String username = ((HttpServletRequest) request).getParameter("uname"); String password = ((HttpServletRequest) request).getParameter("password"); if (username == null || password == null) { ((HttpServletResponse) response).sendRedirect("index.jsp"); } if (username.equals("admin") && password.equals("admin")) { chain.doFilter(request, response); } else { ((HttpServletResponse) response).sendRedirect("index.jsp"); } } public void destroy() { } public void init(FilterConfig filterConfig) { } }

@WebInitParam

You use the @WebInitParam annotation to specify the init parameters to the Servlet or filter. Alternatively, you can specify the init parameters with the initParam attributes of the @WebServlet and @WebFilter annotations.

@WebServlet(name = "GetQuoteServlet", urlPatterns = {"/getquote"}) @WebInitParam(name = "default_market", value = "NASDAQ") public class GetQuoteServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); try { String market = getInitParameter("default_market"); String symbol = request.getParameter("symbol"); out.println("<h1>Stock Price in " + market + " is</h1>" + StockQuoteBean.getPrice(symbol, market)); } finally { out.close(); } } }

Here is an alternate example that uses the @WebInitParam annotation as part of the @WebServlet and @WebFilter initParams attribute:

@WebServlet(name = "GetQuoteServlet", urlPatterns = {"/getquote"}, initParams={@WebInitParam(name="default_market", value="NASDAQ")} ) public class GetQuoteServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); try { String market = getInitParameter("default_market"); String symbol = request.getParameter("symbol"); out.println("<h1>Stock Price in " + market + " is</h1>" + StockQuoteBean.getPrice(symbol, market)); } finally { out.close(); } } }

@WebListener

You use the @WebListener annotation on a class that acts as a listener to various web application events in a given web application context. You can use @WebListener to annotate a class that implements ServletContextListener, ServletContextAttributeListener, ServletRequestListener, ServletRequestAttributeListener, HttpSessionListener, and HttpSessionAttributeListener. Here is an example with ServletContextListener:

@WebListener public class QuoteServletContextListener implements ServletContextListener { public void contextInitialized(ServletContextEvent sce) { ServletContext context = sce.getServletContext(); context.setInitParameter(“default_market”, “NASDAQ”); } public void contextDestroyed(ServletContextEvent sce) { } }

@MultipartConfig

Use the @MultipartConfig annotation to specify the multipart MIME type request for the Servlet. The MIME attachments are read from the request object.

The Metadata and Common Annotations

Apart from the Servlet-specific annotations described above, Servlet 3.0 continues to support all the annotations that are defined as part of JSR 175 (Java Metadata Specification) and JSR 250 (Common Annotations for the Java Platform), including:
  • Annotations related to security, such as @DeclareRoles and @RolesAllowed
  • Annotations to use EJB, such as @EJB and @EJBs
  • Annotations for resource injection, such as @Resource and @Resources
  • Annotations to use JPA, such as @PersistenceContext, @PersistenceContexts, @PersistenceUnit, and @PersistenceUnits
  • Life cycle annotations, such as @PostConstruct and @PreDestroy
  • Annotations to provide references to web services, such as @WebServiceRef and @WebServiceRefs

Annotations or web.xml?

The introduction of annotations makes the web deployment descriptor (web.xml) optional when configuring web components. However, if you have to make any changes or updates to the configuration, you can still use the deployment descriptor. The container will decide to use web.xml or annotations depending on the value for the element metadata-complete in the web.xml descriptor. If the attribute has a value true, then the container does not process the annotations and web fragments; the deployment descriptor is the only source for all the metadata information. The container will process annotations and web fragments only if the element metadata-complete is not there or does not have a value true.



Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap