Skip to content

javaee-samples/javaee7-eclipse

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

29 Commits
 
 
 
 
 
 

Repository files navigation

Java EE 7 using Eclipse

Project creation

  • Create a simple Dynamic Web Project

    • Choose the module version as “3.1”

    • Add a new configuration for WildFly

    • Add index.html in “WebContent”

    • “Run as”, “Run on Server”

    • Change content on index.html and show LiveReload

Servlet

Persistence

  • Right-click on project, select “Properties”, search for “facet”, enable “JPA”, click on “Apply”

    • Talk about “Further configuration available” and default data source (no configuration required)

  • Right-click on project, select “New”, “JPA Entity” and give the name as Student

  • Add a primary key in the wizard. Use long datatype and id name.

  • Generate Getter/Setter by clicking “Source”, “Getters and Setters”.

  • Add toString implementation

  • The updated class should look like:

    @Entity
    @XmlRootElement
    @NamedQuery(name="findAllStudents", query="select s from Student s")
    public class Student implements Serializable {
    
    	@Id
    	private long id;
    	private static final long serialVersionUID = 1L;
    
    	public Student() {
    		super();
    	}
    
    	public Student(long id) {
    		this.id = id;
    	}
    	public long getId() {
    		return this.id;
    	}
    
    	public void setId(long id) {
    		this.id = id;
    	}
    
    	public String toString() {
    		return "Student[" + id + "]";
    	}
    }
    • @XmlRootElement in Student entity enables XML <→ Java conversion.

    • @NamedQuery(name="findAllStudents", query="select s from Student s") in Student enables querying all students.

  • Add the following properties to persistence.xml:

    <properties>
    	<property name="javax.persistence.schema-generation.database.action"
    		value="drop-and-create" />
    	<property name="javax.persistence.schema-generation.create-source"
    		value="metadata" />
    	<property name="javax.persistence.schema-generation.drop-source"
    		value="metadata" />
    	<property name="hibernate.show_sql" value="true"/>
    	<property name="hibernate.format_sql" value="true"/>
    </properties>
  • Show “server console” when the application is deployed. Show the generated SQL statements.

Setup console to watch database

  • Download H2 console war to WildFly’s standalone/deployments directory

    curl -L https://github.com/jboss-developer/jboss-eap-quickstarts/blob/6.3.0.GA/h2-console/h2console.war?raw=true -o h2console.war
  • Start the server and access http://localhost:8080/h2console

  • Enter the JDBC URL and credentials. To access the "test" database your application uses, enter these details (everything else is default):

    • JDBC URL: jdbc:h2:mem:test;DB_CLOSE_ON_EXIT=FALSE;DB_CLOSE_DELAY=-1

    • User Name: sa

    • Password: sa

RESTful Web Services

  • Create a JAX-RS resource StudentEndpoint

    • rest.RestApplication is added and specifies the base URI for REST resoures as /rest.

    • Use Student entity as the basis, select create, findById, listAll methods to be generated.

  • Update the class so that it looks like as shown:

    @RequestScoped
    @Path("/students")
    public class StudentEndpoint {
    
    	@PersistenceContext EntityManager em;
    
    	@Transactional
    	@POST
    	@Consumes({ "application/xml", "application/json", "text/plain" })
    	public void create(final long id) {
    		Student student = new Student(id);
    		em.persist(student);
    	}
    
    	@GET
    	@Path("/{id:[0-9][0-9]*}")
    	@Produces({ "application/xml", "application/json" })
    	public Response findById(@PathParam("id") final Long id) {
    		Student student = em.find(Student.class, id);
    		if (student == null) {
    			return Response.status(Status.NOT_FOUND).build();
    		}
    		return Response.ok(student).build();
    	}
    
    	@GET
    	@Produces("application/xml")
    	public Student[] listAll(
    			@QueryParam("start") final Integer startPosition,
    			@QueryParam("max") final Integer maxResult) {
    		TypedQuery<Student> query = em.createNamedQuery("findAllStudents", Student.class);
    		final List<Student> students = query.getResultList();
    		return students.toArray(new Student[0]);
    	}
    }
  • Use “Advanced REST Client” in Chrome

    • Make a GET request to http://localhost:8080/HelloJavaEE7/rest/students

      • Add Accept: application/xml

      • Show empty response

    • Make a POST request

      • Payload as 1

      • “Content-Type” header to text/plain

    • Make a GET request to validate the data is posted

  • Edit doGet of TestServlet to match the code given below

    ServletOutputStream out = response.getOutputStream();
    out.print("Retrieving results ...");
    Client client = ClientBuilder.newClient();
    Student[] result = client
    .target("http://localhost:8080/HelloJavaEE7/rest/students")
    .request()
    .get(Student[].class);
    for (Student s : result) {
    	out.print(s.toString());
    }
  • Access the Servlet in the browser to show the results and explain JAX-RS Client API

Bean Validation

  • Change create method to add Bean Validation constraint

    public void create(@Min(10) final long id) {
  • Make a POST request with payload as 1 and show an error is being received

CDI

  • Generate an interface Greeting

    public interface Greeting {
    	public String sayHello();
    }
  • Create a new class SimpleGreeting, implement the interface as:

    public class SimpleGreeting implements Greeting {
    
    	@Override
    	public String sayHello() {
    		return "Hello World";
    	}
    
    }
  • Inject the bean in Servlet as @Inject Greeting greeting;

  • Print the output as response.getOutputStream().print(greeting.sayHello());

  • Show “New missing/unsatisfied dependencies” error and explain default injection

  • Add @Dependent on bean

  • Create a new class FancyGreeting, implement the interface, add @Dependent

  • Create a new qualifier using “New”, “Qualifier Annotation Type”

Advanced CDI

Batch

JavaServer Faces

OpenShift

Forge

Continuous Delivery

Releases

No releases published

Packages

No packages published