MVC Annotation Driven trong Spring MVC là gì? Cách sử dụng và áp dụng?

mvc:annotation-driven là  một chú thích được gắn trong thẻ nên được thêm vào file cấu hình  xml ứng dụng  của bạn. Thẻ này mặc định của các thành phần cơ bản cần thiết cho việc uỷ thác các yêu cầu điều khiển trong ứng dụng của bạn.

Cách sử dụng : 

Các bạn chỉ cần thêm chú thích này vào trong file xml ứng dụng :

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
                http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
 
    <mvc:annotation-driven  />
 
</beans>

Vậy <mvc:annotation-driven> được áp dụng  và hỗ trợ gì cho chúng ta ? 

  • Hỗ trợ cho các định dạng số với @NumberFormat
  • Hỗ trợ cho các định dạng ngày, lịch, và thời gian  @DateTimeFormat.
  • Hỗ trợ cho việc chứng thực đầu vào @Controller với @Valid. 
  • Hỗ trợ đọc và viết XML trên classpath.
  • Hỗ trợ đọc và viết JSON trên classpath.

Ví dụ áp dụng :

Bây giờ sẽ lấy một ví dụ để các bạn dễ hiểu nhé,kiến thức là vậy nhưng biết cách áp dụng là một điều hoàn toàn khác? Mình sẽ lấy ví dụ ở đây là trường hợp @Valid cho form login,một trong những trường hợp mà mvc:annotation-driven hỗ trợ.

Đầu tiên code trang LoginController :

 

package controller;

import javax.validation.Valid;

import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import entities.User;

@Controller
@RequestMapping(value="login")
public class LoginController {
	
	@RequestMapping(method=RequestMethod.GET)
	public String index(){
		return "login";
	}
	
	@RequestMapping(method=RequestMethod.POST)
	public String index(@Valid @ModelAttribute("user") User user,BindingResult bindingResult){
		if(bindingResult.hasErrors()){
			return "login";
		}
		return "login";
	}
}

2.Trang login.jsp :

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@taglib uri="http://www.springframework.org/tags/form"  prefix="form"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Upload file Spring MVC Framework</title>
</head>
<body style="margin:0 auto; width:550px;height:350px">
	<div style="background:#E4F4F2;padding:30px;">
		<h1>Form Login</h1>
		<div>
			<div class="left"> 
				<form action="${pageContext.request.contextPath}/login" method="post" >
					Username : <input type="text"  value=""  name="username" /><br /><br />
					<form:errors path="user.username" cssStyle="color:red"></form:errors><br />
					Password : <input type="text"  value=""  name="password" /><br /><br />
					<form:errors path="user.password" cssStyle="color:red"></form:errors><br />
					<input name="submit" value="Login" type="submit" />
				</form>
			</div>
		</div>
	</div>
</body>
</html>

3.Đối tượng User

package entities;

import org.hibernate.validator.constraints.NotEmpty;

public class User {
	private int id_user;
	@NotEmpty(message="Username không được để trống")
	private String username;
	@NotEmpty(message="Password không được để trống")
	private String password;
	public int getId_user() {
		return id_user;
	}
	public void setId_user(int id_user) {
		this.id_user = id_user;
	}
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	
	
}

4.web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
  <display-name>uploadfiledemo</display-name>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
    
  </welcome-file-list>
  
   <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
    
    <servlet-mapping>
		<servlet-name>default</servlet-name>
		<url-pattern>*.png</url-pattern>
		<url-pattern>*.gif</url-pattern>
		<url-pattern>*.jpg</url-pattern>
		<url-pattern>*.jpeg</url-pattern>
	</servlet-mapping>
</web-app>

5.dispatcher-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd
        ">
	<context:component-scan base-package="controller" />
	<bean id="jspviewResolver"
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/WEB-INF/jsp/" />
		<property name="suffix" value=".jsp" />
	</bean>
</beans>

5.index.jsp

<% response.sendRedirect(request.getContextPath()+"/login");%>

Sau khi config,code tất cả các file,chúng ta sẽ chạy dự án.

Khi nhấn nút Login thì sẽ không thể valid form khi nhập rỗng,lý do vì không sử dụng chú thích   <mvc:annotation-driven>.Giờ các bạn thêm chú thích này vào trong file dispatcher-servlet.xml.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd
        ">
	<context:component-scan base-package="controller" />
	<mvc:annotation-driven/>
	<bean id="jspviewResolver"
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/WEB-INF/jsp/" />
		<property name="suffix" value=".jsp" />
	</bean>
</beans>

Sau khi chạy dự án lại,nhấn nút Login,chúng ta đã valid được thông báo form login.

Như vậy,ở bài này các bạn đã hiểu rõ về bản chất của chú thích <mvc:annotation-driven> trong java spring mvc.

Chúc các bạn thực hiện thành công!

 

x