当前位置: 首页 > news >正文

Getting started with Java EE 8 MVC(1)

为什么80%的码农都做不了架构师?>>>   hot3.png

Getting started with Java EE 8 MVC

MVC is a new specification introduced in the upcoming Java EE 8.

It is based on the existing JAXRS.

At the moment I wrote down these posts, most of Java EE 8 specficitaions are still in the early disscussion stage, and MVC 1.0 is also not finalized, maybe some changes are included in future. I will update the Wiki pages and codes aglined with final Java EE 8 specficitaions when it is released.

I will use the latest Java 8, Glassfish 4.1.1, and NetBeans IDE for these posts.

Prequisition

  • Oracle JDK 8 or OpenJDK 8

    Oracle Java 8 is required, go to Oracle Java website to download it and install into your system.

    Optionally, you can set JAVA_HOME environment variable and add <JDK installation dir>/bin in your PATH environment variable.

  • The latest Apache Maven

    Download the latest Apache Maven from http://maven.apache.org, and uncompress it into your local system.

    Optionally, you can set M2_HOME environment varible, and also do not forget to append <Maven Installation dir>/bin your PATH environment variable.

  • NetBeans IDE

    Download the latest NetBeans IDE from http://www.netbeans.org, and installed it into your local disk.

  • Glassfish Server

    Download the latest Glassfish from Glassfish official website. Currently the latest GA version is 4.1.1. Extracted it into your local disk.

NOTE: You can download the JDK and NetBeans bundle from Oracle website instead of installing JDK and NetBeans IDE respectively.

After you installed all of these, start NetBeans IDE, add Glassfish into Service tab in NetBeans IDE.

The Sample application

To demonstrate the basic usage of MVC spection, I will port the task board sample which I have implemented in the Spring4 Sandbox to demonstrate Spring MVC.

Simply, it includes the following features.

  1. List tasks by status, display the tasks in 3 columns(like a simple kanban).
  2. Create a new task.
  3. Edit and update task.
  4. Update task stauts(move to different columns in the task list).
  5. Delete task if it is done.

Create a project skeleton

First of first, you should create a simple project skeleton as start point.

If you are using NetBeans IDE, it is easy to create a Maven based Java EE 7 web project in IDE directly, and add the registered Glassfish as runtime server.

It should include Java EE 7 web artifact as the dependency.

<dependency>
    <groupId>javax</groupId>
    <artifactId>javaee-web-api</artifactId>
    <version>7.0</version>
    <scope>provided</scope>
</dependency>

Add additional MVC api and the implemnetation dependencies.

<dependency>
    <groupId>javax.mvc</groupId>
    <artifactId>javax.mvc-api</artifactId>
    <version>1.0-edr2</version>
</dependency>
<dependency>
    <groupId>org.glassfish.ozark</groupId>
    <artifactId>ozark</artifactId>
    <version>1.0.0-m02</version>
    <scope>runtime</scope>
</dependency>

ozark is the default reference implemnetation of MVC 1.0 specificaiton, which will shipped with Glassfish 5. Currently it is still under active development, what we are using here may be changed in the future.

Here we used Glassfish 4.1.1 as target runtime, so you should include them in the deployment package.

When Glassfish 5 is ready for Java EE 8, these two dependencies can be excluded and removed from POM.

Declare the MVC application

MVC does not reinvent the wheel, it reuses the effort of JAXRS specificaiton.

Similar with activiating JAXRS application, You can declare a customApplicationas our MVC application entry.

@ApplicationPath("mvc")
public class MvcConfig extends Application {

    @Override
    public Set<Class<?>> getClasses() {
        return Collections.singleton(TaskController.class);
    }
}

TaskControlleris a controller, it acts as the C in MVC pattern.

Controller

MVC uses a@Controllerannotation to declare a JAXES resource as Controller.

@Path("tasks")
@Controller
public class TaskController {

    @GET
    @View("tasks.jspx")
    public void allTasks() {
        log.log(Level.INFO, "fetching all tasks");

        List<Task> todotasks = taskRepository.findByStatus(Task.Status.TODO);
        List<Task> doingtasks = taskRepository.findByStatus(Task.Status.DOING);
        List<Task> donetasks = taskRepository.findByStatus(Task.Status.DONE);

        log.log(Level.INFO, "got all tasks: todotasks@{0}, doingtasks@{1}, donetasks@{2}", new Object[]{todotasks.size(), doingtasks.size(), donetasks.size()});

        models.put("todotasks", todotasks);
        models.put("doingtasks", doingtasks);
        models.put("donetasks", donetasks);

    }
}

@Viewannotation indicates the view(eg. JSP pages) a void method will return.

Model

Modelsis a contrainer to hold the model datas that will be transfered to the view.

View

Have a look at thetasks.jspxfile, I just copied some code snippets here, please checkout the source codes for details.

