Breaking News

Helloword với Java Spring theo mô hình MVC

Giới thiệu về Spring FrameWork

Spring FrameWork được ra đời từ năm 2003 bởi tác giả Rod Johnson. Đây là một open source dùng để phát triển các ứng dụng bằng Java.
Với Spring Framework các nhà phát triển có thể tạo ra các mã có hiệu suất cao, dễ kiểm thử và có thể sử dụng lại được.

Tìm hiểu nguyên lý hoạt động của một ứng dụng web sử dụng Java Spring


  
Ở trên là nguyên lý hoạt động của một website sử dụng java spring theo mô hình MVC. Mình sẽ giải thích rõ như sau:
- Khi người dùng nhập một đường dẫn trên trình duyệt thì đó được gọi là Request. Trong Spring MVC, DispatcherServlet sẽ làm nhiệm vụ hứng toàn bộ những Request. Sau khi nhận được Request, DispatcherSerlet kích hoạt Handler Mapping. Lúc này Handler Mapping sẽ có nhiệm vụ kiểm tra xem cái Request mà DispatcherServlet vừa nhận đang nằm ở trong Controller nào và trả lại kết quả cho DispatcherServlet. Tiếp theo DispatcherServlet sẽ gọi đến Controller mà vừa nhận được từ Handler Mapping. Sau khi controller xử lý xong thì sẽ phản hồi lại cho DispatcherServlet biết View nào sẽ được trả ra. DispatcherServlet tiếp tục tương tác với View Resolver. View Resolver nhận được yêu cầu là cần phải trả ra view abc gì đấy mà controller phản hồi. View Resolver sẽ xử lý gửi lại cho DispatcherServlet biết được view abc đấy đang nằm ở đâu. Cuối cùng thì DispatcherServlet sẽ truy xuất vào View và phản hồi lại cho người dùng

Demo chương trình Login HelloWorld  với java spring

- Tạo project với maven project


Bạn nhấn chọn như hình và nhấn next




 Tiếp theo bạn cần khai báo những thông tin như hình dưới. Ở đây, Group Id là tên người code dự án, Atifact Id là tên dự án, Packing là định dạng khi build dự án. Với java spring thì chọn định dạng build ra là .war


Sau khi nhập xong chọn Finish để khởi tạo dự án. Kết quả được 




Cấu hình các file và thư mục cho web


Cấu hình file pom.xml để khởi tạo các dependency cho maven

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.caodat</groupId>
  <artifactId>HelloWorld</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>war</packaging>
  <dependencies>
      <!-- https://mvnrepository.com/artifact/junit/junit -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.0.3.RELEASE</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>4.0.0</version>
            <scope>provided</scope>
        </dependency>
  </dependencies>
</project>


Cấu hình file web.xml 

<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.4"
    xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
   http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
    <display-name>Archetype Created Web Application</display-name>
    <servlet>
        <servlet-name>HelloWorld</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>HelloWorld</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <welcome-file-list>
        <welcome-file>/WEB-INF/views/login.jsp</welcome-file>
    </welcome-file-list>

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/HelloWorld-servlet.xml</param-value>
    </context-param>
</web-app>


Cấu hình file HelloWorld-servlet.xml

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
    http://www.springframework.org/schema/mvc
    http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
    http://www.springframework.org/schema/tx
    http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-4.0.xsd">

    <context:component-scan base-package="controllers" />

    <bean
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/views/" />
        <property name="suffix" value=".jsp" />
    </bean>
</beans>


Tạo controllers LoginController

package controllers;

import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import models.User;

@Controller
public class LoginController {

    @RequestMapping (value = "/login", method = RequestMethod.GET )
    public String doGetLogin() {
        System.out.println("login");
        return "login";
    }
   
    @SuppressWarnings({ "null", "static-access" })
    @RequestMapping (value = "/login", method = RequestMethod.POST)
    public String doLogin(HttpServletRequest request,
            Model model,
            @RequestParam( value = "user-email" ) String userEmail,
            @RequestParam( value = "user-pass" ) String userPass
            ) {
        User.user_email = "datcx@bse-corp.com";
        User.user_pass = "1";
        System.out.println("Email: " + userEmail);
        System.out.println("Pass: " + userPass);
        System.out.println("User email: " + User.user_email);
        System.out.println("User pass: " + User.user_pass);
       
       
        if(userEmail.equals(User.user_email) && userPass.equals(User.user_pass)) {
            System.out.println("Login Success ");
            return "loginSuccess";   
        }{
            System.out.println("Login Error");
            model.addAttribute("loginError", "Email or password incorrect");
            return "login";
        }
       
    }
}
 

