Está en la página 1de 79

Spring Framework

Link: https://gist.github.com/risha9177719594/9961142

1. Ejemplo: Calcular inters con Spring

IntrestCalculatorClient.java
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

public class IntrestCalculatorClient {


public static void main(String args[]) throws Exception {
Resource res = new
ClassPathResource("SimpleIntCalculator.xml");
BeanFactory factory = new XmlBeanFactory(res);
SimpleIntCalculator cal= (SimpleIntCalculator)
factory.getBean("intCalculator");
double amount = cal.simpleIntrest(100.0, 12);
System.out.println("intrest for 100 rupies for 12 months is
: "+amount);
}

SimpleIntCalculator
public interface SimpleIntCalculator {
public double simpleIntrest(double principle,int months);

SimpleIntCalculator.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:aop="http://www.springframework.org/schema/aop"

xsi:schemaLocation="http://www.springframework.org/schema/beans

http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="intCalculator"
class="com.com.test.SimpleIntCalculatorImpl">
<property name="intrestRate" value="14.0" />
</bean>
</beans>
SimpleIntCalculatorImpl
public class SimpleIntCalculatorImpl implements SimpleIntCalculator{
private double intrestRate;

public double getIntrestRate() {


return intrestRate;
}

public void setIntrestRate(double intrestRate) {


this.intrestRate = intrestRate;
}

public double simpleIntrest(double principle, int months) {

return principle*months*intrestRate/100;
}

2. Ejemplo: Ejemplo de Servicio con Spring


Link: https://gist.github.com/risha9177719594/9961632

CommonServiceImpl.java

@Service("commonService")
public class CommonServiceImpl implements CommonService{

@Autowired
private CommonDAO cDao;

@Override
public List< TestBean > getSearch() {
List< TestBean > tList=cDao.getSearch();
return tList;
}
}

Display.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"


pageEncoding="ISO-8859-1"%>

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>


<%@ taglib prefix="form" uri="http://www.springframework.org/tags/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=ISO-8859-1">
<title>Insert title here</title>

<style type="text/css" media="screen">


@import '<c:url
value="/resources/css/dataTable/demo_page.css"/>';
@import '<c:url
value="/resources/css/dataTable/demo_table.css"/>';
@import '<c:url
value="/resources/css/dataTable/demo_table_jui.css"/>';
@import '<c:url
value="/resources/css/dataTable/themes/base/jquery-ui.css"/>';
@import '<c:url
value="/resources/css/dataTable/themes/smoothness/jquery-ui-
1.7.2.custom.css"/>';
@import "http://www.datatables.net/media/css/site_jui.ccss";
/*
* Override styles needed due to the mix of three different
CSS sources! For proper examples
* please see the themes example in the 'Examples' section of
this site
*/
.dataTables_info { padding-top: 0; }
.dataTables_paginate { padding-top: 0; }
.css_right { float: right; }
#example_wrapper .fg-toolbar { font-size: 0.8em }
#theme_links span { float: left; padding: 2px 10px; }
.sorting{background-color:#ccccff; height:22px; font-family:
Arial, Helvetica, sans-serif; color:#333333; font-size:11px;}
</style>

<link rel="stylesheet" type="text/css" href='<c:url


value="/resources/css/layout.css"/>'/>
<link rel="stylesheet" type="text/css" href='<c:url
value="/resources/css/dataTable/TableTools.css"/>'/>
<%-- <link rel="stylesheet" type="text/css" href='<c:url
value="/resources/css/dataTable/TableTools_JUI.css"/>'/> --%>
<script type='text/javascript' src='<c:url
value="/resources/js/dataTable/complete.js"/>'></script>
<script type='text/javascript' src='<c:url
value="/resources/js/dataTable/jquery-1.4.4.min.js"/>'></script>

<script type='text/javascript' src='<c:url


value="/resources/js/dataTable/jquery.dataTables.min.js"/>'></script>
<script type='text/javascript' src='<c:url
value="/resources/js/dataTable/jquery.dataTables.columnFilter.js"/>'></sc
ript>

<script type='text/javascript' src='<c:url


value="/resources/js/dataTable/TableTools.js"/>'></script>
<script type='text/javascript' src='<c:url
value="/resources/js/dataTable/ZeroClipboard.js"/>'></script>

<script type="text/javascript">
$(document).ready(function(){
$('#resultSet').dataTable()
.columnFilter({
aoColumns: [ null,
{ type: "text" },
{ type: "select", values: [ '','','',''] },
{ type: "text" },
{ type: "text" },
{ type: "text" },
{ type: "date-range"}//tobe updated once model
column is modified to date from string.
]

});
});

</script>
<script type="text/javascript">

var _gaq = _gaq || [];


_gaq.push(['_setAccount', 'UA-17838786-4']);
_gaq.push(['_trackPageview']);

(function () {
var ga = document.createElement('script'); ga.type =
'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ?
'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(ga, s);
})();

</script>
</head>
<body>
<form:form modelAttribute="tForm" methode="POST">
<table id="resultSet" cellpadding="0" cellspacing="0" border="0"
class="display" style="">
<thead>
<tr>
<th><input type="checkbox" /></th>
<th>ID</th>

<th>col1</th>
<th> col 2</th>
<th> col 3</th>
<th> col 4</th>
<th> col 5</th>
<th> col 6</th>
</tr>
</thead>
<tfoot>
<tr>
<th></th>
<th>ID</th>
<th> col 1</th>
<th> col 2</th>
<th> col 3</th>
<th> col 4</th>
<th> col 5</th>
<th> col 6</th>
</tr>
</tfoot>

<c:forEach items="${tForm.tbs }" var="tb" varStatus="status">


<tr> <td align="center"></td>
<td>${tb.Id}</td>
<td>${tb.value2}</td>

<td>${ tb.value23}</td>
<td>${ tb.value24}</td>
<td>${ tb.value25}</td>
<td>${ tb.value26}</td>
<td>${ tb.value27}</td>
</tr>
</c:forEach></table>
</form:form>
</body>
</html>

HomeController.java

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import javax.annotation.Resource;
import javax.validation.Valid;
import javax.xml.bind.JAXBException;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.support.SessionStatus;

@Controller
@RequestMapping("/")
public class HomeController {

@Resource(name="CommonService")
private CommonService commonService;
private static List<TestBean> tbs = new ArrayList< TestBean >();

@RequestMapping(value="/testSearch ", method = RequestMethod.GET)


@ExceptionHandler({SpringException.class})
public String pendingSearch(@ModelAttribute("tForm") TestForm
tForm,ModelMap model) {

tbs = commonService.getSearch();
tForm.setTbs (tbs);
model.addAttribute(tForm);
return "testSearch";
}

link.html

<!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>Insert title here</title>
</head>
<body>
<TABLE class=toolkit>
<TBODY>
<TR>
<TD><A href="/test/testSearch">Pending</A></TD></TR>
</TBODY></TABLE></TD>
</body>
</html>

TestDAOImpl.java
@Repository
public class TestDAOImpl implements TestDAO{

private SimpleJdbcTemplate jdbcTemplate;


private DataSource dataSource;

@Resource(name="dataSource")
public void createTemplate( DataSource dataSource1) {
this.jdbcTemplate = new SimpleJdbcTemplate(dataSource1);
this.dataSource=dataSource1;
}

@Override
public List< TestBean > getSearch() {
/*procReadProc =
new SimpleJdbcCall(dataSource);
Map<String,Object> args=new HashMap<String,Object>();
Map<String,Object> args1=new HashMap<String,Object>();
args.put(", "%");//in parameter name
args.put("", "%");
procReadProc.declareParameters();

System.out.println("hell"+procReadProc.getInParameterNames().size());
procReadProc.withProcedureName("");//procedure name
procReadProc.useInParameterNames("");// inparameter name
//procReadProc.setProcedureName("");
System.out.println(procReadProc.getProcedureName());
procReadProc.returningResultSet("reset", rm);
args1=procReadProc.execute(args);*/
List<PendingFSR> resultList = null;//(List<PendingFSR>)
args1.get("reset");//returns data
return resultList;
}

Springs Framework
IOC -- Inversion of Control
Simply said IOC help decouple (loosely couple) an application by handling its
dependencies. Insted of the programer creating an instance for an given
dependent object, the IOC Container holds the responsibility ([life cycle] creation,
destruction, lifetime, configuration, and dependencies) for all the Object's and
provides them as need using DI as Argument, Constructor, Setter & Interface
Injector's.

The Springs Implementation of IOC / Confguration


Spring's has may Context's (ApplicationContext implementations) depending on
the way they can be configured such as the couple of the few

FileSystemXmlApplicationContext -- Loads and configures based on an xml config


file from a local or remote and URI's
ClassPathXmlApplicationContext -- Loads and configures based on an xml config file
presnet in the classpath (both Global or Application)
XmlWebApplicationContext -- Used in the case of WEB applications
where ContextLoaderListener, DispatcherServlet us this context for there respective
applications. Where the default config file would be "/WEB-
INF/applicationContext.xml" for the root context, and "/WEB-INF/{servlet name}-
servlet.xml" for the respective serlvet. These can be overiden using the
contextParam contextConfigLocation.

The XML (bean.xml)

We always start off with the root element of the config as beans with the default
namespace bound to http://www.springframework.org/schema/beans which is used
for IOC (Bean Factory Configuration).
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
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.xsd">
<bean id="sample" class="java.lang.Object" />
</beans>

<beans/>

The beans tag houses all the other tags for the configuration, it supports the
following attributes
default-autowire-candidates -- class names (comma seperated) which need
to be autowired by default. (ex: *Person, Per)
default-autowire --
o default -- equals to no
o no -- do not autowire any thing
o byName -- identify the dependencies by bean/[id] (bean's id attribute)
o byType -- identify the property by its Class/type
o constructor -- autowire the constructor based on the argument's Type
default-destroy-method -- an no argument, void return method to be
invoked at time of destruction of an Object. The method should be part of
the Object, invoked only if present.
default-init-method -- an no argument, void return method to be invoked at
the time of Creation on each instance of an Object. The method should be
part of the Object, invoked only if present.
default-lazy-init -- Help determine when an instance of the Object needs
to be create
o default -- is false
o true -- create only on request for the Object
o false -- create at the time of Context Setup
default-merge -- ="default"
profile --

<bean/>

The bean tag is used to configured an Class instance, by how it should be initialized
and populated with different types of DI's.
class -- Class name including the package for which an instance would be
refred as this bean.
id -- an unique name to identify the bean
name -- helps create multiple aliases for the given bean by an space, comma,
semi-colon (any combination) seperated string.
<bean name="obj, object, random" class="java.lang.Object"></bean>
<bean name="obj object random" class="java.lang.Object"></bean>
<bean name="obj; object; random" class="java.lang.Object"></bean>
abstract -- an boolean value if set to true would prevent the bean for being
initialized / creation, instead it serves as an parent from which the children
can inherit its properties (only the tags inside it not the attributes).
parent -- name of the parent bean from which to inherit. Note: parent tags
can be overriden by the children.
scope
o singleton -- Create only an single instance for the given Context
o prototype -- Create an new instance when ever requested for
o request -- The instance of the bean is alive as long as the request is being
processed, its stored in HttpServletRequest using setAttribute once
processed the bean is destroyed.
o session -- The instance of the bean is alive as long as the session.

Note: request/session as applicable only in spring MVC

autowire -- see beans/[default-autowire], here its in respect to the


specfic bean tag only.
Event's / Life Cycle

init-method--
an void no argument method to be invoked at the time of
bean creation.
destroy-method -- an void no argument method to be invoked at the time of
bean being destroyed.
Custom Bean Factory

factory-bean -- name of the bean which would be the factory instance


factory-method -- method on the bean to be invoked to get an instance
if factory-bean is present or a static mehtod on the class.
NOTE: when using factory-method the return value is stored as the bean it is not
mandatory that it should be off type class. The class becomes useful when
the factory-method is static.

<property>

name -- name of the property for the given bean


value -- value to be set for the property
ref -- id/name/alias of an other bean to be set as the value

NOTE: If the property name / setter is not found Springs would throw an exception.

<constructor-arg>

index -- the position of the argument


name -- name of the argument
ref -- see property/[ref]
type -- data type of the argument ex. java.lang.String
value -- the value for the argument

<lookup-method>

Overrides a method in the given bean, where the method should an no argument,
with a return type, public|protected access, abstract or regular method.

<public|protected> abstract? <return-type> method()

name -- name of the method to be overridden


bean -- name of a bean which is of the same type as the method retun-type. This
bean would be returned when ever the method is invoked.

<replaced-method>

Replace / Override a method off an Springs managed Bean / Object.

name -- name of the method that needs to be replaced


replacer -- name of an been that implements MethodReplacer interface

<arg-type/> Help determine the method overloaded by the type of


arguments it accepts

o match -- Class name (including the package) for the type of argument

<replaced-method name="" replacer="">


<arg-type match="java.lang.String"/>
</replaced-method>

<qualifier>

type="org.springframework.beans.factory.annotation.Qualifier"
value --

<alias/>

name -- name/id of the bean for which the alias is to reffer.


alias -- takes only an single value (name). Wont work with comma seperated
values.

<alias name="person" alias="welch" />

<import/>

Similar to Java importing an package/class where as here it would import an other


configuration xml

resource -- path to the configuration xml.

Types

The tags which can be used inside the <property> / <constructor-arg>

<value/>

<ref/>

bean -- reference to a bean either by id/name/alias


parent -- reference to a bean which is in a parent container of the current container

<idref/>

This tag works similar to ref, but instead of passing the bean it passes the name by
which it is referred. Using this would do a check if the bean eixsts or not, would pass
the value if only exists else raises a Exception

bean -- reference to a bean either by id/name/alias.

<idref bean="types"/>
would equal to

<value>types</value>

<null/>

This tag is used to assign Java null to a respective property/argument

<array/> and <list/>

Both of these tags accept any types, where each off the element would be added in
the same sequence in the xml.

value-type -- attribute help restrict the element being added in to the respective
type. (ex: java.lang.String)

<array>
<value>This</value>
<value>is</value>
<value>a</value>
<value>Sample</value>
<value>Array</value>
</array>

<array>
<value>String</value>
<bean class="java.lang.Object"/>
<idref bean="types"/>
<ref bean="types" parent=""/>
</array>
Just replace array with list for making it an list. Declaring multi-dimensional
array/list is possible with nested declarations of the same tags.

</map>

The map tag only accepts the entry elements


key-type -- attribute help restrict the type of key being added in to the
respective type. (ex: java.lang.String)
value-type -- attribute help restrict the type of value being added.

<entry/> Help determine the method overloaded by the type of arguments


it accepts

o key -- key of the current Entry


o key-ref -- refer to any other bean which would be set as the key
o value -- value of the current Entry
o value-ref -- refer to any other bean which would be set as the value
o value-type -- help's to validate the type of value being added needs to be
an Class with Package (ex:java.lang.String)

<map>
<entry key="Key 1" value="Sample"></entry>
<entry key="Key 2"><value>Sample</value></entry>
<entry key-ref="refKey" value="Custom"></entry>
<entry key="Key 4" key-ref="valueRef" value-type="java.lang.String"></entry>
</map>

<props/>

This refers to the java.util.Properties for which we can create an instance. And
populated using the prop tag.

<prop> -- Each tag represents an individual property which are add to


the props[Properties]. The key is represend using the key attribute where as the
value by the element text
o key -- is the property key, by which its identified

<props>
<prop key="com.example.pool">30</prop>
</props>

Spring Framework
Link: https://gist.github.com/korshny/d5cf1b9a5f2dffafdca9

Ejemplo: Hola en spring

hello.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">

<bean id="greetingService" class="HelloApp">


<property name="greeting" value="!" />
</bean>

<bean id="greetingService" class=" com.example.GreetingServiceImpl">


<constructor-arg value="!" />
</bean>

</beans>
HelloApp.java

import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.FileSystemResource;

public class HelloApp {

public interface GreetingService {


void sayGreeting();
}

public class GreetingServiceImpl implements GreetingService {


private String greeting;

public GreetingServiceImpl(String greeting) {


this.greeting = greeting;
}
public void sayGreeting() {
System.out.println(greeting);
}
public void setGreeting(String greeting) {
this.greeting = greeting;
}
}

public static void main(String[] args) throws Exception {


BeanFactory factory = new XmlBeanFactory(new
FileSystemResource("file:src/hello.xml"));

GreetingService greetingService = (GreetingService)


factory.getBean("greetingService");

greetingService.sayGreeting();
}
}

Spring Framework
Link: https://gist.github.com/dhanuroutu/5307855

Ejemplo: Ejemplo de Spring DBCP

EmployeDAO.java
package com.dhanu;
import java.sql.*;
import org.apache.commons.dbcp.BasicDataSource;
public class EmployeeDAO implements EmployeeDAOI
{
private Connection con;
private Employee employee;
PreparedStatement pstmt;
public EmployeeDAO(BasicDataSource ds,Employee employee)
{
try{
this.con=ds.getConnection();
this.employee=employee;
}
catch(Exception e)
{
System.out.println(e);
}
}
public String saveEmployee()
{
String msg="";
try
{
String qry="insert into employee
values(?,?,?,?,?)";
pstmt=con.prepareStatement(qry);
pstmt.setInt(1,employee.getEmpId());
pstmt.setString(2,employee.getName());
pstmt.setInt(3,employee.getAge());
pstmt.setString(4,employee.getDesign());
pstmt.setDouble(5,employee.getSalary());
pstmt.executeUpdate();
msg="Employee Record inserted successfully";
}
catch (Exception e)
{
msg="Exception::::"+e;
}
finally
{
return msg;
}
}
public String updateSalary(int empNo,double salary)
{
String msg="";
try
{
String qry="update employee set salary=? where
emp_id=?";
pstmt=con.prepareStatement(qry);
pstmt.setDouble(1,salary);
pstmt.setInt(2,empNo);
pstmt.executeUpdate();
msg="Employee Record updated successfully";
}
catch (Exception e)
{
msg="Exception::::"+e;
}
finally
{
return msg;
}
}
}

Employee.java

package com.dhanu;
public class Employee
{
private int empId;
private String name;
private int age;
private String design;
private double salary;

public void setEmpId(int empId)


{
this.empId=empId;
}
public int getEmpId()
{
return empId;
}

public void setName(String name)


{
this.name=name;
}
public String getName()
{
return name;
}

public void setAge(int age)


{
this.age=age;
}
public int getAge()
{
return age;
}

public void setDesign(String design)


{
this.design=design;
}
public String getDesign()
{
return design;
}
public void setSalary(double salary)
{
this.salary=salary;
}
public double getSalary()
{
return salary;
}

EmployeeDAOI.java
package com.dhanu;

public interface EmployeeDAOI


{
public String saveEmployee();
public String updateSalary(int empNo,double salary);
}

mybeans.xml
<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:p="http://www.springframework.org/schema/p"
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-3.0.xsd">

<!-- Definition for textEditor bean -->


<bean id="con" class="org.apache.commons.dbcp.BasicDataSource"
p:username="root"
p:password="root"
p:url="jdbc:mysql://localhost:3306/spring"
p:driverClassName="com.mysql.jdbc.Driver"/>

<!-- Definition for EmployeeDAO bean -->


<bean id="empdao" class="com.dhanu.EmployeeDAO">
<constructor-arg ref="con"/>
<constructor-arg ref="emp"/>
</bean>

<bean id="emp" class="com.dhanu.Employee"


p:empId="107"
p:name="Sekhar Babu Gunji"
p:age="27"
p:design="Technical Lead"
p:salary="30000.0"/>

</beans>
TestCase.java

package com.dhanu;
import org.springframework.beans.factory.*;
import org.springframework.core.io.*;
import org.springframework.beans.factory.xml.XmlBeanFactory;
public class TestCase
{
public static void main(String[] args)
{

Resource res=new ClassPathResource("mybeans.xml");


BeanFactory beans=new XmlBeanFactory(res);
EmployeeDAOI
empdaoi=(EmployeeDAOI)beans.getBean("empdao");
System.out.println(empdaoi.saveEmployee());
System.out.println(empdaoi.updateSalary(107,45000.0));
}
}

Spring Framework
Link: https://gist.github.com/dhanuroutu/5307871
Ejemplo: Uso de Spring Util NameSpace

DisplayBean.java

package com.dhanu;

import java.util.List;

public class DisplayBean {


private List<Employee> employees;
public DisplayBean(List<Employee> employees)
{
this.employees=employees;
}
public void displayEmployees()
{
for(Employee emp:employees)
{

System.out.println(emp.getEmpId()+"\t"+emp.getEmpName()+"\t"+emp.g
etGender()+"\t"+emp.getDept()+"\t"+emp.getSalary());
}
}
}

Employee.java
package com.dhanu;

public class Employee {

private int empId;


private String empName;
private String dept;
private String gender;
private double salary;

public int getEmpId() {


return empId;
}
public void setEmpId(int empId) {
this.empId = empId;
}
public String getEmpName() {
return empName;
}
public void setEmpName(String empName) {
this.empName = empName;
}
public String getDept() {
return dept;
}
public void setDept(String dept) {
this.dept = dept;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}

mybeans.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:util="http://www.springframework.org/schema/util"
xsi:schemaLocation=
"http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-3.0.xsd">

<bean id="db" class="com.dhanu.DisplayBean">


<constructor-arg ref="emps"/>
</bean>

<bean id="emp1" class="com.dhanu.Employee"


p:empId="1"
p:empName="Dhanunjaya Rao"
p:dept="Software"
p:gender="Male"
p:salary="100000.0"
/>
<bean id="emp2" class="com.dhanu.Employee"
p:empId="2"
p:empName="Vidhyasagar"
p:dept="Hardware"
p:gender="Male"
p:salary="25000.0"
/>
<bean id="emp3" class="com.dhanu.Employee"
p:empId="3"
p:empName="Ramakrishna"
p:dept="Electronics Engineer"
p:gender="Male"
p:salary="90000.0"
/>
<util:list id="emps">
<ref bean="emp1"/>
<ref bean="emp2"/>
<ref bean="emp3"/>
</util:list>
</beans>

UnitTest.java

package com.dhanu;

import org.springframework.context.ApplicationContext;
import
org.springframework.context.support.ClassPathXmlApplicationContext;

public class UnitTest {

public static void main(String[] args) {

ApplicationContext beans=new
ClassPathXmlApplicationContext("mybeans.xml");
DisplayBean db=(DisplayBean)beans.getBean("db");
db.displayEmployees();

}
}

Spring Framework
Link: https://gist.github.com/cyy0418/5794516
Ejemplo: Uso de DAO

applicationContext.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:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-
context.xsd">
<aop:aspectj-autoproxy/>
<!--properties-->
<context:property-placeholder location="classpath:jdbc.properties"/>

<bean id="dataSource"
class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName"
value="${jdbc.driverClassName}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
<!--JdbcTemplate
<bean id="jdbcTemplate"
class="org.springframework.jdbc.core.JdbcTemplate">
<constructor-arg name="dataSource" ref="dataSource"/>
</bean>
-->
<!--NamedParameterJdbcTemplate-->
<bean id="jdbcTemplate"
class="org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplat
e">
<constructor-arg name="dataSource" ref="dataSource"/>
</bean>
<context:component-scan base-
package="com.kaishengit"></context:component-scan>
</beans>
jdbc.properties

jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql:///spring
jdbc.username=root
jdbc.password=root

UserDao1.java

@Named
public class UserDao {
@Inject
private JdbcTemplate jdbcTemplate;

public void save(User user) {


String sql = "insert into t_user(username,password)
values(?,?)";
jdbcTemplate.update(sql,
user.getUsername(),user.getPassword());
}
public List<User> findAll() {
String sql = "select id,username,password from
t_user";
return jdbcTemplate.query(sql, new UserRowMapper());
}
public User findById (int id) {
String sql = "select id,username,password from t_user
where id = ?";
return jdbcTemplate.queryForObject(sql , new
UserRowMapper (),id);
}

public int count() {


String sql = "select count(*) from t_user ";
return jdbcTemplate.queryForInt(sql );
}

private class UserRowMapper implements RowMapper<User> {


@Override
public User mapRow(ResultSet rs, int rowIndex) throws
SQLException {
User user = new User();
user.setId(rs.getInt("id"));
user.setPassword(rs.getString("password"));
user.setUsername(rs.getString("username"));
return user;
}
}

UserDao2
@Named
public class UserDao {
@Inject
private NamedParameterJdbcTemplate jdbcTemplate;

public void save(User user) {


String sql = "insert into t_user (username,password)
values(:name,: pwd )";
Map<String, String> map = new HashMap<String, String>();
map.put("name" , user.getUsername ());
map.put("pwd ", user.getPassword ());
jdbcTemplate.update(sql , map);
}
public void save(User user) {
String sql = "insert into t_user (username,password) values(:
username ,:password )";
SqlParameterSource ss = new
BeanPropertySqlParameterSource(user);
jdbcTemplate.update(sql , ss);
}
public List<User> findAll() {
String sql = "select id,username,password from t_user ";
return jdbcTemplate.query (sql , new HashMap<String, String>(),
new
UserRowMapper ());
}
public int count() {
String sql = "select count(*) from t_user ";
return jdbcTemplate.queryForInt(sql,new HashMap<String,String
>());
}

public User findById (int id) {


String sql = "select id,username,password from t_user where
id = :id" ;
SqlParameterSource ss = new MapSqlParameterSource ("id" ,id
);
return jdbcTemplate.queryForObject(sql,ss , new UserRowMapper
());
}
public void save(User user) {
String sql = "insert into t_user (username,password) values(:
username,:password )";
SqlParameterSource ss = new MapSqlParameterSource ()
.addValue ("username", user.getUsername ())
.addValue ("password", user.getPassword ());
jdbcTemplate.update(sql , ss);
}
}

Spring +JPA
Link: https://gist.github.com/Qkyrie/7714379
Ejemplo: Uso de JPA

JPAConfiguration.java

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import
org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.jpa.JpaTransactionManager;
import
org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
import
org.springframework.transaction.annotation.EnableTransactionManagement;
import
org.springframework.transaction.annotation.TransactionManagementConfigure
r;

import javax.sql.DataSource;
import java.util.Properties;

/**
* User: Quinten
* Date: 28-11-13
* Time: 20:48
*
* @author Quinten De Swaef
*/
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(basePackageClasses = Application.class)
class JpaConfiguration implements TransactionManagementConfigurer {

@Value("${dataSource.driverClassName}")
private String driver;
@Value("${dataSource.url}")
private String url;
@Value("${dataSource.username}")
private String username;
@Value("${dataSource.password}")
private String password;
@Value("${hibernate.dialect}")
private String dialect;
@Value("${hibernate.hbm2ddl.auto}")
private String hbm2ddlAuto;

@Bean
public DataSource configureDataSource() {
DriverManagerDataSource dataSource = new
DriverManagerDataSource();
dataSource.setDriverClassName(driver);
dataSource.setUrl(url);
dataSource.setUsername(username);
dataSource.setPassword(password);
return dataSource;
}

@Bean
public LocalContainerEntityManagerFactoryBean
configureEntityManagerFactory() {
LocalContainerEntityManagerFactoryBean entityManagerFactoryBean =
new LocalContainerEntityManagerFactoryBean();
entityManagerFactoryBean.setDataSource(configureDataSource());
entityManagerFactoryBean.setPackagesToScan("${package}");
entityManagerFactoryBean.setJpaVendorAdapter(new
HibernateJpaVendorAdapter());

Properties jpaProperties = new Properties();


jpaProperties.put(org.hibernate.cfg.Environment.DIALECT,
dialect);
jpaProperties.put(org.hibernate.cfg.Environment.HBM2DDL_AUTO,
hbm2ddlAuto);
entityManagerFactoryBean.setJpaProperties(jpaProperties);

return entityManagerFactoryBean;
}

@Bean
public PlatformTransactionManager
annotationDrivenTransactionManager() {
return new JpaTransactionManager();
}
}

Spring boot + Gradle

Link: https://gist.github.com/congjf/4453467a817a754ffbe6d73085a6141f
Ejemplo: Gradle + Spring boot

build.gradle

buildscript {
repositories {
mavenLocal()
mavenCentral()

maven { url 'http://maven.aliyun.com/nexus/content/groups/public'


}
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-
plugin:1.4.1.RELEASE")
}
}

// BASE
apply plugin: 'java'
// apply plugin: 'war'
apply plugin: 'spring-boot'

// IDE
apply plugin: 'eclipse'
apply plugin: 'idea'

jar {
baseName = 'gs-spring-boot'
version = '0.1.0'
}

repositories {
mavenCentral()
}

sourceCompatibility = 1.8
targetCompatibility = 1.8

dependencies {
// tag::jetty[]
compile("org.springframework.boot:spring-boot-starter-web") {
exclude module: "spring-boot-starter-tomcat"
}
compile("org.springframework.boot:spring-boot-starter-jetty")
// end::jetty[]
// tag::actuator[]
compile("org.springframework.boot:spring-boot-starter-actuator")
// end::actuator[]
testCompile("junit:junit")
}

// war {
// from 'src/rootContent' // adds a file-set to the root of the
archive
// webInf { from 'src/additionalWebInf' } // adds a file-set to the
WEB-INF dir.
// classpath fileTree('additionalLibs') // adds a file-set to the
WEB-INF/lib dir.
// classpath configurations.moreLibs // adds a configuration to the
WEB-INF/lib dir.
// webXml = file('src/someWeb.xml') // copies a file to WEB-
INF/web.xml
// }

src\main\java\hello\Application.java

package hello;

/**
* Created by CongJF on 2016/10/6.
*/

import java.util.Arrays;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;

@SpringBootApplication
public class Application {

public static void main(String[] args) {


ApplicationContext ctx = SpringApplication.run(Application.class,
args);

System.out.println("Let's inspect the beans provided by Spring


Boot:");

String[] beanNames = ctx.getBeanDefinitionNames();


Arrays.sort(beanNames);
for (String beanName : beanNames) {
System.out.println(beanName);
}
}

src\main\java\hello\HelloController.java

package hello;

/**
* Created by CongJF on 2016/10/6.
*/

import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestMapping;

@RestController
public class HelloController {

@RequestMapping("/")
public String index() {
return "Greetings from Spring Boot!";
}

@RequestMapping("/user")
public String user() {
return "User Page!";
}

Documentacin del ejemplo:


Steps
Create a build.gradle file, like build.gradle
Open IDEA, and import the build.gradle created before

Gradle
The Spring Boot gradle plugin provides many convenient features:

It collects all the jars on the classpath and builds a single, runnable "ber-jar",
which makes it more convenient to execute and transport your service.
It searches for the public static void main() method to flag as a runnable class.
It provides a built-in dependency resolver that sets the version number to match
Spring Boot dependencies. You can override any version you wish, but it will default
to Boots chosen set of versions.

Annotation
@RestController meaning its ready for use by Spring MVC to handle web
requests. Combines @Controller and @ResponseBody, two annotations that
results in web requests returning data rather than a view.
@RequestMapping maps URL Path to method.
@SpringBootApplication is a convenience annotation that adds all of the
following:
o @Configuration tags the class as a source of bean definitions for the
application context.
o @EnableAutoConfiguration tells Spring Boot to start adding beans based on
classpath settings, other beans, and various property settings.
o Normally you would add @EnableWebMvc for a Spring MVC app, but
Spring Boot adds it automatically when it sees spring-webmvc on the
classpath. This flags the application as a web application and activates key
behaviors such as setting up a DispatcherServlet.
o @ComponentScan tells Spring to look for other components, configurations,
and services in the the hello package, allowing it to find
the HelloController.
By default Spring Boot will serve static content from a directory called /static
(or /public or /resources or /META-INF/resources) in the classpath or from
the root of the ServletContext. It uses the ResourceHttpRequestHandler from
Spring MVC so you can modify that behavior by adding your
own WebMvcConfigurerAdapter and overriding
the addResourceHandlers method.
Spring BootclasspathServletContext
/static /public/resources/META-INF/resources

Spring BootSpring MVCResourceHttpRequestHandler


WebMvcConfigurerAdapteraddResourceHandlers

In a stand-alone web application the default servlet from the container is
also enabled, and acts as a fallback, serving content from the root of the
ServletContext if Spring decides not to handle it. Most of the time this will
not happen (unless you modify the default MVC configuration) because
Spring will always be able to handle requests through the DispatcherServlet.

You can customize the static resource locations using


spring.resources.staticLocations (replacing the default values with a list of
directory locations). If you do this the default welcome page detection will
switch to your custom locations, so if there is an index.html in any of your
locations on startup, it will be the home page of the application.

In addition to the standard static resource locations above, a special case is


made for Webjars content. Any resources with a path in /webjars/** will be
served from jar files if they are packaged in the Webjars format.

Do not use the src/main/webapp directory if your application will be


packaged as a jar. Although this directory is a common standard, it will only
work with war packaging and it will be silently ignored by most build tools if
you generate a jar. jar
src/main/webapp directorywar

jar
Spring Boot also supports advanced resource handling features provided by
Spring MVC, allowing use cases such as cache busting static resources or
using version agnostic URLs for Webjars.

To use version agnostic URLs for Webjars, simply add the webjars-locator
dependency. Then declare your Webjar, taking jQuery for example, as
"/webjars/jquery/dist/jquery.min.js" which results in
"/webjars/jquery/x.y.z/dist/jquery.min.js" where x.y.z is the Webjar version.
If you are using JBoss, youll need to declare the webjars-locator-jboss-vfs
dependency instead of the webjars-locator; otherwise all Webjars resolve as
a 404.
To use cache bursting, the following configuration will configure a cache
busting solution for all static resources, effectively adding a content hash in
URLs, such as <link href="/css/spring-
2a2d595e6ed9a0b24f027f2b63b134d6.css"/>:
spring.resources.chain.strategy.content.enabled=true
spring.resources.chain.strategy.content.paths=/**
Links to resources are rewritten at runtime in template, thanks to a
ResourceUrlEncodingFilter, auto-configured for Thymeleaf, Velocity and
FreeMarker. You should manually declare this filter when using JSPs. Other
template engines arent automatically supported right now, but can be with
custom template macros/helpers and the use of the ResourceUrlProvider.
When loading resources dynamically with, for example, a JavaScript module
loader, renaming files is not an option. Thats why other strategies are also
supported and can be combined. A "fixed" strategy will add a static version
string in the URL, without changing the file name:

spring.resources.chain.strategy.content.enabled=true
spring.resources.chain.strategy.content.paths=/**
spring.resources.chain.strategy.fixed.enabled=true
spring.resources.chain.strategy.fixed.paths=/js/lib/
spring.resources.chain.strategy.fixed.version=v12
With this configuration, JavaScript modules located under "/js/lib/" will use a
fixed versioning strategy "/v12/js/lib/mymodule.js" while other resources will
still use the content one .

See ResourceProperties for more of the supported options.

This feature has been thoroughly described in a dedicated blog post and in
Spring Frameworks reference documentation.

Spring

Link: https://gist.github.com/dhanuroutu/5307855
Ejemplo: DAO

EmployeDAO.java
package com.dhanu;
import java.sql.*;
import org.apache.commons.dbcp.BasicDataSource;
public class EmployeeDAO implements EmployeeDAOI
{
private Connection con;
private Employee employee;
PreparedStatement pstmt;
public EmployeeDAO(BasicDataSource ds,Employee employee)
{
try{
this.con=ds.getConnection();
this.employee=employee;
}
catch(Exception e)
{
System.out.println(e);
}
}
public String saveEmployee()
{
String msg="";
try
{
String qry="insert into employee
values(?,?,?,?,?)";
pstmt=con.prepareStatement(qry);
pstmt.setInt(1,employee.getEmpId());
pstmt.setString(2,employee.getName());
pstmt.setInt(3,employee.getAge());
pstmt.setString(4,employee.getDesign());
pstmt.setDouble(5,employee.getSalary());
pstmt.executeUpdate();
msg="Employee Record inserted successfully";
}
catch (Exception e)
{
msg="Exception::::"+e;
}
finally
{
return msg;
}
}
public String updateSalary(int empNo,double salary)
{
String msg="";
try
{
String qry="update employee set salary=? where
emp_id=?";
pstmt=con.prepareStatement(qry);
pstmt.setDouble(1,salary);
pstmt.setInt(2,empNo);
pstmt.executeUpdate();
msg="Employee Record updated successfully";
}
catch (Exception e)
{
msg="Exception::::"+e;
}
finally
{
return msg;
}
}
}

Employee.java
package com.dhanu;
public class Employee
{
private int empId;
private String name;
private int age;
private String design;
private double salary;

public void setEmpId(int empId)


{
this.empId=empId;
}
public int getEmpId()
{
return empId;
}

public void setName(String name)


{
this.name=name;
}
public String getName()
{
return name;
}

public void setAge(int age)


{
this.age=age;
}
public int getAge()
{
return age;
}

public void setDesign(String design)


{
this.design=design;
}
public String getDesign()
{
return design;
}

public void setSalary(double salary)


{
this.salary=salary;
}
public double getSalary()
{
return salary;
}

EmployeeDAOI.java

package com.dhanu;

public interface EmployeeDAOI


{
public String saveEmployee();
public String updateSalary(int empNo,double salary);
}

mybeans.xml

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:p="http://www.springframework.org/schema/p"
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-3.0.xsd">

<!-- Definition for textEditor bean -->


<bean id="con" class="org.apache.commons.dbcp.BasicDataSource"
p:username="root"
p:password="root"
p:url="jdbc:mysql://localhost:3306/spring"
p:driverClassName="com.mysql.jdbc.Driver"/>

<!-- Definition for EmployeeDAO bean -->


<bean id="empdao" class="com.dhanu.EmployeeDAO">
<constructor-arg ref="con"/>
<constructor-arg ref="emp"/>
</bean>

<bean id="emp" class="com.dhanu.Employee"


p:empId="107"
p:name="Sekhar Babu Gunji"
p:age="27"
p:design="Technical Lead"
p:salary="30000.0"/>
</beans>

TestCase.java
package com.dhanu;
import org.springframework.beans.factory.*;
import org.springframework.core.io.*;
import org.springframework.beans.factory.xml.XmlBeanFactory;
public class TestCase
{
public static void main(String[] args)
{

Resource res=new ClassPathResource("mybeans.xml");


BeanFactory beans=new XmlBeanFactory(res);
EmployeeDAOI
empdaoi=(EmployeeDAOI)beans.getBean("empdao");
System.out.println(empdaoi.saveEmployee());
System.out.println(empdaoi.updateSalary(107,45000.0));
}
}

Spring boot
Link: https://github.com/tux2323/simpleweb-springboot

Ejemplo: Spring web

build.gradle
buildscript {
ext {
springBootVersion = '1.3.2.RELEASE'
}
repositories {
mavenCentral()
maven { url "http://repo.spring.io/release" }
maven { url "http://repo.spring.io/milestone" }
maven { url "http://repo.spring.io/snapshot" }
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-
plugin:${springBootVersion}")
classpath('se.transmode.gradle:gradle-docker:1.2')
}
}

apply plugin: 'java'


apply plugin: 'eclipse'
apply plugin: 'idea'
apply plugin: 'spring-boot'
apply plugin: 'docker'

repositories {
mavenCentral()
maven { url "http://repo.spring.io/release" }
maven { url "http://repo.spring.io/milestone" }
maven { url "http://repo.spring.io/snapshot" }
}

group = 'tux2323'

jar {
baseName = 'simpleweb-springboot'
version = '0.1.0'
}

dependencies {
compile("javax.inject:javax.inject:1")
compile("org.springframework.boot:spring-boot-starter-actuator")
compile("org.springframework.boot:spring-boot-starter-web")
compile("org.springframework.boot:spring-boot-starter-security")
compile("org.springframework.boot:spring-boot-starter-thymeleaf")
compile("org.springframework.boot:spring-boot-starter-data-jpa")
compile("org.springframework.boot:spring-boot-starter-logging")
// Spring Boot DevTools for hot reload
compile("org.springframework.boot:spring-boot-devtools")

compile("org.hibernate:hibernate-validator")
compile("org.hsqldb:hsqldb")
compile("commons-lang:commons-lang:2.6")
compile("commons-io:commons-io:2.4")

compile("org.webjars:bootstrap:3.1.0")
compile("org.webjars:jquery:2.1.0-2")
}

task wrapper(type: Wrapper) {


gradleVersion = '2.3'
}

task buildDocker(type: Docker, dependsOn: build) {


push = true
applicationName = jar.baseName
dockerfile = file('src/main/docker/Dockerfile')
doFirst {
copy {
from jar
into stageDir
}
}
}

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>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.3.2.RELEASE</version>
</parent>

<groupId>com.seitenbau.samples</groupId>
<artifactId>simpleweb-springboot</artifactId>
<version>0.1.0</version>

<properties>
<docker.image.prefix>tux2323</docker.image.prefix>
</properties>

<dependencies>
<dependency>
<groupId>javax.inject</groupId>
<artifactId>javax.inject</artifactId>
<version>1</version>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-
actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-
security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-
thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-
jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-
logging</artifactId>
</dependency>
<!-- Spring Boot DevTools for hot reload -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
</dependency>

<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
</dependency>
<dependency>
<groupId>org.hsqldb</groupId>
<artifactId>hsqldb</artifactId>
</dependency>

<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>2.6</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>

<dependency>
<groupId>org.webjars</groupId>
<artifactId>bootstrap</artifactId>
<version>3.1.0</version>
</dependency>
<dependency>
<groupId>org.webjars</groupId>
<artifactId>jquery</artifactId>
<version>2.1.0-2</version>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>

<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-
plugin</artifactId>
</plugin>

<plugin>
<groupId>com.spotify</groupId>
<artifactId>docker-maven-
plugin</artifactId>
<version>0.4.0</version>
<configuration>
<imageName>${docker.image.prefix}/${project.artifactId}</imageName
>

<dockerDirectory>src/main/docker</dockerDirectory>
<resources>
<resource>

<targetPath>/</targetPath>

<directory>${project.build.directory}</directory>

<include>${project.build.finalName}.jar</include>
</resource>
</resources>
</configuration>
</plugin>
</plugins>
</build>

</project>

Estructura de un proyecto Spring con Gradle

Proyecto/build.gradle

Proyecto/src/main/java
Proyecto/src/main/java/com/codemonkey/Application.java
Proyecto/src/main/java/com/codemonkey/controller/ControllerApplication.java

Proyecto/src/main/resources
Proyecto/src/main/resources/static
Proyecto/src/main/resources/templates
Proyecto/src/main/resources/templates/error
Proyecto/src/main/resources/application.properties
Proyecto/src/main/resources/banner.txt

Construir:
$ gradle build

Listar tareas:
$ gradle q task

Ejecutar:
$ gradle bootRun
IoC: Inversin de control
Ejemplo
Ejemplo.

public class Jugador{


private IEquipo equipo;

public Jugador(){}

public Jugador(IEquipo equipo){


super();
this.equipo=equipo;
}

public void mostrarEquipo(){


equipo.mostrar();
}
}
public interface IEquipo{
public abstract void mostrar();
}

public class Madrid implements IEquipo {


@Override
public void mostrar(){
System.out.println("Real Madrid FC");
}
}

Spring Framework
Link: http://www.logicbig.com/tutorials/spring-framework/spring-web-mvc/thymeleaf-
views/

Maven dependency
pom.xml
<dependency>

<groupId>org.thymeleaf</groupId>

<artifactId>thymeleaf</artifactId>

<version>3.0.7.RELEASE</version>

</dependency>

<dependency>
<groupId>org.thymeleaf</groupId>

<artifactId>thymeleaf-spring4</artifactId>

<version>3.0.7.RELEASE</version>

</dependency>

The first artifact (thymeleaf) is Thymeleaf framework and the second


one (thymeleaf-spring4) contains Spring integration components.

Thymeleaf configuration
@EnableWebMvc

@Configuration

@ComponentScan

public class MyWebConfig {

@Autowired

ApplicationContext applicationContext;

@Bean
public SpringTemplateEngine templateEngine(){

SpringTemplateEngine templateEngine = new SpringTemplateEngine();

templateEngine.setTemplateResolver(templateResolver());

return templateEngine;

@Bean

public SpringResourceTemplateResolver templateResolver(){

SpringResourceTemplateResolver templateResolver = new

SpringResourceTemplateResolver();

templateResolver.setApplicationContext(this.applicationContext);

templateResolver.setPrefix("/WEB-INF/views/");

templateResolver.setSuffix(".html");

return templateResolver;

@Bean

public ViewResolver viewResolver(){


ThymeleafViewResolver viewResolver = new ThymeleafViewResolver();

viewResolver.setTemplateEngine(templateEngine());

return viewResolver;

}
All above components are provided by Thymeleaf framework for Spring
integration. Following is a quick getting-to-know description of them:

SpringTemplateEngine

This class hooks up an instance of SpringStandardDialect (a subclass of


org.thymeleaf.standard.StandardDialect). Thymeleaf dialects define a
set of template processors.

SpringResourceTemplateResolver

It resolves templates using Spring's resource resolution mechanism (see


ApplicationContext.getResource(String)).

ThymeleafViewResolver

It is an implementation of
org.springframework.web.servlet.ViewResolver. The View
implementation managed by this ViewResolver is ThymeleafView which
is responsible to carry out template processing.

Writing a Spring Controller


@Controller

@RequestMapping("/")

public class MyController {

@RequestMapping

public String handleRequest (Model model) {

model.addAttribute("msg", "A message from the controller");

model.addAttribute("time", LocalTime.now());

return "my-page";

The Thymeleaf template


src/main/webapp/WEB-INF/views/my-page.html
<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml"

xmlns:th="http://www.thymeleaf.org">

<body>

<h2>A Thymeleaf view</h2>

<div th:text="${msg}"/>

<div th:text="${time}"/>

</body>

</html>

As seen above the Model attributes are applied as Thymeleaf specific


attributes (details here).

Output

The generated html:

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">

<body>

<h2>A Thymeleaf view</h2>


<div>A message from the controller</div>

<div>21:43:35.050</div>

</body>

</html>

Spring Boot + Spring Security +


Thymeleaf example
http://www.mkyong.com/spring-boot/spring-boot-spring-security-thymeleaf-example/

1. Project Directory
2. Project Dependencies
Declares spring-boot-starter-security, it will get anything you need to develop
a Spring Boot + Spring Securityweb application.
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>

<artifactId>spring-boot-web-spring-security</artifactId>

<packaging>jar</packaging>

<name>Spring Boot Web Spring Security</name>

<description>Spring Boot Web Spring Security Example</description>

<url>https://www.mkyong.com</url>

<version>1.0</version>

<parent>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-parent</artifactId>

<version>1.5.3.RELEASE</version>

</parent>

<properties>

<java.version>1.8</java.version>

</properties>
<dependencies>

<!-- Spring Security -->

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-security</artifactId>

</dependency>

<!-- do you like thymeleaf? -->

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-thymeleaf</artifactId>

</dependency>

<!-- optional, it brings userful tags to display spring


security stuff -->

<dependency>

<groupId>org.thymeleaf.extras</groupId>

<artifactId>thymeleaf-extras-springsecurity4</artifactId>

</dependency>

<!-- hot swapping, disable cache for template, enable live reload -->

<dependency>

<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>

<optional>true</optional>

</dependency>

<!-- Optional, for bootstrap -->

<dependency>

<groupId>org.webjars</groupId>

<artifactId>bootstrap</artifactId>

<version>3.3.7</version>

</dependency>

</dependencies>

<build>

<plugins>

<!-- Package as an executable jar/war -->

<plugin>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-maven-plugin</artifactId>

</plugin>

</plugins>

</build>

</project>

Display project dependencies :


$ mvn dependency:tree

3. Spring Security
3.1 Extends WebSecurityConfigurerAdapter, and defined the security rules in
the configure method.
For user admin :

1. Able to access /admin page


2. Unable to access /user page, redirect to 403 access denied page.

For user user :

1. able to access /user page


2. unable to access /admin page, redirect to 403 access denied page.

SpringSecurityConfig.java

package com.mkyong.config;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.context.annotation.Configuration;

import
org.springframework.security.config.annotation.authentication.builders.Authentic
ationManagerBuilder;

import org.springframework.security.config.annotation.web.builders.HttpSecurity;

import
org.springframework.security.config.annotation.web.configuration.WebSecurityConf
igurerAdapter;

import org.springframework.security.web.access.AccessDeniedHandler;

@Configuration

public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {


@Autowired

private AccessDeniedHandler accessDeniedHandler;

// roles admin allow to access /admin/**

// roles user allow to access /user/**

// custom 403 access denied handler

@Override

protected void configure(HttpSecurity http) throws Exception {

http.csrf().disable()

.authorizeRequests()

.antMatchers("/", "/home",
"/about").permitAll()

.antMatchers("/admin/**").hasAnyRole("ADMIN")

.antMatchers("/user/**").hasAnyRole("USER")

.anyRequest().authenticated()

.and()

.formLogin()

.loginPage("/login")

.permitAll()

.and()

.logout()

.permitAll()

.and()
.exceptionHandling().accessDeniedHandler(accessDeniedHandler);

// create two users, admin and user

@Autowired

public void configureGlobal(AuthenticationManagerBuilder auth) throws


Exception {

auth.inMemoryAuthentication()

.withUser("user").password("password").roles("USER")

.and()

.withUser("admin").password("password").roles("ADMIN");

3.2 Custom 403 Access denied handler, logs the request and redirect to /403
WelcomeController.java

package com.mkyong.error;

import org.slf4j.Logger;

import org.slf4j.LoggerFactory;

import org.springframework.security.access.AccessDeniedException;

import org.springframework.security.core.Authentication;

import org.springframework.security.core.context.SecurityContextHolder;

import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import java.io.IOException;

// handle 403 page

@Component

public class MyAccessDeniedHandler implements AccessDeniedHandler {

private static Logger logger =


LoggerFactory.getLogger(MyAccessDeniedHandler.class);

@Override

public void handle(HttpServletRequest httpServletRequest,

HttpServletResponse httpServletResponse,

AccessDeniedException e) throws IOException,


ServletException {

Authentication auth

= SecurityContextHolder.getContext().getAuthentication();

if (auth != null) {

logger.info("User '" + auth.getName()


+ "' attempted to access the protected URL: "

+ httpServletRequest.getRequestURI());

httpServletResponse.sendRedirect(httpServletRequest.getContextPath() +
"/403");

4. Spring Boot
4.1 A controller class, to define the http request and view name.
DefaultController.java

package com.mkyong.controller;

import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.GetMapping;

@Controller

public class DefaultController {

@GetMapping("/")

public String home1() {

return "/home";

}
@GetMapping("/home")

public String home() {

return "/home";

@GetMapping("/admin")

public String admin() {

return "/admin";

@GetMapping("/user")

public String user() {

return "/user";

@GetMapping("/about")

public String about() {

return "/about";

@GetMapping("/login")

public String login() {

return "/login";
}

@GetMapping("/403")

public String error403() {

return "/error/403";

4.2 Start Spring Boot application.


DefaultController.java

package com.mkyong;

import org.springframework.boot.SpringApplication;

import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication

public class SpringBootWebApplication {

public static void main(String[] args) throws Exception {

SpringApplication.run(SpringBootWebApplication.class, args);

}
5. Thymeleaf + Resources + Static files
5.1 For Thymeleaf files, put in src/main/resources/templates/ folder.
5.2 Thymeleaf fragments, for template layout header.
src/main/resources/templates/fragments/header.html

<html xmlns:th="http://www.thymeleaf.org">

<head>

<div th:fragment="header-css">

<!-- this is header-css -->

<link rel="stylesheet" type="text/css"

href="webjars/bootstrap/3.3.7/css/bootstrap.min.css" />

<link rel="stylesheet" th:href="@{/css/main.css}"

href="../../css/main.css" />

</div>

</head>

<body>

<div th:fragment="header">

<!-- this is header -->

<nav class="navbar navbar-inverse">

<div class="container">

<div class="navbar-header">

<a class="navbar-brand" th:href="@{/}">Spring Boot</a>

</div>

<div id="navbar" class="collapse navbar-collapse">

<ul class="nav navbar-nav">


<li class="active"><a th:href="@{/}">Home</a></li>

</ul>

</div>

</div>

</nav>

</div>

</body>

</html>

5.3 Thymeleaf fragments, for template layout footer. Review the sec tag, it is a
useful tag to display the Spring Security stuff, refer to this Thymeleaf extra Spring
Security for detail.
src/main/resources/templates/fragments/footer.html

<html xmlns="http://www.w3.org/1999/xhtml"

xmlns:th="http://www.thymeleaf.org"

xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4">

<head>

</head>

<body>

<div th:fragment="footer">

<div class="container">

<footer>

<!-- this is footer -->


2017 mkyong.com

<span sec:authorize="isAuthenticated()">

| Logged user: <span sec:authentication="name"></span> |

Roles: <span sec:authentication="principal.authorities"></span>


|

<a th:href="@{/logout}">Sign Out</a>

</span>

<script type="text/javascript"

src="webjars/bootstrap/3.3.7/js/bootstrap.min.js"></script>

</footer>

</div>

</div>

</body>

</html>

5.4 List of the Thymeleaf files, nothing special, self-explanatory.


home ~
src/main/resources/templates/home.html

<!DOCTYPE HTML>

<html xmlns:th="http://www.thymeleaf.org">

<head>

<title>Spring Boot Thymeleaf + Spring Security</title>


<div th:replace="fragments/header :: header-css"/>

</head>

<body>

<div th:replace="fragments/header :: header"/>

<div class="container">

<div class="starter-template">

<h1>Spring Boot Web Thymeleaf + Spring Security</h1>

<h2>1. Visit <a th:href="@{/admin}">Admin page (Spring Security


protected, Need Admin Role)</a></h2>

<h2>2. Visit <a th:href="@{/user}">User page (Spring Security protected,


Need User Role)</a></h2>

<h2>3. Visit <a th:href="@{/about}">Normal page</a></h2>

</div>

</div>

<!-- /.container -->

<div th:replace="fragments/footer :: footer"/>

</body>
</html>

admin ~
src/main/resources/templates/admin.html

<!DOCTYPE HTML>

<html xmlns:th="http://www.thymeleaf.org">

<head>

<div th:replace="fragments/header :: header-css"/>

</head>

<body>

<div th:replace="fragments/header :: header"/>

<div class="container">

<div class="starter-template">

<h1>Admin page (Spring Security protected)</h1>

<h1 th:inline="text">Hello [[${#httpServletRequest.remoteUser}]]!</h1>

<form th:action="@{/logout}" method="post">

<input type="submit" value="Sign Out"/>

</form>

</div>
</div>

<!-- /.container -->

<div th:replace="fragments/footer :: footer"/>

</body>

</html>

user ~
src/main/resources/templates/user.html

<!DOCTYPE HTML>

<html xmlns:th="http://www.thymeleaf.org">

<head>

<div th:replace="fragments/header :: header-css"/>

</head>

<body>

<div th:replace="fragments/header :: header"/>

<div class="container">

<div class="starter-template">

<h1>User page (Spring Security protected)</h1>

<h1 th:inline="text">Hello [[${#httpServletRequest.remoteUser}]]!</h1>


<form th:action="@{/logout}" method="post">

<input type="submit" value="Sign Out"/>

</form>

</div>

</div>

<!-- /.container -->

<div th:replace="fragments/footer :: footer"/>

</body>

</html>

about ~
src/main/resources/templates/about.html

<!DOCTYPE HTML>

<html xmlns:th="http://www.thymeleaf.org">

<head>

<div th:replace="fragments/header :: header-css"/>

</head>

<body>

<div th:replace="fragments/header :: header"/>

<div class="container">
<div class="starter-template">

<h1>Normal page (No need login)</h1>

</div>

</div>

<!-- /.container -->

<div th:replace="fragments/footer :: footer"/>

</body>

</html>

login ~
src/main/resources/templates/login.html

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"

>

<head>

<title>Spring Security Example </title>

<div th:replace="fragments/header :: header-css"/>

</head>

<body>

<div th:replace="fragments/header :: header"/>


<div class="container">

<div class="row" style="margin-top:20px">

<div class="col-xs-12 col-sm-8 col-md-6 col-sm-offset-2 col-md-offset-


3">

<form th:action="@{/login}" method="post">

<fieldset>

<h1>Please Sign In</h1>

<div th:if="${param.error}">

<div class="alert alert-danger">

Invalid username and password.

</div>

</div>

<div th:if="${param.logout}">

<div class="alert alert-info">

You have been logged out.

</div>

</div>

<div class="form-group">

<input type="text" name="username" id="username"


class="form-control input-lg"

placeholder="UserName" required="true"
autofocus="true"/>
</div>

<div class="form-group">

<input type="password" name="password" id="password"


class="form-control input-lg"

placeholder="Password" required="true"/>

</div>

<div class="row">

<div class="col-xs-6 col-sm-6 col-md-6">

<input type="submit" class="btn btn-lg btn-primary


btn-block" value="Sign In"/>

</div>

<div class="col-xs-6 col-sm-6 col-md-6">

</div>

</div>

</fieldset>

</form>

</div>

</div>

</div>

<div th:replace="fragments/footer :: footer"/>

</body>
</html>

403 ~
src/main/resources/templates/error/403.html

<!DOCTYPE HTML>

<html xmlns:th="http://www.thymeleaf.org">

<head>

<div th:replace="fragments/header :: header-css"/>

</head>

<body>

<div th:replace="fragments/header :: header"/>

<div class="container">

<div class="starter-template">

<h1>403 - Access is denied</h1>

<div th:inline="text">Hello '[[${#httpServletRequest.remoteUser}]]',

you do not have permission to access this page.</div>

</div>

</div>

<!-- /.container -->

<div th:replace="fragments/footer :: footer"/>


</body>

</html>

5.5 For static files like CSS or Javascript, put in /src/main/resources/static/


/src/main/resources/static/css/main.css

h1{

color:#0000FF;

h2{

color:#FF0000;

footer{

margin-top:60px;

Note
Read this Spring Boot Serving static content to understand the resource mapping.

6. Demo
6.1 Start the Spring Boot web app. This /admin/** is protected, you need login as
admin to access it.
Terminal

$ mvn spring-boot:run
//...

6.2 Access http://localhost:8080

6.3 Access http://localhost:8080/admin, redirect


to http://localhost:8080/login
6.4 Invalid username or password http://localhost:8080/login
6.5 Login successful, redirect back to admin page http://localhost:8080/admin ,
review the footer section, the user info is displayed.
6.6 Access http://localhost:8080/user, redirect to http://localhost:8080/403
6.7 Clicks on the sign out link in the footer, redirect
to http://localhost:8080/login?logout
http://www.mkyong.com/spring-boot/spring-boot-spring-security-thymeleaf-example/

https://medium.com/@gustavo.ponce.ch/spring-boot-spring-mvc-spring-security-mysql-
a5d8545d837d
https://medium.com/search?q=Spring%20mvc

Recuperar clave Linux


Al entrar al grub
$whoami
$mount rw remount /
passwd nombre_usuario
Despus la clave
$sudo passwd q passwd nombre_usuario

Otra forma:
$rw init=/bin/bash
$ passwd nombre_usuario

WMIC
Link: https://stackoverflow.com/questions/18620173/how-can-i-set-change-dns-using-
the-command-prompt-at-windows-8

Here is another way to change DNS by using WMIC (Windows Management


Instrumentation Command-line).

The commands must be run as administrator to apply.

Clear DNS servers:

wmic nicconfig where (IPEnabled=TRUE) call SetDNSServerSearchOrder ()


Set 1 DNS server:
wmic nicconfig where (IPEnabled=TRUE) call SetDNSServerSearchOrder ("8.8.8.8")
Set 2 DNS servers:

wmic nicconfig where (IPEnabled=TRUE) call SetDNSServerSearchOrder ("8.8.8.8",


"8.8.4.4")
Set 2 DNS servers on a particular network adapter:

wmic nicconfig where "(IPEnabled=TRUE) and (Description = 'Local Area


Connection')" call SetDNSServerSearchOrder ("8.8.8.8", "8.8.4.4")
Another example for setting the domain search list:

wmic nicconfig call SetDNSSuffixSearchOrder ("domain.tld")

Colocar DNS usando CMD

Link:
https://stackoverflow.com/questions/18620173/how-can-i-set-change-dns-using-the-
command-prompt-at-windows-8

netsh interface ipv4 add dns "Local Area Connection" address=192.168.x.x index=1
netsh interface ipv4 add dns "Local Area Connection" address=192.168.x.x index=2

También podría gustarte