Nearby lessons

34 of 35

Spring - Integration with Servlets

📌 What You Will Learn
  • Understand Spring - Integration with Servlets
  • See working code examples
  • Learn from common mistakes and Q&A

Learn Spring - Integration with Servlets step by step — simple explanations, complete programs with their output, common beginner mistakes, and exam-style MCQs.

a) Prepare html file or jsp file

  • select "src".
  • select "main".
  • Right Click on "webapps".
  • Select "New".
  • Select "Html File".
  • Provide File Name "loginform.html".
  • Click on "Next".
  • Click on "Finish".
  • Provide Html Code in loginform.html.
  • Save Html File.

EX: loginform.html

a) Prepare html file or jsp file

Example02
JCode Cell
1 
2<html>
3<body>
4<form action="./hello" method="post">
5User Name<input type="text" name="uname"/><br>
6Password<input type="password" name="upwd"/><br>
7<input type="submit" value="Login"/>
8</form>
9</body>
10</html>
11

a) Prepare html file or jsp file

Example03
JCode Cell
1 
2success.html
3<!DOCTYPE html>
4<html>
5<head>
6<meta charset="ISO-8859-1">
7<title>Insert title here</title>
8</head>
9<body>
10<h1>Durga Software Solutions</h1>
11<h2>User Login Status</h2>
12<font color="red" size="7">User Login Success</font>
13<h3>
14<a href="./loginform.html">|User Login Form|</a>
15</h3>
16</body>
17</html>
18

a) Prepare html file or jsp file

Example04
JCode Cell
1 
2failure.html
3<!DOCTYPE html>
4<html>
5<head>
6<meta charset="ISO-8859-1">
7<title>Insert title here</title>
8</head>
9<body>
10<h1>Durga Software Solutions</h1>
11<h2>User Login Status</h2>
12<font color="red" size="7">User Login Failure</font>
13<h3>
14<a href="./loginform.html">|User Login Form|</a>
15</h3>
16</body>
17</html>
18

b) Prepare Servlets

a. Project Name : loginapp

b. Folder Name: src/main/servlets

c. Click on "Finish" Button.

Example05
JCode Cell
1 
2Right Click on Java Resources.
3Select "New".
4Select "Source Folder".
5Provide the following details.
6

b) Prepare Servlets

a) Package Name: com.durgasoft.servlets

b) Class Name : LoginServlet

Example06
JCode Cell
1 
2Right Click on "src/main/servlets" folder.
3Select "New".
4Select "Servlet".
5Provide the following details.
6

b) Prepare Servlets

EX: LoginServlet.java

Example07
JCode Cell
1 
2Click on "Next" button.
3Edit URL Pattern "/login".
4Click on "Next" button.
5Select "doPost" [bydefault Selected].
6Click on "Finish" button.
7Write Application Logic in Servlets.
8

b) Prepare Servlets

Example08
JCode Cell
1 
2package com.durgasoft.servlets;
3

b) Prepare Servlets

Example09
JCode Cell
1 
2import java.io.IOException;
3

b) Prepare Servlets

Example10
JCode Cell
1 
2import javax.servlet.RequestDispatcher;
3import javax.servlet.ServletException;
4import javax.servlet.http.HttpServlet;
5import javax.servlet.http.HttpServletRequest;
6import javax.servlet.http.HttpServletResponse;
7

b) Prepare Servlets

ows ServletException, IOException {

Example11
JCode Cell
1 
2import com.durgasoft.service.UserService;
3public class LoginServlet extends HttpServlet {
4private static final long serialVersionUID = 1L;
5protected void doPost(HttpServletRequest request, HttpServletResponse response) thr
6

b) Prepare Servlets

Example12
JCode Cell
1 
2response.setContentType("text/html");
3String uname = request.getParameter("uname");
4String upwd = request.getParameter("upwd");
5RequestDispatcher reqDispatcher = null;
6UserService userService = new UserService();
7String status = userService.checkLogin(uname, upwd);
8if(status.equals("success")) {
9reqDispatcher = request.getRequestDispatcher("success.html");
10reqDispatcher.forward(request, response);
11}else {
12reqDispatcher = request.getRequestDispatcher("failure.html");
13reqDispatcher.forward(request, response);
14}
15

b) Prepare Servlets

Example13
JCode Cell
1 
2}
3

b) Prepare Servlets

web.xml

Example14
JCode Cell
1 
2}
3

b) Prepare Servlets

Example15
JCode Cell
1 
2<!DOCTYPE web-app PUBLIC
3"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
4"http://java.sun.com/dtd/web-app_2_3.dtd" >
5

b) Prepare Servlets

Example16
JCode Cell
1 
2<web-app>
3<display-name>Archetype Created Web Application</display-name>
4<servlet>
5<servlet-name>LoginServlet</servlet-name>
6<display-name>LoginServlet</display-name>
7<description></description>
8<servlet-class>com.durgasoft.servlets.LoginServlet</servlet-class>
9</servlet>
10<servlet-mapping>
11<servlet-name>LoginServlet</servlet-name>
12<url-pattern>/login</url-pattern>
13</servlet-mapping>
14<welcome-file-list>
15<welcome-file>loginform.html</welcome-file>
16</welcome-file-list>
17</web-app>
18

c)Prepare Service Class As per the requirement

i) Package Name : com.durgasoft.service

ii) Class Name : UserService

Example17
JCode Cell
1 
2Right Click on "src/main/servlets"
3Select "New".
4Select "Class"
5Provide the following details.
6

c)Prepare Service Class As per the requirement

EX:UserService.java

Example18
JCode Cell
1 
2Select "Next" button
3Provide Application Logic in UserService class
4

c)Prepare Service Class As per the requirement

Example19
JCode Cell
1 
2package com.durgasoft.service;
3

c)Prepare Service Class As per the requirement

Example20
JCode Cell
1 
2import java.sql.Connection;
3import java.sql.DriverManager;
4import java.sql.ResultSet;
5import java.sql.Statement;
6

c)Prepare Service Class As per the requirement

", "durga");

Example21
JCode Cell
1 
2public class UserService {
3Connection con;
4Statement st;
5ResultSet rs;
6String status = "";
7public UserService() {
8try {
9Class.forName("oracle.jdbc.OracleDriver");
10con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "system
11

c)Prepare Service Class As per the requirement

wd = '"+upwd+"'");

Example22
JCode Cell
1 
2st = con.createStatement();
3} catch (Exception e) {
4e.printStackTrace();
5}
6}
7public String checkLogin(String uname, String upwd) {
8try {
9rs = st.executeQuery("select * from reg_Users where uname = '"+uname+"' and up
10

c)Prepare Service Class As per the requirement

7.Past the URL in Browser Addressbar.

http://localhost:9944/loginapp/loginform.html

  • Provide data and click on "Login" button and get response from LoginServlet.

Spring Core Module Application in MAVEN

Steps to Prepare Spring Core Module Application in MAVEN:

  • Create Maven Quick Start Project.
  • Provide Configurations in pom.xml file.
  • Prepare Spring Resources like Beans, Configuration Files, Test and Cases...
  • Run Spring Application
  • Create Maven Quick Start Project.
  • Open Eclipse IDE
  • Right Click on "Project Explorer"
  • Select "New"
  • Select "Others"
  • Search for "Maven".
  • Select for "Maven Project".
  • Click on "Next" button.
  • Click on "Next" button.
  • Provide the following details.

a. groupId: com.durgasoft

b. artifactId: springapp1

c. version: 0.0.1-SNAPSHOT

d. package: com.durgasoft

  • Click on "Finish" Button.
  • Provide Configurations in pom.xml file.
  • Open pom.xml file File and provide java8 plugin configuration:

EX:

Example23
JCode Cell
1 
2boolean b = rs.next();
3if(b == true) {
4status = "success";
5}else {
6status = "failure";
7}
8} catch (Exception e) {
9e.printStackTrace();
10}
11return status;
12}
13}
14Update Project:
15Right Click on Project.
16Select "Maven".
17Select "Update Project".
18Select Project and Click on "OK" button.
19Run Application:
20Right Click on Project.
21Select "Run As".
22Select "Maven Build...".
23Provide Value to "Goals" : tomcat:run -Dmaven.tomcat.port=9944[Any port number]
24Click on "Run" button.
25Copy the URL from Console.
26

c)Prepare Service Class As per the requirement

EX:

Example24
JCode Cell
1 
2<build>
3<plugins>
4<plugin>
5<groupId>org.apache.maven.plugins</groupId>
6<artifactId>maven-compiler-plugin</artifactId>
7<version>3.7.0</version>
8<configuration>
9<source>1.8</source>
10<target>1.8</target>
11</configuration>
12</plugin>
13</plugins>
14</build>
15Provide Spring dependencies in pom.xml file
16

c)Prepare Service Class As per the requirement

Example25
JCode Cell
1 
2<dependencies>
3<dependency>
4<groupId>org.springframework</groupId>
5<artifactId>spring-core</artifactId>
6<version>4.3.18.RELEASE</version>
7</dependency>
8

c)Prepare Service Class As per the requirement

Example26
JCode Cell
1 
2<dependency>
3<groupId>org.springframework</groupId>
4<artifactId>spring-context</artifactId>
5<version>4.3.18.RELEASE</version>
6</dependency>
7

c)Prepare Service Class As per the requirement

Note: In the above dependencies, just add spring-core and spring-context dependencies in

pom.xml file then automatically all other dependencies are also be loaded.

EX: pom.xml

Example27
JCode Cell
1 
2<dependency>
3<groupId>org.springframework</groupId>
4<artifactId>spring-aop</artifactId>
5<version>4.3.18.RELEASE</version>
6</dependency>
7</dependencies>
8

c)Prepare Service Class As per the requirement

XMLSchema-instance"

  • xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/m

aven-4.0.0.xsd">

Example28
JCode Cell
1 
2<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/
3

c)Prepare Service Class As per the requirement

Example29
JCode Cell
1 
2<modelVersion>4.0.0</modelVersion>
3

c)Prepare Service Class As per the requirement

Example30
JCode Cell
1 
2<groupId>com.durgasoft</groupId>
3<artifactId>springapp1</artifactId>
4<version>0.0.1-SNAPSHOT</version>
5<packaging>jar</packaging>
6

c)Prepare Service Class As per the requirement

Example31
JCode Cell
1 
2<name>springapp</name>
3<url>http://maven.apache.org</url>
4

c)Prepare Service Class As per the requirement

Example32
JCode Cell
1 
2<properties>
3<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
4</properties>
5

c)Prepare Service Class As per the requirement

Example33
JCode Cell
1 
2<dependencies>
3<dependency>
4<groupId>junit</groupId>
5<artifactId>junit</artifactId>
6<version>3.8.1</version>
7<scope>test</scope>
8</dependency>
9

c)Prepare Service Class As per the requirement

Example34
JCode Cell
1 
2<dependency>
3<groupId>org.springframework</groupId>
4<artifactId>spring-core</artifactId>
5<version>4.3.18.RELEASE</version>
6</dependency>
7

c)Prepare Service Class As per the requirement

Example35
JCode Cell
1 
2<dependency>
3<groupId>org.springframework</groupId>
4<artifactId>spring-context</artifactId>
5<version>4.3.18.RELEASE</version>
6</dependency>
7

c)Prepare Service Class As per the requirement

Example36
JCode Cell
1 
2<dependency>
3<groupId>org.springframework</groupId>
4<artifactId>spring-aop</artifactId>
5<version>4.3.18.RELEASE</version>
6</dependency>
7</dependencies>
8<build>
9<plugins>
10<plugin>
11<groupId>org.apache.maven.plugins</groupId>
12<artifactId>maven-compiler-plugin</artifactId>
13<version>3.7.0</version>
14<configuration>
15<source>1.8</source>
16<target>1.8</target>
17</configuration>
18</plugin>
19</plugins>
20</build>
21</project>
22Save pom.xml file and see "Markers" for errors.
23Right Click on :Project"
24Select "Maven" .
25Select "Update Project".
26Click on "OK" button.
27Prepare Spring Resources like Beans, Configuration Files, Test Cases...
28

a) Prepare Bean class

  • Right Click on "src/java/main".
  • Select "New"
  • Select "Class".
  • Provide the following details

Package: com.durgasoft.beans

Class : HelloBean

5 .Click on "Finish" button.

  • Provide properties and methods in Bean class.

EX: HelloBean.java

a) Prepare Bean class

Example38
JCode Cell
1 
2package com.durgasoft.beans;
3

a) Prepare Bean class

