Friday, 23 December 2016

Spring MVC with JDBC Template


Hi Friends,
Today I am here with most important  and valuable topic  in Java, its SPRING MVC
Here I am going to explain example with JDBC Template with Maven

Project Structure-1.



2.pom.xml
<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>
  <groupId>com.neesri</groupId>
  <artifactId>neeraj</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>war</packaging>
  <name>nee</name>

  
  
   <properties>
    <java.version>1.7</java.version>
    <spring.version>4.0.3.RELEASE</spring.version>
    <cglib.version>2.2.2</cglib.version>
</properties>




<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>
  
</project>
3. Contacts 

package com.neesri.bean;

public class Contacts {
private int id;
private String name;
private String email;
private String mobile;

public Contacts() {
}

public Contacts(int id, String name, String email, String mobile) {
super();
this.setId(id);
this.setName(name);
this.setEmail(email);
this.setMobile(mobile);
}

public int getId() {
return id;
}

public void setId(int id) {
this.id = id;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getEmail() {
return email;
}

public void setEmail(String email) {
this.email = email;
}

public String getMobile() {
return mobile;
}

public void setMobile(String mobile) {
this.mobile = mobile;
}

}

4. ContactDAO 


package com.neesri.bean;

import java.util.List;


public interface ContactDAO {

public void saveOrUpdate(Contacts contact);
    
    public void delete(int contactId);
     
    public Contacts get(int contactId);
     
    public List<Contacts> list();

}

5. ContactsDaoImplment 

package com.neesri.bean;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import javax.sql.DataSource;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.ResultSetExtractor;
import org.springframework.jdbc.core.RowMapper;


public class ContactsDaoImplment implements ContactDAO{
private JdbcTemplate jdbctemp;

public ContactsDaoImplment(DataSource datasource) {
jdbctemp = new JdbcTemplate(datasource);

}

public void saveOrUpdate(Contacts contact) {
if (contact.getId() > 0) {
// update
String sql = "UPDATE contacts SET name=?, email=?,  "
+ "mobile=? WHERE id=?";
jdbctemp.update(sql, contact.getName(), contact.getEmail(),
contact.getMobile(), contact.getId());
} else {
// insert
String sql = "INSERT INTO contacts (name, email,  mobile)"
+ " VALUES (?, ?, ?)";
jdbctemp.update(sql, contact.getName(), contact.getEmail(),
contact.getMobile());
}

}

public void delete(int contactId) {
String sql = "DELETE FROM contacts WHERE id=?";
jdbctemp.update(sql, contactId);
}

public List<Contacts> list() {
final String sql = "SELECT * FROM contacts";
List<Contacts> listContact = jdbctemp.query(sql,
new RowMapper<Contacts>() {

public Contacts mapRow(ResultSet rs, int rowNum)
throws SQLException {
Contacts aContact = new Contacts();

aContact.setId(rs.getInt("id"));
aContact.setName(rs.getString("name"));
aContact.setEmail(rs.getString("email"));

aContact.setMobile(rs.getString("mobile"));

return aContact;
}

});

return listContact;
}

public Contacts get(final int contactId) {
final String sql = "SELECT * FROM contacts WHERE id="
+ contactId;
return jdbctemp.query(sql, new ResultSetExtractor<Contacts>() {

public Contacts extractData(ResultSet rs) throws SQLException,
DataAccessException {
if (rs.next()) {
Contacts contact = new Contacts();
contact.setId(rs.getInt("id"));
contact.setName(rs.getString("name"));
contact.setEmail(rs.getString("email"));

contact.setMobile(rs.getString("mobile"));
return contact;
}

return null;
}

});
}

}

6. MvcConfiguration - i have used this class instead of spring.xml, dont  be confuse 

package com.neesri.config;

import javax.sql.DataSource;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

import com.neesri.bean.ContactDAO;
import com.neesri.bean.ContactsDaoImplment;


@Configuration
@ComponentScan(basePackages="com.neesri")
@EnableWebMvc
public class MvcConfiguration extends WebMvcConfigurerAdapter {


@Bean
public ViewResolver getViewResolver(){
InternalResourceViewResolver resolver=new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/view/");
resolver.setSuffix(".jsp");
return resolver;

}


@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
//super.addResourceHandlers(registry);
}

@Bean
   public DataSource getDataSource() {
       DriverManagerDataSource dataSource = new DriverManagerDataSource();
       dataSource.setDriverClassName("com.mysql.jdbc.Driver");
       dataSource.setUrl("jdbc:mysql://localhost:3306/contact_spring");
       dataSource.setUsername("neeraj");
       dataSource.setPassword("neeraj");
     
       return dataSource;
   }


@Bean
public  ContactDAO getcoContactDAO(){

return new ContactsDaoImplment(getDataSource());
}


}

