12 Ekim 2015 Pazartesi

Spring MVC 4 AngularJS Bootstrap Entegrasyonu Final

bootstrap spring
            Maven Yapılı Spring MVC 4 Web ile AngularJS ve Bootstrap Nasıl Yapılandırılabilir ve Kullanılabilir.




Başla

Kullanılan Teknolojiler

  • Maven 4.0
  • Netbeans IDE 8.0.2
  • Spring 4.1.6.RELEASE
  • Glashfish 4.1
  • Java EE 7
  • Apache Tiles 3.0.5
  • SLF4J 1.7.6
  • AngularJS 1.4.7
  • Bootstrap 3.2.0



Spring Tutorial
Spring MVC
LOG4J Kullanımı ?
LOG4J Hatası Çözümü   log4j:WARN No appenders could be found for logger

Adım 1 :

Netbeans Maven Web Projesi Oluşturalım. Nasıl Oluşturulur?


Adım 2 :

Aşağıdaki Proje Yapısını Oluşturalım.


Maven AngularJS Bootstrap
Res2.1. - Proje Dosya Yapısı

Adım 3 :

Kullanılacak Tüm Teknolojileri Projeye Bağlayalım. (pom.xml)


<?xml version="1.0" encoding="UTF-8"?>
<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.mycompany</groupId>
    <artifactId>MySpringMVC</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>

    <name>MySpringMVC</name>

    <properties>
        <endorsed.dir>${project.build.directory}/endorsed</endorsed.dir>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <jstl.version>1.2</jstl.version>
        <javax.servlet.version>3.0.1</javax.servlet.version>
    </properties>
    
    <dependencies>
        <dependency>
            <groupId>javax</groupId>
            <artifactId>javaee-web-api</artifactId>
            <version>7.0</version>
            <scope>provided</scope>
        </dependency>
        <!-- spring-context which provides core functionality -->
  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-context</artifactId>
   <version>4.1.6.RELEASE</version>
  </dependency>
 
  <!-- The spring-aop module provides an AOP Alliance-compliant aspect-oriented 
   programming implementation allowing you to define -->
  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-aop</artifactId>
   <version>4.1.6.RELEASE</version>
  </dependency>
 
  <!-- The spring-webmvc module (also known as the Web-Servlet module) contains 
   Spring’s model-view-controller (MVC) and REST Web Services implementation 
   for web applications -->
  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-webmvc</artifactId>
   <version>4.1.6.RELEASE</version>
  </dependency>
 
  <!-- The spring-web module provides basic web-oriented integration features 
   such as multipart file upload functionality and the initialization of the 
   IoC container using Servlet listeners and a web-oriented application context -->
  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-web</artifactId>
   <version>4.1.6.RELEASE</version>
  </dependency>
                
                 <dependency>  
                        <groupId>javax.servlet</groupId>  
                        <artifactId>javax.servlet-api</artifactId>  
                        <version>${javax.servlet.version}</version>  
                        <scope>provided</scope> 
                </dependency> 

                <dependency>  
                        <groupId>jstl</groupId>  
                        <artifactId>jstl</artifactId>  
                        <version>${jstl.version}</version>  
                </dependency>
                
                <!--Twitter Bootstrap-->
                <dependency>
                        <groupId>org.webjars</groupId>
                        <artifactId>bootstrap</artifactId>
                        <version>3.2.0</version>
                        <exclusions>
                            <exclusion>
                                <groupId>org.webjars</groupId>
                                <artifactId>jquery</artifactId>
                            </exclusion>
                        </exclusions>
                </dependency>

                <dependency>
                        <groupId>org.webjars</groupId>
                        <artifactId>jquery</artifactId>
                        <version>2.1.1</version>
                </dependency>
                <!--AngularJS-->
                
                <dependency>
                        <groupId>org.webjars.bower</groupId>
                        <artifactId>angularjs</artifactId>
                        <version>1.4.7</version>
                </dependency>
                
                <!--Apache Tiles-->
  
                <dependency>
   <groupId>org.apache.tiles</groupId>
   <artifactId>tiles-extras</artifactId>
   <version>3.0.5</version>
  </dependency>
  <dependency>
   <groupId>org.slf4j</groupId>
   <artifactId>slf4j-api</artifactId>
   <version>1.7.6</version>
  </dependency>
  <dependency>
   <groupId>org.slf4j</groupId>
   <artifactId>slf4j-log4j12</artifactId>
   <version>1.7.6</version>
  </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.1</version>
                <configuration>
                    <source>1.7</source>
                    <target>1.7</target>
                    <compilerArguments>
                        <endorseddirs>${endorsed.dir}</endorseddirs>
                    </compilerArguments>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <version>2.3</version>
                <configuration>
                    <failOnMissingWebXml>false</failOnMissingWebXml>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-dependency-plugin</artifactId>
                <version>2.6</version>
                <executions>
                    <execution>
                        <phase>validate</phase>
                        <goals>
                            <goal>copy</goal>
                        </goals>
                        <configuration>
                            <outputDirectory>${endorsed.dir}</outputDirectory>
                            <silent>true</silent>
                            <artifactItems>
                                <artifactItem>
                                    <groupId>javax</groupId>
                                    <artifactId>javaee-endorsed-api</artifactId>
                                    <version>7.0</version>
                                    <type>jar</type>
                                </artifactItem>
                            </artifactItems>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

