DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • A Systematic Approach for Java Software Upgrades
  • From J2EE to Jakarta EE
  • Exploring Exciting New Features in Java 17 With Examples
  • The Next Evolution of Java: Faster Innovation, Simpler Adoption

Trending

  • Docker Model Runner: Streamlining AI Deployment for Developers
  • Internal Developer Portals: Modern DevOps's Missing Piece
  • Unlocking AI Coding Assistants Part 2: Generating Code
  • My LLM Journey as a Software Engineer Exploring a New Domain
  1. DZone
  2. Coding
  3. Java
  4. A Detailed Look at Controllers in Java EE 8 MVC

A Detailed Look at Controllers in Java EE 8 MVC

An MVC Controller is a JAX-RS resource method annotated with @Controller. If a class is annotated with @Controller, then all resource methods of this class are regarded as controllers.

By 
Michael Scharhag user avatar
Michael Scharhag
·
Oct. 07, 15 · Tutorial
Likes (6)
Comment
Save
Tweet
Share
18.7K Views

Join the DZone community and get the full member experience.

Join For Free

Java EE MVC is a new action based MVC framework planned for Java EE 8 and specified in JSR-371. This is the second post of my Java EE 8 MVC tutorial. The first post covered the basics and shows how to get started with Ozark, the Java EE 8 MVC reference implementation.

In this post we will have a more detailed look at MVC Controllers.

MVC Controllers

A controller is responsible for processing incoming requests. It invokes business logic, updates the model and returns the view that should be rendered. An MVC Controller is a JAX-RS resource method annotated with @Controller. If a class is annotated with @Controller, then all resource methods of this class are regarded as controllers.

The following example shows a simple Controller that renders a product details page for a given product ID:


@Path("product")
@Controller
public class ProductController {

  @Inject
  private Models models;

  @Inject
  private ProductService productService;

  @GET
  public String getProductDetailPage(@QueryParam("id") long productId) {
    Product product = this.productService.getProduct(productId);
    models.put("product", product);
    return "/WEB-INF/jsp/productDetailPage.jsp";
  }
}

This Controller resolves a product id (passed as id request parameter) to a product using a ProductService. The obtained product is added to the model and a path to a view is returned. The view is then rendered with the information stored in the model.

Like in JAX-RS, the @Path annotation is used to define the URL path. This Controller is accessible via a URL that looks like this:


/<application-path>/product?id=42

The following example shows a hybrid class with one MVC controller method and one traditional JAX-RS resource method:


@Path("hybrid")
public class HybridController {

  @GET
  @Path("jaxrs")
  public Response jaxrs() {
    return Response.status(200).build();
  }

  @Path("mvc")
  @GET
  @Controller
  public String mvc() {
    return "/WEB-INF/jsp/hello.jsp";
  }
}

Controller methods work very similar to JAX-RS resource methods. However, there are two small differences:

  • A return type of String on Controller methods is interpreted as a view path. With JAX-RS resource methods the returned String is interpreted as text content.
  • The default response media type for Controller methods is text/html. Like in JAX-RS the media type can be changed using the @Produces annotation.

MVC Controller classes and hybrid classes with MVC Controller methods need to be CDI-managed beans. Like JAX-RS resource classes, MVC controller classes are instantiated per request. For every request, a new Controller class instance is created.

Like in JAX-RS the supported HTTP verb is defined by annotations. If a controller method should listen for HTTP POST requests, it needs to be annotated with @POST instead of @Get.

For example:


@Controller
@Path("http")
public class PostController {

  @POST
  @Path("post")
  public String post() {
    return "/WEB-INF/jsp/hello.jsp";
  }
}

Controller Return Types

Four different return types are supported on MVC controller methods:

  • String - The returned string value is interpreted as view path.
  • void - In this case the view need to be defined using the @View annotation
  • Viewable - An abstraction that includes information about a view, the model and the used view engine.
  • Response - A JAX-RS response. The entity type of the response needs to be String, void or Viewable.

The following class defines four controller methods using different return types. All methods return the same response:


@Controller
@Path("return-types")
public class ReturnTypesController {

  @GET
  @View("/WEB-INF/jsp/hello.jsp")
  @Path("return-void")
  public void returnVoid() {
  }

  @GET
  @Path("return-string")
  public String returnString() {
    return "/WEB-INF/jsp/hello.jsp";
  }

  @GET
  @Path("return-string")
  public Viewable returnViewable() {
    return new Viewable("/WEB-INF/jsp/hello.jsp");
  }

  @GET
  @Path("return-response")
  public Response returnResponse() {
    return Response.status(Response.Status.OK)
        .entity("/WEB-INF/jsp/hello.jsp")
        .build();
  }
}

Returning a JAX-RS Response is the most flexible way. This way the JAX-RS Response builder can be used to modify the HTTP status code, response headers and more.

If void is used as return type, the view needs to be defined using the @View annotation. @View can be applied to methods (like in the previous example) and classes. If a class is annotated with @View, the view is applied to all controller methods in this class. A class level @View annotation can be overridden by a more specific view definition on method level, like shown in the following example:


@Controller
@Path("views")
@View("/WEB-INF/jsp/foo.jsp")
public class ViewController {

  @GET
  @Path("first")
  public void first() {
    // renders foo.jsp
  }

  @GET
  @Path("second")
  @View("/WEB-INF/jsp/bar.jsp")
  public void second() {
    // renders bar.jsp
  }

  @GET
  @Path("third")
  public String third() {
    // renders baz.jsp
    return "/WEB-INF/jsp/baz.jsp";
  }
}

Summary

The @Controller annotation can be used on methods and classes. When used on classes, all methods of the class are considered as controllers. Controller methods invoke business logic and determine the view that should be rendered. Classes with Controller methods are CDI managed beans. For every request, a new class instance will be created. Traditional JAX-RS resource methods can be combined with MVC Controller methods in the same class.

In the next posts about Java EE 8 MVC we will have a look at parameter binding and validation.

You can find the example source code on GitHub.

Java EE Java (programming language)

Published at DZone with permission of Michael Scharhag, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • A Systematic Approach for Java Software Upgrades
  • From J2EE to Jakarta EE
  • Exploring Exciting New Features in Java 17 With Examples
  • The Next Evolution of Java: Faster Innovation, Simpler Adoption

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: