Tuesday, 20 September 2016

Start tomcat at windows 7 startup


Copy the bat file in windows Startup folder
C:\Users\userName\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup
if you dont get AppData or Roaming folder then make sure that your folder is not hidden
it will allow the program to launch upon starting up Windows 7


Thanks
Keep Happy Learning

Friday, 9 September 2016

Spring Framework In Java(VVI)




Spring MVC,  I think  every  Java developer  wants  to learn Spring framework, because its a "Framework of Fromeworks", Well  this  is  super  framework which provides  loose coupling,

ok,  now  i  am starting  from  simple example of  spring    with  jdbc  template, we  use  jdbc  template  instead  of  JDBC,  you  know  its a  amazing  thing,  lets start  with it then  you will get how much it is interesting,

one  more  thing  you  must  know  about  Spring  theory.ok, I have developed this example in eclipse I have downloaded spring plugins in eclipse and took  as maven project. Here we will not use any jar files but use dependency jars in to pom.xml  files,  please read about maven its very easy. J

we use generally JDBC for database connection  and you know  all exception  in  JDBC are checked Exception So  its Our  responsibility to  open and close connections  and use try catch block  for  exception handling right
Spring JDBC have one abstraction layer on top of existing JDBC technology,
We  work with Spring JDBC and this call to jdbc internally,  so there is no need of  open and close connection it will be taken care by spring. And also this converts  checked exceptios to unchecked exceptions .


Step:-1

Make database
CREATE DATABASE contact_spring;
And  column is id,name,email and mobile

Step:-2
Put all this dependencies in to your pom.xml file
<dependencies>
    <!-- Spring core & mvc -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>${spring.version}</version>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-orm</artifactId>
        <version>${spring.version}</version>
        <type>jar</type>
        <scope>compile</scope>
    </dependency>

    <!-- CGLib for @Configuration -->
    <dependency>
        <groupId>cglib</groupId>
        <artifactId>cglib-nodep</artifactId>
        <version>${cglib.version}</version>
        <scope>runtime</scope>
    </dependency>


    <!-- Servlet Spec -->
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>3.1.0</version>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>javax.servlet.jsp</groupId>
        <artifactId>javax.servlet.jsp-api</artifactId>
        <version>2.3.1</version>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>jstl</groupId>
        <artifactId>jstl</artifactId>
        <version>1.2</version>
    </dependency>
   
    <dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.30</version>
</dependency>

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jdbc</artifactId>
    <version>4.0.3.RELEASE</version>
</dependency>

</dependencies>




Step:-3
Make Bean class

package com.nee.spring.modal;

public class Customer {

     private int id;
     private String name;
     private String email;
     private String mobile;

     public Customer(int id, String name, String email, String mobile) {
           super();
           this.setId(id);
           this.setName(name);
           this.setEmail(email);
           this.setMobile(mobile);
     }
// here getter and setter methods
}


Step:-4

package com.nee.spring.modal;

import org.springframework.jdbc.core.JdbcTemplate;

public class CustomerDao {

     private JdbcTemplate jdbTemplate;

     public JdbcTemplate getJdbTemplate() {
           return jdbTemplate;
     }

     public void setJdbTemplate(JdbcTemplate jdbTemplate) {
           this.jdbTemplate = jdbTemplate;
     }

     public int saveEmployee(Customer e) {
           String query = "insert into contacts values( '" + e.getId() + "','"
                     + e.getName() + "','" + e.getEmail() + "','" + e.getMobile()
                     + "')";

           return jdbTemplate.update(query);
     }

     public int updateEmployee(Customer e) {
           String query = "update contacts set name='" + e.getName() + "',EMAIL='"
                     + e.getEmail() + "' where id='" + e.getId() + "' ";

           return jdbTemplate.update(query);
     }

     public int deleteEmployee(Customer e) {
           String query = "delete from contacts where id='" + e.getId() + "' ";
           return jdbTemplate.update(query);
     }
}

Step:-5


<?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" 
    xsi:schemaLocation="http://www.springframework.org/schema/beans  
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> 
 
<bean id="ds" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> 
<property name="driverClassName" value="com.mysql.jdbc.Driver" /> 
<property name="url" value="jdbc:mysql://localhost:3306/contact_spring" /> 
<property name="username" value="neeraj" /> 
<property name="password" value="neeraj" /> 
</bean> 
 
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> 
<property name="dataSource" ref="ds"></property> 
</bean> 
 
<bean id="edao" class="com.nee.spring.modal.CustomerDao"> 
<property name="jdbTemplate" ref="jdbcTemplate"></property> 
</bean> 
 
</beans> 

Step:-6

package com.nee.spring.modal;

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