</project>


Adım 4 :

(tiles.xml) Template belirleyelim



 
 
  
  
  
  
 
 



Adım 5 :

(log4j.properties)Loglama İçin Gerekli Tanımlamarı Yapalım. Projeyi Build Edelim.


log4j.rootLogger=INFO, CONSOLE

log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern=%d{ABSOLUTE} %-5p [%c{1}:%L] %m%n

Adım 6 :

template.jsp


<%-- 
    Document   : template
    Author     : gurkan
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@ taglib uri="http://tiles.apache.org/tags-tiles" prefix="tiles"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<c:set var="cp" value="${pageContext.request.servletContext.contextPath}" scope="request"></c:set>
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1, maximum-scale=1">
<link rel="stylesheet" type="text/css" href="${cp}/resources/css/site.css" />
<link rel='stylesheet' href='${cp}/webjars/bootstrap/3.2.0/css/bootstrap.min.css'>
</head>
 
<body>
    <div class="container">
        <div class="row" style="background-color: burlywood;">
 <div class="header col-md-12">
  <tiles:insertAttribute name="header" />
 </div>
        </div>
        <div class="row" >
 <div class="menu col-md-4" style="background-color: coral;">
  <tiles:insertAttribute name="menu" />
 </div>
 <div class="body col-md-8" style="background-color: antiquewhite;">
  <tiles:insertAttribute name="body" />
 </div>
        </div>
        <div class="row" style="background-color: chartreuse;">
 <div class="footer col-md-12">
  <tiles:insertAttribute name="footer" />
 </div>
        </div>
    </div>
     <!--Script Bootstrap & Jquery -->
    <script type="text/javascript" src="${cp}/webjars/bootstrap/3.2.0/js/bootstrap.min.js"></script>
    <script type="text/javascript" src="${cp}/webjars/jquery/2.1.1/jquery.min.js"></script> 
    <script type="text/javascript" src="${cp}/webjars/angularjs/1.4.7/angular.min.js"></script> 
    <script type="text/javascript" src="${cp}/resources/js/app.js"></script> 
</body>
</html>


Adım 7 :

body.jsp,header.jsp,footer.jsp dosyalarını şimdilik aşağıdaki gibi sadece belirtelim.


<%-- 
    Document   : footer
    Author     : gurkan
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
        <h1>Footer</h1>
    </body>
</html>


Adım 8 :

menu.jsp sayfasını bootstrap kullanmak amacıyla biraz özelleştirelim.


<%-- 
    Document   : menu
    Author     : gurkan
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<c:set var="cp" value="${pageContext.request.servletContext.contextPath}" scope="request"></c:set>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>  
        <h1>List</h1>
        <ul class="nav nav-pills nav-stacked">
                <li role="presentation" class="active"><a href="${cp}/">AnaSayfa</a></li>
                <li role="presentation"><a href="${cp}/page1">Page1</a></li>
                <li role="presentation"><a href="${cp}/page2">Page2</a></li>
        </ul>
    </body>
</html>


Adım 9 :

index.jsp (Dikkat! Sadece template body kısmı override ediliyor.)


<%-- 
    Document   : index
    Author     : gurkan
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://tiles.apache.org/tags-tiles" prefix="tiles"%>
<c:set var="cp" value="${pageContext.request.servletContext.contextPath}" scope="request"></c:set>
<!DOCTYPE html>
<tiles:insertDefinition name="defaultTemplate" >
                        
    <tiles:putAttribute name="body" >
    <body ng-app="myModule">
        
        <h1>Hello World!</h1>   
        <h2${msg}</h2>
        <h2>
        <div ng-controller="MyController">
            {{myValue}}
        </div>
        <c:out value="JSTL Hello World!"></c:out>
        </h2>
       <button type="button" class="btn btn-success" id="bas">Click mE</button>
        </tiles:putAttribute>
</tiles:insertDefinition>    


Adım 10 :

page1.jsp (Müdahale edilmemiş sayfa)


<%-- 
    Document   : page1
    Author     : gurkan
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@ taglib uri="http://tiles.apache.org/tags-tiles" prefix="tiles"%>
<!DOCTYPE html>

