Quinta-feira Ago 07, 2008

Deploying Web Services on other Servers using NetBeans

Hey everybody!

A friend made a question on the WebServices and JSP on NetBeans 6.1 post about deploying Web Services on other servers, like Tomcat. It could be, actually, a problem, because many will say that you won't be able to deploy WS on Tomcat. That is not true. If you are using a version of JDK greater than 1.6.0_04, nothing needs to be done, you will just have to use TomCat on your project. If you are using older versions, you may check this link http://wiki.netbeans.org/FaqEndorsedDirTomcat.

I will do some demonstration here using Tomcat 6.0.16 that cames bundled with NetBeans 6.1 using JDK version 1.6.0_07 and JBOSS version 4.2.2 that I downloaded some time ago from www.jboss.org.

First, let's do our simple WS - that will receive a name as a parameter and return Hello name. Quite simple ;)
I will not get into details here because the other post has already covered the Web Service easy creation on NetBeans.
Just ask for a New Project on NetBeans (File->New Project or Ctrl+Shift+N). Select a Web Application, using the Web Category and press Next. Choose a name for your application (for example: HelloTom) and press Next again.
On this screen, you choose the server you will use for the project, select Tomcat.

Press Finish.
After project creation, right click the project name (HelloTom) and select "New->Web Service" from the drop down menu. On the wizard screen, define the Class and package name for your WS (like Hello and hello.ws). NetBeans will open your WebService for visual development.

Click on the "Add Operation..." Button. On the wizard screen, select the name of the operation (i.e. helloOperation). Do not use just 'Hello' as the name of the operation because it will be interpreted as the WS class constructor and you may get confused. Leave the Return Type as String but add a String parameter called "name". Click OK and see that the visual designer added your operation to the WS Operations list on the screen. Right Click the helloOperation and select "Go To Source".

On the Source edit the Operation code like this:

@WebMethod(operationName = "helloOperation")
public String helloOperation(@WebParam(name = "name")
String name) {
       return "Hello "+name;

Done. Now, right click your project name (HelloTom) and choose Run. If Tomcat is up and running, it will show the Hello World! message for you that is on its default JSP page.
The "Test Web Service" functionality we have used on the other post will not be avaiable on Tomcat like on Glassfish, but you can easily try your WS creating another project that access the Web Service on the server. If you have problems creating a project to access the WS, check the WebServices and JSP on NetBeans 6.1 post.

Now let's add another server to NetBeans and make use of it.

Click on the Services tab, on the left side of IDE. Righ Click the Server node and click on "Add Server..." just like the next picture:

The Wizard starts and you need to choose the Server type. Here, on my example, I chose JBoss Application Server (but there are many others):

Press Next. On the next screen, select the server location (ie, where is it installed) and press Next again.
On this screen, you will need to select a server configuration, I've just left the default:

Press Finish. The Server will be added to your Server list on the IDE. You may right click on its icon and Start the server just like this (Iniciar=Start, in Portuguese):

Wait until JBOSS starts and let's test it.

Go Back to your projects clicking on the Projects Tab. Right Click the Hello Project and select Properties from the drop down menu. On the Properties screen, select the Run category (that may be the last one) on the left panel just like the next picture (the picture has somethings in Portuguese where Run=Executar). After selecting the Run category, you will see (on the right side) the option to select the server where you want to deploy your project, we will have Tomcat selected, change it to JBoss Application Server.

Press OK and wait while NetBeans save your project's Settings. Now your can Run the Hello project again and it will be deployed directly on JBoss. The "Test Web Service" functionality is not avaiable on JBoss too, you need to create another simple project that access the Service on the server. It'easy and described on the WebServices and JSP on NetBeans 6.1 post.

That's it! There is no limit!

Quarta-feira Jun 04, 2008

WebServices and JSP on NetBeans 6.1

Turn The Very Easy mode On and Play

Hi Everybody! Today I'm writing a little review (that may sounds like a tutorial) about the easiest way to write a simple Web Service and use it on your projects. See, you don't need to be an expert on Web Services nor JSP nor Web Technologies, because we are using NetBeans 6.1, the only IDE you need to learn something big on the very easy way.

From 6.0 to 6.1, NetBeans has grown faster, more stable and more practical. I haven't found anything specific about the development of WS using the New NetBeans, only using the 5.5 version. That's why I decided to write it here.

I've downloaded the Web & JavaEE Pack of Netbeans 6.1 on NetBeans Download Center. It comes with TomCat and Glassfish bundled, but we can use others Containers too, like JBOSS, for example. On the Services tab, on the left side of IDE, you can find the servers that NetBeans is using.

You may click on 'Servers' and choose 'Add Server...', A list of 'Connectible' servers appears. You will be able to connect Servers like JBOSS, WebSphere, BEA WebLogic, Sailfin, and, of course, TomCat, Sun Application Server and Glassfish, all out-of-the-box. (They just need to be installed, TomCat and Glassfish can be installed during NetBeans Setup).

Now Let's Start our Web Service. We just need to go to File -> New Project (Ctrl+Shift+N), choose Web on Categories and Web Application on Projects. Then Press Next. Choose the name and folders of your application and press Next again, then choose the server where your Web Application will be deployed. You will see the screens below (but they will be shown separated, through the next steps, not layered). On the End, just press Finish. (If you press Next, you will be able to choose a framework like JSF or Struts)

Now we have our Web Project. A Default index.jsp is there waiting - delete it - we are doing WebServices for now. Select the Project, click on the Project name with your right mouse button, choose New -> Web Service... on the list. NetBeans will then open a tab on the development area showing it's graphical interface to create Web Services, just like that:

A Web Service is quite like a java class (it's a .java file), in which the methods are called Operations. A Web Service may have many Operations. So, let's create our Operations clicking at the 'Add Operation...' Button. A window will pop up, asking the details of your operation, just like this:

I created two operations, one to add a user (the addUser Operation show above) and one to check if the user has been added to the list, like a login check (the checkUser Operation). NetBeans shows me the details graphically:

(If the image is too little, click with your right mouse button and choose View Image, The blog may be resizing the pictures, making them unreadable)

Now we go to the Source Code (Clicking on the Source button on the development area, just below the file tab)! You can click with the right button on the Operation and choose 'Go to Source' option on the Menu.
At The Source you see all the Structure of your code. Out of the methods scope, create a List of Users like:
>> List users; . There is no User Class defined in the package, so click on the light bulb near the code and ask NetBeans to create User Class in the package for you:

Go to User Class source code and add two parameters to the class: String username; and String password;
Then we ask NetBeans to create the getter and setter methods, and to override equals and hash code methods. How?? Easy! Just click with the right button and select Insert Code: A little menu will appear:

and we may choose to generate many kinds of methods. For example, if we choose to generate equals and hash code, another windows will pop up asking about which parameters of the class do you want to use, just like this:

Any doubts about the User Class, see it's source here.

Back to the Web Service source code, now we have to implement the addUser and checkUser Operations. They are both easy, see the idea of the code below:
To add a user:
   User user = new User();
   if(!users.contains(user)) { //if the user is not already on the list
     users.add(user); // add the user and return true to say everything has gone OK
     return true;
   } else { // user is already on the list.
     return false; // Return false to say no one has been added to the list

To check the User:
   User user = new User();
   if(users.contains(user)) { //if the user is on the list
     return true; // let it login, return OK
   } else { // user isn't on the list
     return false; // return 'there is a problem here'

The Full Web Service Code can be viewed (and copied ;) ) here.

Now, we may just Run our Web Service, and see that it's Running on the Service tab under your container's Web Applications.

But, let's Test it to see if it's really working!
Expand the Web Service Folder of Your Project and select your Web Service. Click with the right button and select Test Web Service:

Something like that will be opened on your Browser:

Amazing, isn't it?? You may test your Web Service as you want, and get answers like this:

Tip: Add some users using the addUser Operation and see if checkUser works returning True for added Users and False for unknown users.

Now Lets quickly create our JSP! Yes... really fast.

Create a New Project (File -> New Project). Select Web / Web Application Again!
Now we may use the 'index.jsp' file. There is a palette on the right side of the IDE, you may drag and drop HTML Form Items to your code. You need a FORM that collect user's login and password. Something like this:

<form name="loginForm" action="checkLogin.jsp" method="POST">
<input type="text" name="login" value="Your Login" />
<input type="password" name="pwd" value="\*\*\*\*\*\*\*" />
<input type="submit" value="Submit" name="loginSubmit" />

The Form action is checkLogin.jsp... so Let's create it. Click on your new Web Project name with the right button, go to New -> JSP. Create the JSP named checkLogin.
Now let's add a client to our WebService, the one we created on the other Project.
Click with right button on your New Project Name, go to New -> Web Service Client...
Select the Project where the WebService has been Created, just like this:

There are other ways to get the Web Service (thought WSDL link, for example), you may explore it yourself latter.
Wait while NetBeans process the Web Service into your New Project, you will be able to see it on the project. Like this:

(On the properties of the webservice, you will find the WSDL address of the service, then you can visualize it o the browser, and see it's XSD too.)

Now, go to the JSP code. Below the Hello World default Message, click with the right button and select:
Web Service Client Resources -> Call Web Service Operation
A window will appear asking which operation you want to choose:

Choose checkUser and NetBeans will do all the code for you. Of course, you need to put some by yourself. Our FORM, on index.jsp, send it's data using POST. so let's get these values from POST. Add the fallowing code before the Web Service process, just after the 'try {' put by NetBeans on your JSP:
    String uname = request.getParameter("login");
    String pwd = request.getParameter("pwd");

Then, change the generated code lines to point to your collected data:
    java.lang.String login = uname;
    java.lang.String password = pwd;
    // TODO process result here
    boolean result = port.checkUser(login, password);
    if(result) {
       out.println("User Logged");
    } else {
       out.println("Access Denied");
    } catch (Exception ex) {
       out.println("Unable to operate the WebService");

Any doubts, check index.jsp and checkLogin.jsp codes.

Then, ask NetBeans to Run the index.jsp file. The browser will be opened with your JSP page asking a login and password (Just after the Hello World! message). Try the login and password you have added using the Test tool and see if checkLogin grants access to the users or not. Try the users you have added and another ones. If no User is recognized, the data on the Server may has been lost, try adding new login/passwords using the Test Tool or using the addUser Operation, now you know how to do it.

You don't need to use a Web Interface to access your Web Service, you can create a Java Project with a GUI that connects to the server and use the Web Service, or use a Mobile, everything through NetBeans. Just Explore!

Remember!! We are keeping this user information on a List inside the Memory (through the Web Service inside the Server). If you restart the Server or the IDE, all information may be lost. This example is just a simple one, to do a more professional system, you should use a database, this way your data will be kept safe.

Hope you enjoy that! The text is quite big, but it's simple to do that!
Any doubts or tips, just send a comment! ;)


Terça-feira Abr 15, 2008

Tech Demos

As promised, the tech demos' abstracts. All in Portuguese because they will be done on Brazil... so...(for English versions, send me an e-mail).

Iniciativa Acadêmica Sun :: Tech Demos

Quinta-Feira dia 24/04: Construindo Aplicações para dispositivos Móveis visualmente usando o NetBeans 6.0

    A Tech demo busca expor alguns conceitos da elaboração de aplicativos para dispositivos móveis usando Java, explicando sucintamente a arquitetura da plataforma JAVA Micro Edition (JavaME) e ferramentas de suporte à citada tecnologia presentes no NetBeans 6.0. É realizada uma pequena demonstração do que pode ser feito nele, construindo os aplicativos de forma simples e visual.

Sexta-Feira dia 25/04: Serviços Web utilizando o NetBeans 6.0

    Esta pequena demonstração tecnológica aborda o suporte oferecido para a plataforma Java Enterprise Edition, também conhecida como JavaEE ou J2EE, no NetBeans 6.0, exemplificando com o desenvolvimento rápido e prático de serviços web. Além da demonstração, explica-se sucintamente o que é um serviço web, sua arquitetura e por que este se mostra como uma solução tão interessante no mercado atual.

Em ambas as Tech Demos, o programa de iniciativa acadêmica da Sun é explicado lembrando as vantagens para os alunos nos treinamentos online gratuitos e certificações com desconto.

Domingo Abr 13, 2008

New Tech Demos

Tech Demos Scheduled @ UFRJ! 24 and 25 of april! I will post abstracts here! For now, just the poster!!

(The following poster is written in Br Portuguese!)

Sábado Mar 15, 2008

Tech Demo at Estácio

Hi all,

Today, I did a 2 hours presentation with Pedro Reis (another CA from Rio de Janeiro) at Estácio de Sá University, on the center of Rio. We had an attendance of 62 people, including 5 professors, of the Java Development pos graduation class.

The presentation slides were prepared by Bruno Bastos (Petrópolis Sun CA) and I added some ones latter. The first arrangement was that Bruno and Luiz Aquino would do the today’s tech talk on Estácio, but in the end, things got totally different.

Bruno had an important appointment for today and Luiz Aquino got Dengue disease and needed to stay resting. So, I completed the task with Pedro!

Bruno made a cool web service and client system on NetBeans to show on the presentation. I constructed a simpler one during the demo (to make it on shorter time), and then, showed Bruno’s. The examples were quite nice because we were able to illustrate many features of NetBeans on a single shot, like the easy implementation of a web service, it’s integration with Glassfish and the way to use it on a client that can be developed using NetBeans Matisse! Everybody got really impressed!

Aside the Web Services and GlassFish, we talked about NetBeans 6.0 features (emphasizing the new ones), the SAI program, and the Java Certification, explaining how they can get theirs with discount! I inserted an OpenSolaris slide, focusing on SXDE, for fast and easy development, they got tempted to try it!

In the end, we raffled some souvenirs like Sun pens, All Access Kit DVDs, OpenSolaris mini-books and locksmiths.

Some professors on the room asked us to schedule more presentation on another institutes and universities on Rio that they give classes too. They will help us organize it there.


Well... Let's keep this blog updated for now on!!


« Agosto 2016