7. HomeController -this is controller class

package com.neesri.controller;

import java.io.IOException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
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.servlet.ModelAndView;

import com.neesri.bean.ContactDAO;
import com.neesri.bean.Contacts;




@Controller
public class HomeController {

@Autowired
private ContactDAO contactDAO;

@RequestMapping(value="/")
  public ModelAndView listcontacts(ModelAndView model) throws IOException{
List<Contacts>listContacts=contactDAO.list();
model.addObject("listContact", listContacts);
model.setViewName("home");

return model;

}

@RequestMapping(value="/saveContact", method = RequestMethod.POST)
 public ModelAndView savecontact(@ModelAttribute Contacts contacts){
contactDAO.saveOrUpdate(contacts);
return new ModelAndView("redirect:/");


}


@RequestMapping(value = "/editContact", method = RequestMethod.GET)
public ModelAndView editContact(HttpServletRequest request) {
   int contactId = Integer.parseInt(request.getParameter("id"));
   Contacts contact = contactDAO.get(contactId);
   ModelAndView model = new ModelAndView("ContactForm");
   model.addObject("contact", contact);

   return model;
}


@RequestMapping(value = "/deleteContact", method = RequestMethod.GET)
public ModelAndView deleteContact(HttpServletRequest request) {
   int contactId = Integer.parseInt(request.getParameter("id"));
   contactDAO.delete(contactId);
   return new ModelAndView("redirect:/");
}


@RequestMapping(value = "/newContact", method = RequestMethod.GET)
public ModelAndView newContact(ModelAndView model) {
   Contacts newContact = new Contacts();
   model.addObject("contact", newContact);
   model.setViewName("ContactForm");
   return model;
}

}

8. ContactForm.jsp- this must be in WEB-INF/view folder

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
    <%@ 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>
</head>
<body>
<div align="center">
        <h1>New/Edit Contact</h1>
        <form:form action="saveContact" method="post" modelAttribute="contact">
        <table>
            <form:hidden path="id"/>
            <tr>
                <td>Name:</td>
                <td><form:input path="name" /></td>
            </tr>
            <tr>
                <td>Email:</td>
                <td><form:input path="email" /></td>
            </tr>
         
            <tr>
                <td>Telephone:</td>
                <td><form:input path="mobile" /></td>
            </tr>
            <tr>
                <td colspan="2" align="center"><input type="submit" value="Save"></td>
            </tr>
        </table>
        </form:form>
    </div>
</body>
</html>
9. home.jsp-  this must be in WEB-INF/view folder
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd">
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Contact Manager Home</title>
    </head>
    <body>
        <div align="center">
            <h1>Contact List</h1>
            <c:set var="root" value="${pageContext.request.contextPath}"/>
            <h3><a href="${root}/newContact">New Contact</a></h3>
            <table border="1">
                <th>No</th>
                <th>Name</th>
                <th>Email</th>
             
                <th>Mobile</th>
                <th>Action</th>
               
                <c:forEach var="contact" items="${listContact}" varStatus="status">
                <tr>
                    <td>${status.index + 1}</td>
                    <td>${contact.name}</td>
                    <td>${contact.email}</td>
                 
                    <td>${contact.mobile}</td>
                    <td>
                        <a href="${root}/editContact?id=${contact.id}">Edit</a>
                        &nbsp;&nbsp;&nbsp;&nbsp;
                        <a href="${root}/deleteContact?id=${contact.id}">Delete</a>
                    </td>
                           
                </tr>
                </c:forEach>          
            </table>
        </div>
    </body>
</html>
10 web.xml -the most important xml file , where we write about dispatherservlet
<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xmlns="http://java.sun.com/xml/ns/javaee"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
         id="WebApp_ID" version="2.5">

    <display-name>neeraj</display-name>
 
   <!--
- Location of the XML file that defines the root application context.
- Applied by ContextLoaderListener.
-->
 <context-param>
<param-name>contextClass</param-name>
<param-value>
org.springframework.web.context.support.AnnotationConfigWebApplicationContext
</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