<div class="col-md-4 col-xs-12">
    <div class="panel panel-default">
        <!-- Default panel contents -->
        <div class="panel-heading">
            <span class="glyphicon glyphicon-list-alt" aria-hidden="true"><jsp:text /></span>
            TODO
        </div>
        <div class="panel-body">
            <p>Tasks newly added in the backlog.</p>
        </div>

        <!-- List group -->
        <c:if test="${not empty todotasks}">
            <ul id="todotasks" class="list-group">
                <c:forEach var="task" begin="0" items="${todotasks}">
                    <li class="list-group-item">
                        <h4>
                            <span>#${task.id} ${task.name}</span> <span class="pull-right">
                                <c:url var="taskUrl" value="tasks/${task.id}" /> <c:url
                                    var="taskEditUrl" value="tasks/${task.id}/edit" /> <a
                                    href="${taskUrl}"> <span class="glyphicon glyphicon-file"
                                                         aria-hidden="true"><jsp:text /></span>
                                </a> <a href="${taskEditUrl}"> <span
                                        class="glyphicon glyphicon-pencil" aria-hidden="true"><jsp:text /></span>
                                </a>
                            </span>
                        </h4>
                        <p>${task.description}</p>
                        <p>
                            <c:url var="markDoingUrl"
                                   value="/mvc/tasks/${task.id}/status" />
                        <form action="${markDoingUrl}" method="post">
                            <input type="hidden" name="_method" value="PUT"><jsp:text /></input>
                            <input type="hidden" name="status" value="DOING"><jsp:text /></input>
                            <button type="submit" class="btn btn-sm btn-primary">
                                <span class="glyphicon glyphicon-play" aria-hidden="true"><jsp:text /></span>
                                START
                            </button>
                        </form>
                        </p>
                    </li>
                </c:forEach>
            </ul>
        </c:if>
    </div>
</div>

No surprise, just pure JSP files, I used the JSP xml form in this sample.

By default the views should be put in the /WEB-INF/views folder in projects.

In this example, when you send a GET request to /ee8-mvc/mvc/tasks, theallTasks()method will handle this request, then find data(tasks by status here) from database, and put the query results into aModelscontainer, in the view pages the model data can be accessed via el directly.

The path(/ee8-mvc/mvc/tasks) is the combination of context path, mvc application path, and controller path.

Source codes

  1. Clone the codes from my github.com account.

    https://github.com/hantsy/ee8-sandbox/

  2. Open the mvc project in NetBeans IDE.

  3. Run it on Glassfish server.
  4. After it is deployed and running on the Glassfish application server, navigate http://localhost:8080/ee8-mvc/mvc/tasks in your favorite browser.

    https://github.com/hantsy/ee8-sandbox/wiki/mvc-tasks.png

转载于:https://my.oschina.net/hantsy/blog/661428

相关文章:

  • 产品经理问我:手动创建线程不香吗,为什么非要用线程池呢?
  • 将桌面上的硬盘移除
  • 白话Mysql的锁和事务隔离级别!死锁、间隙锁你都知道吗?
  • Jquery datatables 使用方法
  • 基于SpringBoot实现文件的上传下载
  • 作为一个后端开发,你需要了解多少Nginx的知识?
  • CAShapeLayer(持续更新)
  • 一个成熟的Java项目如何优雅地处理异常
  • UITableView分页
  • 分布式集群环境下,如何实现每个服务的登陆认证?
  • 【中亦安图】Oracle内存过度消耗风险提醒(6)
  • 你知道JWT是什么吗?它和Session的区别又在哪里?
  • hadoop家族成员
  • 项目经理最近感觉系统慢了,想知道整个系统每个方法的执行时间
  • 获得指定文件夹所有文件的路径
  • Android框架之Volley
  • iBatis和MyBatis在使用ResultMap对应关系时的区别
  • JavaScript设计模式系列一:工厂模式
  • LeetCode18.四数之和 JavaScript
  • php ci框架整合银盛支付
  • React的组件模式
  • RedisSerializer之JdkSerializationRedisSerializer分析
  • TypeScript迭代器
  • Zsh 开发指南(第十四篇 文件读写)
  • - 概述 - 《设计模式(极简c++版)》
  • 给新手的新浪微博 SDK 集成教程【一】
  • 回顾 Swift 多平台移植进度 #2
  • 近期前端发展计划
  • 删除表内多余的重复数据
  • 使用 @font-face
  • 微信如何实现自动跳转到用其他浏览器打开指定页面下载APP
  • MiKTeX could not find the script engine ‘perl.exe‘ which is required to execute ‘latexmk‘.
  • mysql面试题分组并合并列
  • Play Store发现SimBad恶意软件,1.5亿Android用户成受害者 ...
  • (1)Map集合 (2)异常机制 (3)File类 (4)I/O流
  • (3)llvm ir转换过程
  • (C#)if (this == null)?你在逗我,this 怎么可能为 null!用 IL 编译和反编译看穿一切
  • (libusb) usb口自动刷新
  • (排序详解之 堆排序)
  • (三)模仿学习-Action数据的模仿
  • (一一四)第九章编程练习
  • (转) SpringBoot:使用spring-boot-devtools进行热部署以及不生效的问题解决
  • (转)拼包函数及网络封包的异常处理(含代码)
  • **CI中自动类加载的用法总结
  • .bat批处理出现中文乱码的情况
  • .htaccess配置重写url引擎
  • .Net7 环境安装配置
  • .NET开源项目介绍及资源推荐:数据持久层 (微软MVP写作)
  • .net知识和学习方法系列(二十一)CLR-枚举
  • .net专家(张羿专栏)
  • .vimrc php,修改home目录下的.vimrc文件,vim配置php高亮显示
  • ??javascript里的变量问题
  • @软考考生,这份软考高分攻略你须知道
  • [ solr入门 ] - 利用solrJ进行检索
  • [2023年]-hadoop面试真题(一)