Friday 30 September 2016

How to Upload Multiple files or Image on Server in Java(VVI)



After wasting 2 days  I came to know how to upload multiple files  on server, I searched many times on internet but  did not  get  solution ,now i can take breath  :P its very important code.
i know the value of this code :) this is for updated servlet3

 keep in mind
1.Do not forget to use enctype="multipart/form-data" in form action of jsp
2.Do not forget to use
@MultipartConfig(maxFileSize = 1024 * 1024 * 50, maxRequestSize = 1024 * 1024 * 100)

if you dont use it then you will get Null pointer exception and believe me even after debugging you will not come to know exact reason, :)


Jsp page
<input type="file" name="files1" >
<input type="file" name="files2" >
<input type="file" name="files3" >
Here name of file is different

Now servlet code


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

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



@MultipartConfig(maxFileSize = 1024 * 1024 * 50, maxRequestSize = 1024 * 1024 * 100)
// 5MB,and 100MB
@WebServlet("/Add_admin_user")
public class Add_admin_user extends HttpServlet {
       private static final long serialVersionUID = 1L;


response.setContentType("text/html;charset=UTF-8");

              PrintWriter out = response.getWriter();
// for multiple files upload

              String filesFolder = "/filesFolder/";
here getting exact path of project
              String appPath_for_multileFiles = request.getServletContext()
                           .getRealPath(filesFolder);

              File multifile = new File(appPath_for_multileFiles);

              if (!multifile.exists()) {

                     multifile.mkdir();
              }

See here if you forget to create new folder then it will create folder on server


//for file 1

       Part part1 = request.getPart("files1");
              if (part1 != null) {

                     if (part1.getSize() != 0) {

              String fileName1 = extractgetFileName(part1);
       if (fileName1 != null) {
       part1.write(appPath_for_multileFiles + File.separator
                     + fileName1);

     String filePath1 = appPath_for_multileFiles + File.separator
                                                + fileName1;

       System.out.println("customer filePath1 full path " + filePath1);

                                 
                           }
                     }
              }

//for file 2
Part part2 = request.getPart("files2");
if (part2 != null) {

       if (part2.getSize() != 0) {

              String fileName2 = extractFileName(part2);
       if (fileName2 != null) {
                     part2.write(appPath_for_multileFiles + File.separator
                                                + fileName2);

              String filePath2 = appPath_for_multileFiles + File.separator
                                                + fileName2;

              System.out.println("customer filePath2 full path " + filePath2);

                                 
                           }
                     }
              }

//for file 3

              Part part3 = request.getPart("files3");
              if (part3 != null) {

       if (part3.getSize() != 0) {
String fileName3 = extractFileName(part3);
       if (fileName3 != null) {
              part3.write(appPath_for_multileFiles + File.separator
                                                + fileName3);

       String filePath3 = appPath_for_multileFiles + File.separator
                                                + fileName3;
System.out.println("customer filePath3 full path " + filePath3);

                                 
                           }
                     }
              }



private String extractgetFileName(Part part) {
              String contentDisp = part.getHeader("content-disposition");
              String[] items = contentDisp.split(";");
              for (String s : items) {
                     if (s.trim().startsWith("filename")) {
                           return s.substring(s.indexOf("=") + 2, s.length() - 1);
                     }
              }
              return "";


       }

if any query then put your questions in comment box.

Thanks
Happy Keep Learning

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