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)


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
<?xml version="1.0" encoding="UTF-8"?>
    <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


1
2
3
4
5
6
7
8
9
10
<tiles-definitions>
  
 <definition name="defaultTemplate" template="/WEB-INF/jsp/template/template.jsp">
  <put-attribute name="header" value="/WEB-INF/jsp/template/header.jsp">
  <put-attribute name="menu" value="/WEB-INF/jsp/template/menu.jsp">
  <put-attribute name="body" value="/WEB-INF/jsp/template/body.jsp">
  <put-attribute name="footer" value="/WEB-INF/jsp/template/footer.jsp">
 </put-attribute></put-attribute></put-attribute></put-attribute></definition>
  
</tiles-definitions>

Adım 5 :

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


1
2
3
4
5
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


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
<%--
    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.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<%--
    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.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<%--
    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.)


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<%--
    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)


1
2
3
4
5
6
7
8
9
10
<%--
    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ş.)


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<%--
    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.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
(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


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
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


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
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)


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
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


1 yorum:

  1. Superb blog you have here but I was wondering if you knew of any community forums that cover the same topics discussed in this article? I'd really love to be a part of community where I can get advice from other knowledgeable people that share the same interest. If you have any recommendations, please let me know. Kudos! Our staffing company in chennai's team come with years of industry experience to help takent acquisitions teams find hightly-qualified professionals that align with an organization's culture, goals and objectives.

    YanıtlaSil