Example39
JCode Cell
1 
2public class HelloBean {
3public String sayHello() {
4return "Hello User!";
5}
6}
7

b) Prepare Spring Configuration File

  • Right Click on "src\java\main".
  • Select "Package".
  • Provide package name "com.durgasoft.resources".
  • Click on "Finish" button.
  • Right Click on "com.durgasoft.resources" package.
  • Select "New".
  • Select "Other".
  • Search "XML" and select "XML File".
  • Click on "Next" button.
  • Provide file Name: applicationContext.xml
  • Click on "Next" button.
  • Click on "Finish" Button.

EX: applicationContext.xml

b) Prepare Spring Configuration File

Example41
JCode Cell
1 
2<?xml version="1.0" encoding="UTF-8"?>
3<beans xmlns="http://www.springframework.org/schema/beans"
4xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
5xsi:schemaLocation="http://www.springframework.org/schema/beans
6http://www.springframework.org/schema/beans/spring-beans.xsd">
7<bean id="helloBean" class="com.durgasoft.beans.HelloBean"/>
8</beans>
9

c) Prepare Test Application

  • Right Click on "src/java/main".
  • Select "New"
  • Select "Class".
  • Provide the following details

Package: com.durgasoft.test

Class : TestClient

  • Click on "Finish" button.
  • Provide application Logic in TestClient class.

EX:TestClient.java

c) Prepare Test Application

Example43
JCode Cell
1 
2package com.durgasoft.test;
3

c) Prepare Test Application

Example44
JCode Cell
1 
2import org.springframework.context.ApplicationContext;
3import org.springframework.context.support.ClassPathXmlApplicationContext;
4

c) Prepare Test Application

Example45
JCode Cell
1 
2import com.durgasoft.beans.HelloBean;
3

c) Prepare Test Application

sources/applicationContext.xml");

Example46
JCode Cell
1 
2public class TestClient {
3public void test() {
4ApplicationContext context = new ClassPathXmlApplicationContext("com/durgasoft/re
5

c) Prepare Test Application

d)Access TestClient Application from JUnit test[src\test\main\TestApp.java]:

EX:TestApp.java

Example47
JCode Cell
1 
2HelloBean bean = (HelloBean) context.getBean("helloBean");
3String message = bean.sayHello();
4System.out.println(message);
5}
6}
7

c) Prepare Test Application

Example48
JCode Cell
1 
2package com.durgasoft;
3import com.durgasoft.test.TestClient;
4import junit.framework.Test;
5import junit.framework.TestCase;
6import junit.framework.TestSuite;
7public class AppTest
8extends TestCase
9{
10public AppTest( String testName )
11{
12super( testName );
13}
14

c) Prepare Test Application

Example49
JCode Cell
1 
2public static Test suite()
3{
4return new TestSuite( AppTest.class );
5}
6

c) Prepare Test Application

Example50
JCode Cell
1 
2public void testApp()
3{
4TestClient client = new TestClient();
5client.test();
6

c) Prepare Test Application

LOG4J

COURSE MATERIAL

BY

SPRING LOG4J MODULE INDEX

  • INTRODUCTION...................................................................Page 745
  • Log4j......................................................................................Page 748
  • Appenders.............................................................................Page 755
  • Layouts..................................................................................Page 761

INTRODUCTION

In Real time applications development, we may get no of problems or bugs or exceptions while

executing or testing the applications, Ti identify the problems and their locations then we have to

trace the applications flow of execution.

To trace applications flow of execution we will use "System.out.println(--)" at basic level.

EX:

Example51
JCode Cell
1 
2assertTrue( true );
3}
4}
5Run Spring Application:
6Right Click on Project[springapp1].
7Select "Run As".
8Select "Maven Test" and see the Result in Console.
9

c) Prepare Test Application

If we execute the above application then we are able to get the following output on console or

command prompt.

Before deposit() method call

logic for deposit

After deposit() method call

Before withdraw() method call

logic for withdraw

After withdraw() method call

Before transfer() method call

logic for transfer

After transfer() method call

If we use System.out.println() method in applications to trace flow of execution then we are able to

get the following problems.