<tiles:insertDefinition name="defaultTemplate" />


Adım 11 :

page2.jsp (Şablonun body kısmı değiştirilmiş.)


<%-- 
    Document   : page2
    Author     : gurkan
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@ taglib uri="http://tiles.apache.org/tags-tiles" prefix="tiles"%>
<!DOCTYPE html>
<tiles:insertDefinition name="defaultTemplate" >
                        
    <tiles:putAttribute name="body" >
         
        
         Ben Tasarım Yapılmış Body
         <input type="button" value="Bootstrap" class="btn btn-success" />
                            
    </tiles:putAttribute>
                        
                        
                        
                        
                        
                        
</tiles:insertDefinition>


Adım 12 :

app.js (AngularJS ve JQuery Testi İçin Basit Örnek) Ayrıca site.css ile de özelleştirme yapabiliriz.


(function (){
    var app = angular.module('myModule', []);
    
    app.controller('MyController', ['$scope', function($scope) {
        $scope.myValue = 'AngularJS Merhaba Dünya!';
    }]);

})();

$(document).ready(function(){
   
    $('#bas').click(function(){
        alert("Bana Tiklandi.");
    });
});
    
   
    



Adım 13 :

Config.java


package com.mycompany.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;
import org.springframework.web.servlet.view.UrlBasedViewResolver;
import org.springframework.web.servlet.view.tiles3.TilesConfigurer;
import org.springframework.web.servlet.view.tiles3.TilesView;


@Configuration
@ComponentScan("com.mycompany")
@EnableWebMvc
public class Config extends WebMvcConfigurerAdapter{
    
    @Bean
    public UrlBasedViewResolver xmlViewResolver(){
        UrlBasedViewResolver resolver = new UrlBasedViewResolver();
        resolver.setViewClass(TilesView.class);
        resolver.setOrder(1);
        return resolver;
    }
    
    @Bean
    public TilesConfigurer tilesConfigurer() {
        TilesConfigurer tilesConfigurer = new TilesConfigurer();
        tilesConfigurer.setDefinitions(new String[] { "/WEB-INF/tiles.xml" });
        tilesConfigurer.setCheckRefresh(true);
        return tilesConfigurer;
    }
    
    @Bean
    public ViewResolver viewResolver(){
    InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
        viewResolver.setViewClass(JstlView.class);
        viewResolver.setPrefix("/WEB-INF/jsp/view/");
        viewResolver.setSuffix(".jsp");
        viewResolver.setOrder(0);
        return viewResolver;
    
    }
    
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        //css ve js ulaşmak için
        registry.addResourceHandler("/resources/**").addResourceLocations("/WEB-INF/resources/");
        //bootstrap ve jquery sağlayan webjars ulaşmak için
        registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
    }
    
}


Adım 14 :

WebInitializer.java


package com.mycompany.config;

import javax.servlet.ServletRegistration.Dynamic;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;

public class WebInitializer implements WebApplicationInitializer{

    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {
        AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
        ctx.register(Config.class);
        ctx.setServletContext(servletContext);
        Dynamic servlet = servletContext.addServlet("dispatcher", new DispatcherServlet(ctx));
        servlet.addMapping("/");
        servlet.setLoadOnStartup(1);
        
    }
    
    
    
}


Adım 15 :

DefaultController.java (LOG4J basit kullanım)


package com.mycompany.controllers;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;


@Controller
public class DefaultController {
    private static final Logger logger = LoggerFactory.getLogger(DefaultController.class);
    
    @RequestMapping(value = "/" , method = RequestMethod.GET)
    public String index(ModelMap map) {
        logger.info("index deyim");
        map.put("msg", "Hello Spring 4 Web MVC!");
        return "index";
    }
    @RequestMapping(value = "/page1", method = RequestMethod.GET)
    public String page1() {
        logger.info("page1 deyim");
 return "page1";
    }
 
 @RequestMapping(value = "/page2", method = RequestMethod.GET)
    public String page2(ModelMap model) {
        logger.info("page2 deyim");
 return "page2";
    }
}


Adım 15 :

Projeyi Build ve Run Edelim.

Maven AngularJS Bootstrap Final Arayüz
Res15.1. - Uygulama Ekran Görüntüsü (index.jsp)

Maven AngularJS Bootstrap Final Arayüz - 2
Res15.2. - Uygulama Ekran Görüntüsü (page1.jsp)

Maven AngularJS Bootstrap Final Arayüz - 3
Res15.3. - Uygulama Ekran Görüntüsü (page2.jsp)

Maven AngularJS Bootstrap Final Arayüz - 4
Res15.4. - Uygulama Ekran Görüntüsü Mobil



Download   GitHub

Bitir


Hiç yorum yok:

Yorum Gönderme