Tuesday, January 26, 2016

Learn and shine: Getting started with spring mvc controller and je...

Learn and shine: Getting started with spring mvc controller and je...: Getting started with spring mvc and jersey rest service example This topic is about how to work with sping mvc controller using annotations...

Getting started with spring mvc controller and jersey rest service example

Getting started with spring mvc and jersey rest service example
This topic is about how to work with sping mvc controller using annotations and jersey rest service
Create dynamic web project using eclipse. Name it has springweb-mvc






This is spring project, so first we need to configure the details in web.xml for spring
Edit the web.xml file and add the below code
1. Dispatcher Servlet
2. Context LoaderListener
3. SpringServlet for rest webservice


  springweb-mvc
 
           org.springframework.web.context.ContextLoaderListener
       
        
  spring
  
                org.springframework.web.servlet.DispatcherServlet
        
  1
 
 
 
  spring
  /
  
 
  
  jersey-serlvet
  
   com.sun.jersey.spi.spring.container.servlet.SpringServlet
  
  
   com.sun.jersey.config.property.packages   com.siva.rest  
 
 
 
  jersey-serlvet
  /rest/*
 



1. Now we need to create spring-servlet.xml, hope you will understand why we need to create this file,
Let me explain , in above web.xml we have configured servlet name as spring. So as part of spring DispatcherServlet we need to create xml (servletname-servlet.xml). in this case spring –servlet.xml
2. Need to provide the jersey related configuration
Here I have provided param-value as com.siva.rest , where our rest service related files resides.

Add below code in spring-servlet.xml


  

   
   
        
    
    
    
   
      
      
    
 
 



In the above xml, component package we have given has com.siva.controlller, where our controller classes resides.
Since we are using annotations no other configurations required.
View configuration - our views will be under WebContent/views
Now we need to create applicationContext.xml, where application will start the executing, here I am not providing any configuration details in this file, simply I am creating file to avoid runtime exceptions .
   

   

        
    
 
 



Now it’s time to create controllers , rest service and views

1. First we will create rest webservice
Create a Calculator.java under package com.siva.rest
   package com.siva.rest;


import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name = "Calculator")
public class Calculator {

 private int number1;
 private int number2;

 // Must have no-argument constructor
 public Calculator() {

 }

 public Calculator(int number1, int number2) {
  this.number1 = number1;
  this.number2 = number2;
 }

 
 @Override
 public String toString() {
  return new StringBuffer(" Number 1 : ").append(this.number1)
    .append("Number 2 : ").append(this.number2).toString();
 }

 public int getNumber1() {
  return number1;
 }
 @XmlElement
 public void setNumber1(int number1) {
  this.number1 = number1;
 }

 public int getNumber2() {
  return number2;
 }

 @XmlElement
 public void setNumber2(int number2) {
  this.number2 = number2;
 }

}


Now we need to write Rest service class JersyRestService under package com.siva.rest

package com.siva.rest;

import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;


@Path("/xmlServices")
public class JerseyRestService {
 
 @GET
 @Path("/add/{number1}/{number2}")
 @Produces(MediaType.TEXT_PLAIN)
 public String add( @PathParam("number1") Integer number1,  @PathParam("number2")Integer number2 ) {
        System.out.println("Number 1["+number1+"], Number 2["+number2+"]");
  return number1+number2 +"";
 }
 
 @POST
 @Path("/substract")
 @Produces(MediaType.TEXT_PLAIN)
 public String substract(Calculator cal ) {
        System.out.println("Number 1["+cal.getNumber1()+"], Number 2["+cal.getNumber2()+"]");
  return(cal.getNumber1()- cal.getNumber2() +"");
 }
}


Create a Controller RestServiceController class under package com.siva.controller

package com.siva.controller;

import javax.ws.rs.core.MediaType;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.siva.rest.Calculator;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;

@Controller
public class RestServiceController {

 @RequestMapping(value="/addRequestDetails" ,method = RequestMethod.POST)
 public ModelAndView addNumbers(@ModelAttribute("addRequestDetails") Calculator command,
   ModelMap model) {
  System.out.println("addNumbers inside RestServiceController");
  int number1 = command.getNumber1();
  int number2 = command.getNumber2();
  String resultMessage = null;
  try {
   Client client = Client.create();
   WebResource webResource = client.resource("http://localhost:8080/springweb-mvc/rest/xmlServices/add/"+number1+"/"+number2);
   ClientResponse response = webResource.accept(MediaType.TEXT_PLAIN).get(ClientResponse.class);
   resultMessage = response.getEntity(String.class);
   System.out.println("Addition of the 2 numbers result["+resultMessage+"]");
   System.out.println(" resposne status in RestServiceController ["+response.getStatus()+"]");
   
  }  
  catch (Exception e) {
   System.out.println("Exception occurred while calling rest services..."+e);
      e.printStackTrace();
     } 
  return new ModelAndView("restresult").addObject("resultMessage", "Addition of the two values result is["+resultMessage +"]");
 }
 
 @RequestMapping(value="/substractRequestDetails" ,method = RequestMethod.POST)
 public ModelAndView substractNumbers(@ModelAttribute("substractRequestDetails") Calculator command,
   ModelMap model) {
  System.out.println("addNumbers inside RestServiceController");
  int number1 = command.getNumber1();
  int number2 = command.getNumber2();
  Calculator cal = new Calculator(number1, number2);
  String resultMessage = null;
  try {
   Client client = Client.create();
   WebResource webResource = client.resource("http://localhost:8080/springweb-mvc/rest/xmlServices/substract");
   ClientResponse response = webResource.accept(MediaType.TEXT_PLAIN).post(ClientResponse.class,cal);
   resultMessage = response.getEntity(String.class);
   System.out.println("Substraction of the 2 numbers result["+resultMessage+"]");
   System.out.println(" resposne status in RestServiceController ["+response.getStatus()+"]");
   
  }  
  catch (Exception e) {
   System.out.println("Exception occurred while calling rest services..."+e);
      e.printStackTrace();
     } 
  return new ModelAndView("restresult").addObject("resultMessage", "Substraction of the two values result is["+resultMessage +"]");
 }
}



Create addition.jsp page under WebContent/views/

<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>




Add 2 numbers using rest service


  
Number1
Number2

Create substraction.jsp page under WebContent/views/

<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>




substract 2 numbers using rest post service


  
Number1
Number2


Now after adding/substracting the numbers we need to show the results
Create a restresult.jsp under WebContent/views/
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>




Result of the rest service


     
${resultMessage}

Now we have completed coding now we need to run this project. I have executed this project using tomcat7 server
Required jars to executing this project, please make sure your tomcat or jboss lib having these ja rs

common jars

commons-beanutils-1.8.0.jar
commons-codec-1.3.jar
commons-collections.jar
commons-digester-2.1.jar
commons-logging-1.0.jar
commons-net-1.4.0.jar


Jersey related jars

jersey-client.jar
jersey-core-1.8.jar
jersey-server-1.8.jar
jersey-spring-1.8


spring related jars


spring-aop-4.1.5.RELEASE.jar
spring-beans-4.1.5.RELEASE.jar
spring-context-4.1.5.RELEASE.jar
spring-core-4.1.5.RELEASE.jar
spring-expression-4.1.5.RELEASE.jar
spring-web-4.1.5.RELEASE.jar
spring-webmvc-4.1.5.RELEASE.jar
asm-3.1.jar

After executing project Now it’s time to see the output.
If project deployed successfully then click the below link
http://localhost:8080/springweb-mvc/views/addition.jsp



After entering the values click on Add button



Substract the numbers using following URL
http://localhost:8080/springweb-mvc/views/substraction.jsp





After entering the details ,Result page same like the addition results page.

This is how Rest service with Spring mvc will work.

If you want execute same rest service using main method use the below code.

Create a class JersyClient.java under package com.siva.rest
package com.siva.rest;


import javax.ws.rs.core.MediaType;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;


public class JerseyClient {
 
 public static void main(String[] args) {
  try {
   Client client = Client.create();
   //Adding 2 numbers using GET
            WebResource webResource = client.resource("http://localhost:8080/springweb-mvc/rest/xmlServices/add/"+40+"/"+50);
   ClientResponse response = webResource.accept(MediaType.TEXT_PLAIN).get(ClientResponse.class);
   String resultMessage = response.getEntity(String.class);
   System.out.println("Addition of the 2 numbers result["+resultMessage+"]");
   System.out.println(" resposne status in RestServiceController ["+response.getStatus()+"]");
   
   
   //Substract 2 numbers using POST
      Calculator cal = new Calculator(20, 10);
   WebResource webResource1 = client.resource("http://localhost:8080/springweb-mvc/rest/xmlServices/substract");
   ClientResponse response1 = webResource1.accept(MediaType.TEXT_PLAIN).post(ClientResponse.class, cal);
   System.out.println("["+response1.getStatus()+"]");
   if (response1.getStatus() != 200) {
    throw new RuntimeException("Failed : HTTP error code : "+ response1.getStatus());
   }
   String output = response1.getEntity(String.class);
   System.out.println("Substraction of 2 numbers  : \n["+output+"]");
  } catch (Exception e) {

   e.printStackTrace();

  }

 }



}



Thanks for viewing this post.




Saturday, January 23, 2016

Create a blog app using Web2py


1. Start web2py
2. Usually blog will have post and view the post details
3. Validations required to validate the post
4. Database design to store title, content, image category , blog posted date etc..
First we need to create model



5. Edit the db.py file
6.End of the file add the below code, to create a table 'blog' along with columns

db.define_table('blog',
                 Field('blog_title'),
                 Field('blog_details'),
                 Filed('blog_image'),
                 Field('blog_url'),
                 Field('blog_category'),
                 Field('blog_date_posted'))


We need to use validators inside model, more validators look inside

http://web2py.com/examples/static/web2py_cheatsheet.pdf

db.define_table('blog',
                 Field('blog_title', requires=IS_NOT_EMPTY()),
                 Field('blog_details', type='text'),
                 Filed('blog_image',requires=IS_URL()),
                 Field('blog_url',requires=IS_URL()),
                 Field('blog_category',requires=IS_IN_SET(['News','Events','Technology','Business'])),
                 Field('blog_date_posted', type='date',requires=IS_DATE()))

  


7. Need to add validation for table details


8.Now we need to create a controller, to post the blog app
9.Create controller name called blog under controller section
10.Edit blog.py
11. Add two methods one is called post and one is view



def post():
       form =SQLFORM(db.blog).process()
       return locals()
      def view():
      rows = db(db.blog).select(orderby=~db.blog.id)
      return locals()

   



12.Now we need to create views as blog/post and blog/view
13.Edit the blog/post.py
{{extend 'layout.html'}}
     

post a blog as you like

{{=form}}

http://127.0.0.1:8000/sivaweb2py/blog/post


14.If you submit without entering any values, then it will show the validation errors






Provide the details as required and submit the same. You can see the success message.

Need to know more about SQLFORMS and validators
http://web2py.com/books/default/chapter/29/07/forms-and-validators
Now we need to update the blog

Edit the blog.py and add the below code for update method

def update():
    record = db.blog(request.args(0)) or redirect (URL(post))
    form = SQLFORM(db.blog,record)
    if form.process().accepted:
        response.flash = T('Record Updated')
    else:
        response.flash=T('Please complete the form')
    return locals()





Create update view under views section
{{extend 'layout.html'}}
            

Update the form

{{=form}}

Click on the below link to update the record or provide number after update method which ever record want to update
http://127.0.0.1:8000/sivaweb2py/blog/update/1



Now we need to create the view page

{{extend 'layout.html'}}
      

View the blog


{{ for x in rows:}}
blog image

{{=x.blog_title}}

categrory:{{=x.blog_category}}

blog Details:{{=x.blog_details}}

blog posted:{{=x.blog_date_posted}}

{{ pass }}




After adding the above code in view.py, if we check the result using below url
http://127.0.0.1:8000/sivaweb2py/blog/view




This is how we can create a blog app using web2py.



Sunday, January 10, 2016

Getting started with web2py framework



    Full Stack web development with Python (Web2Py)
    How to download and install web2py
1.  Go  to http://web2py.com/
2.   Down load latest version http://web2py.com/init/default/download
     Unzip the downloaded file
     CliCk on the Web2py.exe file to it will open the window like below





           Provide the password(any password) and start the server
           Server has been started. Now we need to create a application using web2py framework.
           http://localhost:8000

                                                

         Click on the Admin,  which is there on the right side in the page. And provide the password which      we have given while starting the server





                After Successful Login,  page will be open like below.

               Create a new application using this framework- > New simple application –
       Application Name - ex: sivaweb2py
              Click on the create button. Now we have created application successfully.
               Need to run the application
               http://localhost:8000/sivaweb2py
               


              Now we need to write sample code in this application. So we need to understand basics of  the
       framework
               Need to edit the application


      This framework will follow MVC architecture
          Model- Contains db details
         Controller – Method and logic details
         Views – Html input/output to the user

Now we need to create one controller and respective views
Click on the Create button under Controller Section
I have given controller name as basics – basics.py will be created under controller

       Now edit the controller – Click on the basics.py
     def helloworld():
     msg= "Hello welcome to basics controller!"
     return locals()


 In the above code helloworld is method name . Copy the code and paste the same in your file.
  Save the file and go to back – by click on the back buton
  Now we need to create a  view- under Views section
  View name should be as method name  ex: basics/helloworld

   {{extend 'layout.html'}}
    This is our first web page
   {{ =msg}}

Writing first web2py is very easy


                          

        

                               






AddToAny

Contact Form

Name

Email *

Message *