<servlet>
<servlet-name>SpringDispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextClass</param-name>
<param-value>
org.springframework.web.context.support.AnnotationConfigWebApplicationContext
</param-value>
</init-param>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>com.neesri.config</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>SpringDispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>

<session-config>
<session-timeout>30</session-timeout>
</session-config>

</web-app>

.



Result is:




If any query then make a comment

Thanks
Neeraj Srivastava
Java Developer

Happy Learning :) :)
Keep Smiling :) :) :)

Sunday, 20 November 2016

How to configure the session timeout in servlet

How to configure the session timeout in servlet

1) Timeout in the deployment descriptor (web.xml)
Using the deployment descriptor, you can only set the timeout in minutes:
<session-config>
    <session-timeout>1</session-timeout>
</session-config>

2) Timeout with setMaxInactiveInterval()
but using the HttpSession api you can set the session timeout in seconds for a servlet:

HttpSession session = request.getSession();
session.setMaxInactiveInterval(40*60);

if you dont want to kill session in java then write it in web.xml

  <session-config>
    <session-timeout>-1</session-timeout>
  </session-config>
           or
 <session-config>
    <session-timeout>0</session-timeout>
</session-config>
             or

<session-config>
    <session-timeout>1000</session-timeout>
</session-config>

if it is like
  <session-config>
    <session-timeout>30</session-timeout>
  </session-config>
here 30 is in minutes
So when the client doesn't visit the webapp anymore for over 30 minutes, then the servletcontainer will trash the session. Every subsequent request, even though with the cookie specified, will not have access to the same session anymore. The servletcontainer will create a new one.
Note 1:-The session-timeout element defines the default session timeout interval for all sessions created in this web application.
Note 1:- Default value is  30 minutes if you don’t configure session timeout.
 The specified timeout must be expressed in a whole number of minutes. If the timeout is 0 or less,
The container ensures the default behaviour of sessions is never to time out. If this element is not specified, the container must set its default timeout period.
You can use "-1" where the session never expires. Since you do not know how much time it will take for the thread to complete.

Keep Happy Learning
Thanks
Neeraj Srivastava


Monday, 24 October 2016

Fetch Data From Database Using Java and Ajax


Hi friends, I think you all know how to fetch data from databse using Servlet, but some time you need to fetch data in another way like if insert into text and press the Enter key then data should me come into other text fields.

So I am giving example here. learn and enjoy this code

1.Jsp page

Here i have taken four input type text,
See Book Id,there is onKeyup property means when you enter into Book ID text and then press the Enter button then you will get data form database in to others fields.

onkeyup="get(this.value,<%=session.getAttribute("sid")%>)"

here this.value  means it will take enter value and ,<%=session.getAttribute("sid")%> means it will take id of your product, it is not necessary if your product is only one login

 <label class="text-danger"><strong>BOOK ID :</strong></label> <input type="text" name="lib_bookID"  id="lib_bookID"onkeyup="get(this.value,<%=session.getAttribute("sid")%>)" />
                    
                    
<label class="text-danger"><strong>AUTHOR NAME :</strong></label> <input type="text" style="color: green;"
name="lib_author" id="lib_author"/>
                          

<label class="text-danger"><strong>BOOK NAME :</strong></label> <input type="text" name="lib_book_name" id="lib_book_name"/>
                                                                                                             
<label class="text-danger"><strong>PUBLICATION NAME :</strong></label> <input type="text" name="publication_book" id="publication_book" />
                                               

2. Ajax


xmlhttp.open("GET","Getdata?book_number="+book_number + "&sid="+sid ,true);

see here, I have taken two parameter, because I have two login for different products.

And also check url ,this url must match with servlet url

<script>
       
        function get(book_number,sid)
               {
                   var xmlhttp=new XMLHttpRequest();
                   xmlhttp.onreadystatechange=function()
                     {
                     if (xmlhttp.readyState==4 && xmlhttp.status==200)
                       {
                       
 var responseArray = xmlhttp.responseText.split(",");
                         document.getElementById("lib_book_name").value=responseArray[0];
                         document.getElementById("lib_author").value=responseArray[1];
                         document.getElementById("publication_book").value=responseArray[2];
                       }
                     };
                    
                  
                   xmlhttp.open("GET","Getdata?book_number="+book_number + "&sid="+sid ,true);
                   xmlhttp.send();

               }
        </script>

