跳至主要内容

博文

目前显示的是 四月, 2016的博文

Getting started with Java EE8 MVC(9)-View engine

View engine Spring MVC provides View and ViewResolver to find view and render view. MVC provides ViewEngine to do the same job.
View Engine By default, ozark support tow built-in view engines to render JSP and Facelets, respectively.
In the org.glassfish.ozark.ext (check org.glassfish.ozark.ext) package, ozark provides several ViewEngine implementations for the popular template.
ThymeleafFreemarkerVelocityHandlebarsMustacheAsciidocStringtemplateJade JSR223(Script engine)Facelets Originally, Facelets is part of JSF specification, now it can be worked as a standard template engine in MVC.
Activate Facelets in web.xml.
<servlet> <servlet-name>Faces Servlet</servlet-name> <servlet-class>javax.faces.webapp.FacesServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>Faces Servlet</servlet-name> <url-pattern>*.xhtml</url-pattern> </servlet-mapp…

Getting started with Java EE 8 MVC(8)-Parameter conversion

Parameter conversion Spring MVC provides ConversionService to convert data to bean target type from from data.
In MVC, we can use custom ParamConverter to convert form data to the target type.
Parameter conversion As an example, add a dueDate to Task entity. We need to convert the form field value(it is a String) to LocalDate type.
Create a custom ParamConverterProvider for LocalDate.
@Provider public class CustomConverterProvider implements ParamConverterProvider { final DateTimeFormatter DATE_FORMAT = DateTimeFormatter.ISO_DATE; @Override public <T> ParamConverter<T> getConverter(Class<T> rawType, Type genericType, Annotation[] annotations) { if (rawType.getName().equals(LocalDate.class.getName())) { return new ParamConverter<T>() { @Override public T fromString(String value) { return value != null ? (T) LocalDate.parse(value, DATE_FORMAT) : null; } …

Getting started with Java EE 8 MVC(7)-MVC Security

MVC Security MVC has built-in some security features to protect pages, eg. CSRF protection.
CSRF protection MVC has built-in CSRF protection, there is a Csrf interface.
Configure Csrf in the Application class. Override the getProperties method.
@Override public Map<String, Object> getProperties() { Map<String, Object> props = new HashMap<>(); props.put(Csrf.CSRF_PROTECTION, Csrf.CsrfOptions.EXPLICIT); //view folder //props.put(ViewEngine.DEFAULT_VIEW_FOLDER, ViewEngine.VIEW_FOLDER); return super.getProperties(); } And there are some options to configure CSRF via Csrf.CsrfOptions.
OFF to disable Csrf.EXPLICIT to enable Csrf wtih annotation @CsrfValid on the Controller method.IMPLICIT to enable Csrf autmaticially. No need @CsrfValid. Add annotation @CsrfValid on the Controller method.
@POST @CsrfValid @ValidateOnExecution(type = ExecutableType.NONE) public Response save(@Valid @BeanParam TaskForm form) { } In the view, add hidden field to insert th…

Getting started with Java EE8 MVC(6)-MVC and CDI

MVC and CDI In before posts, we have already use @Inject to inject CDI beans into the Controller class. In fact, MVC embraced CDI internally.
RedirectScoped There is a new CDI compatible scope named RedirectScoped introduced in MVC 1.0.
A bean annotated with @RedirectScoped annotation can be transfered between two requests, conceptly, it is similar with JSF Flash.
The AlertMessage is an example.
Declare a bean with @RedirectScoped annotation.
@RedirectScoped @Named("flashMessage") public class AlertMessage implements Serializable {} Inject it into a Controller class.
@Inject AlertMessage flashMessage; Access the bean properties in the view via EL.
<c:if test="${not empty flashMessage and not empty flashMessage.text}"> <div class="alert alert-${flashMessage.type} alert-dismissible" role="alert"> <button type="button" class="close" data-dismiss="alert" aria-labe…

Getting started with Java EE8 MVC(5)-Page navigation

Page navigation As introducing the feature pieces of the MVC specification, we have visited most of views in this demo. In fact, when you desgin a website, you should have a map for the page navigation among all views.
View navigation summaryWhen the appliation starts up, it will display the task list view.User can create a new task by clicking the New Task button, the task creating view is displayed.When user input the task title and description, submit the form. If the task is submitted successfully, return the main task list view. The new created task should be in the list.If the task form data is invalid, show the validation errors.User can edit the new created task by click edit icon. It will read the task from database and fill the existing data into form fieldsThe submission progress is similiar with the new task subflow described in above 3.User can update the task status(TODO to DOING, or DOING to DONE). When the status is changed successfully, return to the task list.Us…

Getting started with Java EE8 MVC(4)-Handle PUT and DELETE request

Handle PUT and DELETE request When you try to submit a PUT or DELETE http request via form submission, and you want to invoke the methods annotated with @PUT or @DELETE in the Controller to handle the request.
Unfortunately it does not work.
There is a simple solution which can help us to overcome this issue.
If you have used Spring MVC before and I think you could know there is a HiddenMethodFilter in the Spirng MVC to fix this issue. Java EE 8 MVC does not ship the similar Filter, we can create one.
Solution Create a Filter to convert the request method to the target HTTP method.
@WebFilter(filterName = "HiddenHttpMethodFilter", urlPatterns = {"/*"}, dispatcherTypes = {DispatcherType.REQUEST}) public class HiddenHttpMethodFilter implements Filter { @Inject Logger log; /** * Default method parameter: {@code _method} */ public static final String DEFAULT_METHOD_PARAM = "_method"; private String methodParam = DEFAULT_ME…

Getting started with Java EE 8 MVC(3)-Exception Handling and form validation

Exception Handling and form validation When submitting a form, it should validate the form data before it is stored in the backend database.
Form binding and validation Like Spring MVC, Struts, Stripes, JSF etc. MVC provides the similiar progress to process form submission.
Gather user input form data.Convert form data to the target form bean. If there are some conversion failure, it is possbile to stop the progress and notify user.Bind the converted value to the form bean.Validate the form bean via Bean Validation. If there are some constraint voilations, it is possbile to stop the progress and notify user.Continue to process form. MVC provides a BindingResult to gather all of the binding errors and constraint voilations in the request.
Handling form validation Inject it in the controller class.
@Inject private BindingResult validationResult; In the controller method, add @Valid annotation on the methed parameters.
@ValidateOnExecution(type = ExecutableType.NONE) public Response save…

Getting started wtih Java EE 8 MVC(2)-Handling form submission

Handling form submission In the tranditional MVC applications, the mostly-used HTML methods should GET and POST.
POST method is usually used in the form submission, aka form post.
In order to create a new task, you should follow the flow.
In the task list view, click Add Task button to enter the creating task view.Fill the fields of the task form and submit. It will return to task list view.Display the creating page Firstly display the task creating page.
@GET @Path("new") public Viewable add() { log.log(Level.INFO, "add new task"); return new Viewable("add.jspx"); } Viewable is another approach to indicate a view path, I have motioned the @View annotation in the first post.
The add.jspx page code snippets.
<div class="row"> <div class="col-md-12"> <c:url var="formActionUrl" value="/mvc/tasks"/> <form id="form" name="form" role="form" cla…

Getting started with Java EE 8 MVC

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 fo…