public class Test1 {
            public static void main(String[] args) {

                        ApplicationContext applicationContext = new ClassPathXmlApplicationContext(
                                                "applicationContext.xml");

                        CustomerDao customerDao = (CustomerDao) applicationContext
                                                .getBean("edao");

                        int status = customerDao.saveEmployee(new Customer(101,
                                                "Neeraj Srivastava", "neeraj.javadeveloper@gmail.com",
                                                "9876543210"));
                        System.out.println(status);

            }
}

Finally right click on project and run as java application and check your database you will get values are inserted into databse, this is just simple example of Spring MVC, I will come with web application  also. Good Luck Friends

If any query then send me mail at neeraj.javadeveloper@gmail.com

Thanks

Keep Happy Learning

Thursday, 8 September 2016

How to Download file from server in Java


This is example using servlet, you must be basic knowledge of file handling, because here we have to create file into specifric folder.




import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/DownLoadFile")
public class DownLoadFile extends HttpServlet {
private static final long serialVersionUID = 1L;

public DownLoadFile() {
super();

}

protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {

response.setContentType("text/html");
PrintWriter out = response.getWriter();

            //create file name
String filename = "customer.csv";
                 //create folder
String upload = "/folderCsv/";
             //method for getting path 
String filepath = request.getServletContext().getRealPath(upload);

// creates the save directory if it does not exists
File folder = new File(filepath);
if (!folder.exists()) {

folder.mkdir();
}

response.setContentType("APPLICATION/OCTET-STREAM");
response.setHeader("Content-Disposition", "attachment; filename=\""
+ filename + "\"");

FileInputStream fileInputStream = new FileInputStream(filepath
+ File.separator + filename);

int i;
while ((i = fileInputStream.read()) != -1) {
out.write(i);
}
fileInputStream.close();
out.close();

}

now jsp contents are in my coding

 <a href="DownloadExportFile" target="_blank"> <img src="img/excellogo.png" height="200px" width="200px"></a></center>
                        </div><br>

here i have use a image for downloading


Thanks
Keep Happy Learning

How To Export Database Data To Excel File In Java


I am here to tell you how can we export database data into excel file and then download it in servlet, you can also put this logic in core java and any framework in java.

one important thing dont forget to download apache poi jar and put into lib, by this API we can export data easily.



import java.io.File;

import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.Connection;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

/**
 * Servlet implementation class DatabaseToExcel
 */
@WebServlet("/DatabaseToExcel")
public class DatabaseToExcel extends HttpServlet {
private static final long serialVersionUID = 1L;

/**
* @see HttpServlet#HttpServlet()
*/
public DatabaseToExcel() {
super();
// TODO Auto-generated constructor stub
}


@SuppressWarnings("deprecation")
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {

Connection connection;
Statement stmt;
ResultSet rs;

try {
connection = com.Database.nee.DatabaseConnect.getConnection();
stmt = connection.createStatement();
String query = "Select C.TYPE,C.CUSTOMER,C.MOBILE, P.PURCHASE_DATE,P.DEAL_ID from customer C "
+ "INNER JOIN productinfo P ON C.C_ID=P.C_ID";
rs = stmt.executeQuery(query);

HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("lawix10");
HSSFRow rowhead = sheet.createRow((short) 0);
rowhead.createCell((short) 0).setCellValue("TYPE");
rowhead.createCell((short) 1).setCellValue("CUSTOMER");
rowhead.createCell((short) 2).setCellValue("MOBILE");
rowhead.createCell((short) 3).setCellValue("PURCHASE_DATE");
rowhead.createCell((short) 4).setCellValue("DEAL_ID");

int i = 1;

while (rs.next()) {

HSSFRow row = sheet.createRow((short) i);
// row.createCell((short)
// 0).setCellValue(Integer.toString(rs.getInt("TYPE")));
row.createCell((short) 0).setCellValue(rs.getString("TYPE"));
row.createCell((short) 1)
.setCellValue(rs.getString("CUSTOMER"));
row.createCell((short) 2).setCellValue(rs.getString("MOBILE"));
row.createCell((short) 3).setCellValue(
rs.getString("PURCHASE_DATE"));
row.createCell((short) 4).setCellValue(rs.getString("DEAL_ID"));
i++;
System.out.println(i);

}

String filename = "bajaj.xls";
String upload = "/folderCsv/";
String filepath = request.getServletContext().getRealPath(upload);
File folder = new File(filepath);
if (!folder.exists()) {

folder.mkdir();
}
String exactPath = filepath + File.separator + filename;
FileOutputStream filOut = new FileOutputStream(exactPath);
workbook.write(filOut);

filOut.close();

} catch (SQLException | IOException e) {

e.printStackTrace();
}



String message = "<span style='color:green;'>"
+ " Data Is Exported Successfully"
+ "</span>";
request.setAttribute("message", message);
request.getRequestDispatcher("/exportContacts.jsp").forward(request,
response);


}

protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}


Here i have created database connection according to me but you can do it according to you. and i think you know how to play with jsp.



Thanks

Keep Happy Learning !