Pular para o conteúdo principal

Checking out what is new with Servlet 3.0


To com preguiça de traduzir o post abaixo e coloco na integra o artigo extraído de um blog, quem visita o meu blog deve saber ler em inglês , logo não vejo grandes complicações. O assunto é interessante , é utilizar anotations para substituir as declarações de deploy em arquivos XML em projetos java web, enjoy .

With the JEE6 specification hitting the market, some major changes have taken place with respect to how you would approach developing applications in the enterprise application world. In this article i would be touching upon a few changes that were done with respect to web application development.



First things first, say good bye to the web.xml deployment descriptor (at least for parts of it). Well its not like it is deprecated, but with the rise of the usage of annotations and their usage, the new specification allows us to define our configuration using annotations, though some thing such as welcome file lists, context params etc will still need to go inside your web.xml . Annotations available for use are;
@WebServlet
@WebFilter
@WebInitParam
@WebListener
@MultipartConfig

In this article i would be checking out the @WebServlet and @WebFilter annotations. Let us see how we would usually map a servlet in the web.xml era;
1   <servlet>
2       <servlet-name>myservlet</servlet-name>
3       <servlet-class>com.example.MyServlet</servlet-class>
4   </servlet>
5 
6<servlet-mapping>
7 <servlet-name>myservlet</servlet-name>
8 <url-pattern>/hello</url-pattern>
9</servlet-mapping>
With the Servlet 3.0 spec, now configuring a Servlet is as easy as annotating a class that extends HttpServlet. Lets see how that looks like;
01@WebServlet('/student')
02public class StudentServlet extends HttpServlet{
03 
04 /**
05  *
06  */
07 private static final long serialVersionUID = 2276157893425171437L;
08 
09 @Override
10 protected void doPost(HttpServletRequest arg0, HttpServletResponse arg1)
11   throws ServletException, IOException {
12  StringBuilder response = new StringBuilder(500);
13  response.append('').append('Registered Student : ').append(arg0.getParameter('txtName')).append('
');
14  arg1.getOutputStream().write(response.toString().getBytes());
15  arg1.getOutputStream().flush();
16  arg1.getOutputStream().close();
17 }
18}
All you need is the @WebServlet annotation. In order for this to work, the class should reside either in the WEB-INF/classes folder or within a jar residing in the WEB-INF/lib folder. Next up lets see how we would configure a filter with annotations.
01package com.blog.example.servlettest;
02 
03import java.io.IOException;
04 
05import javax.servlet.Filter;
06import javax.servlet.FilterChain;
07import javax.servlet.FilterConfig;
08import javax.servlet.ServletException;
09import javax.servlet.ServletRequest;
10import javax.servlet.ServletResponse;
11import javax.servlet.annotation.WebFilter;
12 
13@WebFilter('/student')
14public class StudentFilter implements Filter{
15 
16 @Override
17 public void destroy() {
18 }
19 
20 @Override
21 public void doFilter(ServletRequest arg0, ServletResponse arg1,
22   FilterChain arg2) throws IOException, ServletException {
23 
24  if(arg0.getParameter('txtName')==null || arg0.getParameter('txtName').isEmpty())
25  {
26   arg1.getWriter().append('Invalid name supplied');
27   arg1.getWriter().flush();
28   arg1.getWriter().close();
29  }
30  else
31  {
32   arg2.doFilter(arg0, arg1);
33  }
34 }
35 
36 @Override
37 public void init(FilterConfig arg0) throws ServletException {
38  // TODO Auto-generated method stub
39 
40 }
41 
42}
Again very easy. Just a mere annotation to notify it as a filter. Note that here we implement the Filter interface. The value or theurlPatterns should be available. Using both is illegal as per the specification.

In the coming weeks i will cover the other new annotations available with JEE6 and wrap up with a comprehensive example using them together. If JEE6 will replace Spring framework or not is not a question by itself, but i believe we would be seeing some fierce competition between the two. The annotations vs xml debate is more or less resolved with people with preference for each holding their own grounds. I believe a little bit from both worlds would be beneficial for an application.

You can download and run a sample example which i have uploaded here. If you are using JBoss-AS7 all you need to do is run the application server on standalone mode and do a mvn package jboss-as:deploy and point the browser to http://localhost:{port}/servlet3.0.

That is it for today. Thank you for reading and if you have any comments or suggestions for improvement, please do leave by a comment.

Have a good day all!!
Reference: Checking out what is new with Servlet 3.0 from our JCG partner Dinuka Arseculeratne at the My Journey Through IT blog.

Comentários

Postagens mais visitadas deste blog

Video Aulas de Java já disponíveis no 4Shared

Turma segue as video aulas já disponíveis para download no 4Shared , espero que vocês gostem das aulas e por favor postem um comentario no blog dizendo o que vc's acharam preciso desse feed back para o constante aprimoramento das aulas . Basta escolher o arquivo clickar  no link para download ( tenha paciencia os arquivos são grandes ) <p>&lt;p&gt;&amp;amp;amp;amp;lt;p&amp;amp;amp;amp;gt;&amp;amp;amp;amp;amp;amp;amp;lt;br&amp;amp;amp;amp;amp;amp;amp;gt;&amp;amp;amp;amp;amp;amp;amp;lt;br&amp;amp;amp;amp;amp;amp;amp;gt;se&amp;amp;amp;amp;lt;/p&amp;amp;amp;amp;gt;&lt;/p&gt;</p> Se a Janela de Download acima não funcionar tente acessar os arquivos usando o seguinte link http://www.4shared.com/dir/34812571/bf01348d/VideoAulas.html Bom estudo  :-)

Notícias da UFSC » UFSC é segunda universidade brasileira melhor colocada no Webometrics

Notícias da UFSC » UFSC é segunda universidade brasileira melhor colocada no Webometrics : A Universidade Federal de Santa Catarina passou à segunda instituição brasileira melhor qualificada no  Ranking Web of World Universities , sendo a primeira universidade federal brasileira no levantamento . No primeiro lugar geral se mantém a USP. No ranking passado, publicado no mês de janeiro, a UFSC ocupava a quarta posição. Na classificação para a América Latina, em que figurava como quinta universidade,  passou a terceira colocada. E no ranking mundial está entre as cem universidades do mundo: subiu da 129ª posição para a 98ª. Harvard University, Massachusetts Institute of Technology e Stanford University se mantêm no topoda classificação mundial. Entre as brasileiras, lideram aUniversidade de São Paulo (USP), UFSC e Universidade Estadual de Campinas (Unicamp)

Serialização de objetos I - Salvando objetos em arquivos

Serialização: como salvar seus objetos Java par utilizar quando precisar  Serialização de objetos é a possibilidade de salvar uma cópia completa de um objeto ou de uma coleção de objetos em um fluxo de saída (arquivo externo), de modo que o objeto pode ser recriado a partir da cópia serializada  quando necessário . A serialização de objetos Java,  fornece um recurso para transformar um grupo ou um único objeto em um fluxo de bits, ou um array de bytes para armazenar ou enviar pela rede,  de modo que o  referido fluxo de bits ou uma matriz de bytes pode ser transformado novamente em objetos Java. O processo de serialização também é conhecido como marshaling de um objeto, e de-serialização é conhecido como un-marshaling. Assim a serialização oferece os seguintes benefícios: Um sistema para persistência de objetos, ou seja, escrever as suas propriedades em arquivos externos ou discos, ou salvá-las em um banco de dados. Um sistema para chamadas d...