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

Projetos em Sala de aula

A educação baseada em projetos vem sendo usada como uma metodologia poderosa para melhor preparar estudantes do século 21, já que leva os alunos a trabalhar em conjunto, se organizar, pesquisar e executar harmonicamente. Porém, antes de levar a metodologia para a sala de aula, será que os professores sabem como e quais projetos trabalhar em suas disciplinas? Uma dessas novidades é o  PBLU (Project Based Learning University ), plataforma gratuita que ajuda a capacitar professores para o uso de projetos em suas disciplinas, como uma forma de agregar conteúdo e motivar os estudantes. Conheça os oito pontos principais para um bom programa de aprendizagem baseada em projeto: Ter conteúdo relevante.   O objetivo da abordagem é trabalhar os conceitos-chave das disciplinas acadêmicas a partir de um projeto. Desenvolver habilidades para o século 21.   Ao longo do projeto, os alunos deverão buscar uma resposta a um problema. Para isso, eles deverão buscar referências...

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  :-)

Sistemas distribuidos: Enviando mensagens TCP Parte II - Servidor

Igual ao servidor UDP esse servidor só vai receber a mensagem e envia-la de volta , ou seja é um servidor de ECO mas com boa vontade basta fazer algumas alterações que vc tem um servidor de chat :-) . Server TCP: import java.net.*; import java.io.*; public class TCPServer { public static void main(String[] args) { try { int serverPort = 7896; ServerSocket listenSocket = new ServerSocket(serverPort); //socket de escuta o socket que vai atender as requisições while(true){ Socket client = listenSocket.accept( ); Connection c = new Connection(client); //precisamos criar a classe conection que vai //inicializar nossas threads para atender a cada requisição } } catch (IOException e) { System.out.println("Listem :" + e.getMessage( )); } }//fim do main }//fim da classe Depois de fin...