Documentos de Académico
Documentos de Profesional
Documentos de Cultura
Link: https://gist.github.com/risha9177719594/9961142
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;
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;
return principle*months*intrestRate/100;
}
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
<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">
(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>
<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 >();
tbs = commonService.getSearch();
tForm.setTbs (tbs);
model.addAttribute(tForm);
return "testSearch";
}
link.html
TestDAOImpl.java
@Repository
public class TestDAOImpl implements TestDAO{
@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.
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.
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
<property>
NOTE: If the property name / setter is not found Springs would throw an exception.
<constructor-arg>
<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.
<replaced-method>
o match -- Class name (including the package) for the type of argument
<qualifier>
type="org.springframework.beans.factory.annotation.Qualifier"
value --
<alias/>
<import/>
Types
<value/>
<ref/>
<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
<idref bean="types"/>
would equal to
<value>types</value>
<null/>
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>
<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.
<props>
<prop key="com.example.pool">30</prop>
</props>
Spring Framework
Link: https://gist.github.com/korshny/d5cf1b9a5f2dffafdca9
hello.xml
</beans>
HelloApp.java
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.FileSystemResource;
greetingService.sayGreeting();
}
}
Spring Framework
Link: https://gist.github.com/dhanuroutu/5307855
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;
EmployeeDAOI.java
package com.dhanu;
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">
</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)
{
Spring Framework
Link: https://gist.github.com/dhanuroutu/5307871
Ejemplo: Uso de Spring Util NameSpace
DisplayBean.java
package com.dhanu;
import java.util.List;
System.out.println(emp.getEmpId()+"\t"+emp.getEmpName()+"\t"+emp.g
etGender()+"\t"+emp.getDept()+"\t"+emp.getSalary());
}
}
}
Employee.java
package com.dhanu;
mybeans.xml
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">
UnitTest.java
package com.dhanu;
import org.springframework.context.ApplicationContext;
import
org.springframework.context.support.ClassPathXmlApplicationContext;
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;
UserDao2
@Named
public class UserDao {
@Inject
private NamedParameterJdbcTemplate jdbcTemplate;
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());
return entityManagerFactoryBean;
}
@Bean
public PlatformTransactionManager
annotationDrivenTransactionManager() {
return new JpaTransactionManager();
}
}
Link: https://gist.github.com/congjf/4453467a817a754ffbe6d73085a6141f
Ejemplo: Gradle + Spring boot
build.gradle
buildscript {
repositories {
mavenLocal()
mavenCentral()
// 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 {
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!";
}
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
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 .
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;
EmployeeDAOI.java
package com.dhanu;
mybeans.xml
<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">
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)
{
Spring boot
Link: https://github.com/tux2323/simpleweb-springboot
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')
}
}
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")
}
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>
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 Jugador(){}
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>
Thymeleaf configuration
@EnableWebMvc
@Configuration
@ComponentScan
@Autowired
ApplicationContext applicationContext;
@Bean
public SpringTemplateEngine templateEngine(){
templateEngine.setTemplateResolver(templateResolver());
return templateEngine;
@Bean
SpringResourceTemplateResolver();
templateResolver.setApplicationContext(this.applicationContext);
templateResolver.setPrefix("/WEB-INF/views/");
templateResolver.setSuffix(".html");
return templateResolver;
@Bean
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
SpringResourceTemplateResolver
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.
@RequestMapping("/")
@RequestMapping
model.addAttribute("time", LocalTime.now());
return "my-page";
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org">
<body>
<div th:text="${msg}"/>
<div th:text="${time}"/>
</body>
</html>
Output
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<body>
<div>21:43:35.050</div>
</body>
</html>
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>
<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>
<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.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>
<dependency>
<groupId>org.webjars</groupId>
<artifactId>bootstrap</artifactId>
<version>3.3.7</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
3. Spring Security
3.1 Extends WebSecurityConfigurerAdapter, and defined the security rules in
the configure method.
For user admin :
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
@Override
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);
@Autowired
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;
@Component
@Override
HttpServletResponse httpServletResponse,
Authentication auth
= SecurityContextHolder.getContext().getAuthentication();
if (auth != null) {
+ 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
@GetMapping("/")
return "/home";
}
@GetMapping("/home")
return "/home";
@GetMapping("/admin")
return "/admin";
@GetMapping("/user")
return "/user";
@GetMapping("/about")
return "/about";
@GetMapping("/login")
return "/login";
}
@GetMapping("/403")
return "/error/403";
package com.mkyong;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
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">
href="webjars/bootstrap/3.3.7/css/bootstrap.min.css" />
href="../../css/main.css" />
</div>
</head>
<body>
<div th:fragment="header">
<div class="container">
<div class="navbar-header">
</div>
</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>
<span sec:authorize="isAuthenticated()">
</span>
<script type="text/javascript"
src="webjars/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</footer>
</div>
</div>
</body>
</html>
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
</head>
<body>
<div class="container">
<div class="starter-template">
</div>
</div>
</body>
</html>
admin ~
src/main/resources/templates/admin.html
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
</head>
<body>
<div class="container">
<div class="starter-template">
</form>
</div>
</div>
</body>
</html>
user ~
src/main/resources/templates/user.html
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
</head>
<body>
<div class="container">
<div class="starter-template">
</form>
</div>
</div>
</body>
</html>
about ~
src/main/resources/templates/about.html
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
</head>
<body>
<div class="container">
<div class="starter-template">
</div>
</div>
</body>
</html>
login ~
src/main/resources/templates/login.html
<!DOCTYPE html>
>
<head>
</head>
<body>
<fieldset>
<div th:if="${param.error}">
</div>
</div>
<div th:if="${param.logout}">
</div>
</div>
<div class="form-group">
placeholder="UserName" required="true"
autofocus="true"/>
</div>
<div class="form-group">
placeholder="Password" required="true"/>
</div>
<div class="row">
</div>
</div>
</div>
</fieldset>
</form>
</div>
</div>
</div>
</body>
</html>
403 ~
src/main/resources/templates/error/403.html
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
</head>
<body>
<div class="container">
<div class="starter-template">
</div>
</div>
</html>
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
//...
https://medium.com/@gustavo.ponce.ch/spring-boot-spring-mvc-spring-security-mysql-
a5d8545d837d
https://medium.com/search?q=Spring%20mvc
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
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