Tạo model User

package models;

public class User {
    public static String user_email;
    public static String user_pass;
}
 

Tạo view login.jsp

 <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!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=ISO-8859-1">
<title>HelloWorld Spring MVC</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<style>
    .form-signin
{
    max-width: 330px;
    padding: 15px;
    margin: 0 auto;
}
.form-signin .form-signin-heading, .form-signin .checkbox
{
    margin-bottom: 10px;
}
.form-signin .checkbox
{
    font-weight: normal;
}
.form-signin .form-control
{
    position: relative;
    font-size: 16px;
    height: auto;
    padding: 10px;
    -webkit-box-sizing: border-box;
    -moz-box-sizing: border-box;
    box-sizing: border-box;
}
.form-signin .form-control:focus
{
    z-index: 2;
}
.form-signin input[type="text"]
{
    margin-bottom: -1px;
    border-bottom-left-radius: 0;
    border-bottom-right-radius: 0;
}
.form-signin input[type="password"]
{
    margin-bottom: 10px;
    border-top-left-radius: 0;
    border-top-right-radius: 0;
}
.account-wall
{
    margin-top: 20px;
    padding: 40px 0px 20px 0px;
    background-color: #f7f7f7;
    -moz-box-shadow: 0px 2px 2px rgba(0, 0, 0, 0.3);
    -webkit-box-shadow: 0px 2px 2px rgba(0, 0, 0, 0.3);
    box-shadow: 0px 2px 2px rgba(0, 0, 0, 0.3);
}
.login-title
{
    color: #555;
    font-size: 18px;
    font-weight: 400;
    display: block;
}
.profile-img
{
    width: 96px;
    height: 96px;
    margin: 0 auto 10px;
    display: block;
    -moz-border-radius: 50%;
    -webkit-border-radius: 50%;
    border-radius: 50%;
}
.need-help
{
    margin-top: 10px;
}
.new-account
{
    display: block;
    margin-top: 10px;
}
</style>
</head>
<body>
<div class="container">
    <div class="row">
        <div class="col-sm-6 col-md-4 col-md-offset-4">
            <h1 class="text-center login-title">Login - HelloWorld Spring MVC</h1>
            <div class="account-wall">
                <img class="profile-img" src="https://lh5.googleusercontent.com/-b0-k99FZlyE/AAAAAAAAAAI/AAAAAAAAAAA/eu7opA4byxI/photo.jpg?sz=120"
                    alt="">
                <form class="form-signin" method="post" action="/HelloWorld/login">
                <p class="text-center text-danger">${ loginError }</p>
                <input type="text" name="user-email" class="form-control" placeholder="Email" required autofocus>
                <input type="password" name="user-pass" class="form-control" placeholder="Password" required>
                <button class="btn btn-lg btn-primary btn-block" type="submit">
                    Sign in</button>
                <label class="checkbox pull-left">
                    <input type="checkbox" value="remember-me">
                    Remember me
                </label>
                <a href="#" class="pull-right need-help">Need help? </a><span class="clearfix"></span>
                </form>
            </div>
            <a href="#" class="text-center new-account">Create an account </a>
        </div>
    </div>
</div>
</body>
</html>


 Tạo view loginSuccess để hiển thị kết quả đăng nhập thành công

 <%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!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>Insert title here</title>
</head>
<body>
    <h1 style="font-size:30px; text-align:center;">Đăng nhập thành công</h1>
</body>
</html>


Click chuột phải vào project -> Properties -> Java Build Path -> Chọn như hình. Bạn phải cấu hình như vậy để eclipse mới chạy ứng dụng của bạn trong môi trường jre và chạy các dependency của maven.



 Cuối cùng là nhấp chuột phải vào project và chọn run trên server.
Kết quả thu được sẽ là