Example52
JCode Cell
1 
2class Transaction{
3void deposit(){
4System.out.println("logic for deposit");
5}
6void withdraw(){
7System.out.println("logic for withdraw");
8}
9void transfer(){
10System.out.println("logic for transfer");
11}
12}
13class Test{
14Transaction tx = new Transaction();
15System.out.println("Before deposit() method call");
16tx.deposit()
17System.out.println("After deposit() method call");
18-----
19System.out.println("Before withdraw() method call");
20tx.withdraw();
21System.out.println("After withdraw method call");
22------
23System.out.println("Before transfer() method call");
24tx.transfer();
25System.out.println("After transfer() method call");
26}
27
Output

logic for deposit
logic for withdraw
logic for transfer
Before deposit() method call
After deposit() method call
Before withdraw() method call
After withdraw method call
Before transfer() method call
After transfer() method call
      

c) Prepare Test Application

output systems like file systems[html files, xml files, text files...], databases, network,....

Example53
JCode Cell
1 
2System.out.println(--) will be used for only console display, not for sending data to any other
3

c) Prepare Test Application

expensive and time consuming.

  • In Applications, it is not suggestible to write too many no of System.out.println() methods in

applications, because, it will reduce application performance.

Example54
JCode Cell
1 
2System.out.println() method contains synchronized block to display data, it is heavy weight,
3

c) Prepare Test Application

production environment , because, if we use System.out.println() method in server side

applications then it will display messages in servers console only, it will not be avaiable to

users.

Example55
JCode Cell
1 
2System.out.println() method is usefull in Development environment only, It is not suitable in
3

c) Prepare Test Application

show differences in Error messages, warning messaages, normal information,....

Example56
JCode Cell
1 
2System.out.println() will display the messages on console or on command prompt, it will not
3

c) Prepare Test Application

enterprise applications.

To overcome all the problems while tracing applications we have to use Logging.

Logging : It is the process of writing log messages during the execution of a program to a central

place. This logging allows you to report and persist error and warning messages as well as info

messages so that the messages can later be retrieved and analyzed.

In general, in java applications, Logging is required

  • To understand flow of execution in applications
  • To manage exception messages when Exceptions are occurred in java applications
  • To manage the event - notification messages in file systems....

Logging Framework: It is a set of classes and interfaces or a product to perform Logging in Java

applications.

EX:

Example57
JCode Cell
1 
2System.out.println() is suitable for simple standalone applications, not for complex
3

c) Prepare Test Application

Advantages of Logging Frameworks:

  • Problem diagnosis: In ingeneral, in application development, we are able to detect the

problems which are occurred in compilation time or in execution, but, some hidden problems are

existed inside the applications, which may not come in out side direcly, but, they will give effect to

our application execution, in this situation, if we use good Logging Framework then it is possible to

detect the hidden problems quickly and we can fix them easily.

  • Quick Debugging: Once if we diagnose the problem and if we identify the location of the

problem by using logging framework then it is very simple to fix that problem and it simplifies

Debugging and it able to reduce overall Debugging time.

  • Easy Maintenance: If we provide good Logging Framework to perform logging in our

applications then it will provide somde description or information about our application which is

usefull to manage our applications easily.

  • History: In general, all Logging Frameworks are tracing the applications flow of execution and

they are able to store tracing details in a file system, this logging details are usefull to analyze the

problems and to solve the problems.

  • Cost and Time Saving: Logging Frameworks will simplifies debugging, easy maintenance ,

persisting application information,..... , these qualities of Logging Framework saves time and cost

of the application.

Drawbacks with Logging Frameworks:

  • Logging Frameworks needs to write some extra code in our java applications, it will

increase overhead to the application.

  • Logging Frameworks will provide some extra code in our applications, it will increase

application execution time at runtime, it will reduce application performance.

  • Logging Framework will provide some extra code in application, so that, it will increase

application length.

  • Poor logging strategies will increase confusion to the developers.

Log4j

Log4J is a reliable, fast and flexible framework written in JAVA to perform logging in Java

applications and it is provided by Apache Software Foundations.

Example58
JCode Cell
1 
2Java provided java.util Logging
3Log4j
4LogBack
5Commons Logging
6ObjectGuy
7TinyLog
8
📝 Key Takeaways
  • Key ideas of Spring - Integration with Servlets explained simply
  • Ready-to-use code examples
  • Exam-style questions at the end