3. Servlet code
package com.bookdetails;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import javax.mail.Session;
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 dbActivity.JDBCUtil;
@WebServlet("/Getdata")
public class Getdata extends HttpServlet {
       private static final long serialVersionUID = 1L;
       public Getdata() {
              super();
                     }

      
       protected void doGet(HttpServletRequest request,
                     HttpServletResponse response) throws ServletException, IOException {
             
String book_number = request.getParameter("book_number");
String sid=request.getParameter("sid");
      
      

              System.out.println(book_number);
              System.out.println(sid);

              String book, auth, puslh;
              try {

                     Connection con = JDBCUtil.getConnection();
       // here create connection according to youJDBCUtil is my connection class

       
                     PreparedStatement ps = con
                                  .prepareStatement("SELECT BOOK_NAME,AUTHOR_NAME,PUBLISHER_NAME from BOOK_REGISTRATION where BOOK_NUMBER=? and SID=?");
                     ps.setString(1, book_number);
                     ps.setString(2, sid);
                     ResultSet rs = ps.executeQuery();
                     if (rs.next()) {
                           book = rs.getString("BOOK_NAME");
                           auth = rs.getString("AUTHOR_NAME");
                           puslh = rs.getString("PUBLISHER_NAME");
                     } else {
                           book = "";
                           auth = "";
                           puslh = "";
                     }
                     response.getWriter().write(book + "," + auth + "," + puslh);

                    
              } catch (Exception e) {

                     e.printStackTrace();
              }

       }

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

       }

}

If any query then put your questions into comment box.

Thanks
Neeraj Srivastava

Happy Learning

Friday, 14 October 2016

How to get rid of “maximum user connections” error ?

1.Run this query

SELECT max_user_connections FROM mysql.user
WHERE user='db_user' AND host='localhost';

(in user after where plz write your db username,all will be same)

If this is a nonzero value, change it back with:

GRANT USAGE ON *.* TO db_user@localhost MAX_USER_CONNECTIONS 0;
or

UPDATE mysql.user SET max_user_connections = 0
WHERE user='db_user' AND host='localhost';

FLUSH PRIVILEGES;



Once you get to this point, now check the global setting using

SHOW VARIABLES LIKE 'max_user_connections';




If this is a nonzero value, you need to do two things

THING #1 : Look for the setting in /etc/my.cnf

[mysqld]
max_user_connections = <some number>
comment that line out

THING #2 : Set the value dynamically

SET GLOBAL max_user_connections = 0;

MySQL restart is not required





//increate the connection

UPDATE mysql.user SET
max_connections = 1000
WHERE user='myuser' AND host='localhost';
FLUSH PRIVILEGES;


To set the maximum number of queries per hour at 1000 on a given connection do this:

UPDATE mysql.user SET
max_questions = 1000
WHERE user='myuser' AND host='localhost';
FLUSH PRIVILEGES;
To set the maximum number of updates per hour at 1000 on a given connection do this:

UPDATE mysql.user SET
max_updates = 1000
WHERE user='myuser' AND host='localhost';
FLUSH PRIVILEGES;
To set the maximum number of connections per hour at 1000 on a given connection do this:

UPDATE mysql.user SET
max_connections = 1000
WHERE user='myuser' AND host='localhost';
FLUSH PRIVILEGES;


Happy Learning

Sunday, 9 October 2016

How to configure spring nature in eclipse?



1. Install New Software

 Eclipse IDE, click “Help” -> “Install New Software…”. 
Type “http://springide.org/updatesite” to access the Spring IDE update site.

Select all the Spring IDE features you want to install.

Take long time to install and restart Eclipse after finished.

OR

1. Eclipse Marketplace
(NO NEED TO KEEP REMEMBER LONG URL)

This is the prefer way, because you no need to remember the long Spring ide update URL.
In Eclipse IDE, click “Help” -> “Eclipse Marketplace“, type “Spring IDE“, follow the wizard to finish the installation.


2.select new project as a dynamic projects in eclipse

3. right click on project and then go to spring tool (second last option,just before properties)

click on "add spring project nature"

and now your project is ready for spring mvc :)


if any query then make a note in comment box

Thanks

Happy Learning

Friday, 7 October 2016

Why Apache Tomcat 7.0.40 disappears after 1 second

Catalina needs JAVA_HOME to work properly. So configure path to java jre and JAVA_HOME in environment variables.
To see the error, in command prompt execute
\path\apache-tomcat-7.0.40\bin > catalina.bat run