Sie sind auf Seite 1von 9

Java Servlets and Filters

Software Required:
JDK 1.7
NetBeans 8 with Tomcat 8
Java Servlets are server side components in Java that runs on Servlet Container enabled web server such as Tomcat,
Jetty, WebSphere etc.
Java Servlets are part of the Java Enterprise Edition (Java EE) and are used to develop dynamic web applications.
Servlet is a web component that is deployed on the server to create dynamic web page.

Environment Setup Open Netbeans IDE, Create a new Java Web Application

Provide Project Name as ServletsNfiltersProj and set runtime as following:

Add Click Finish Button


Netbeans creates web application with a page called index.html file
Creating Deployment Descriptor (web.xml)
RClick Web Pages New Other Web Standard Deployment Descriptor (web.xml) and Run the Project

Creating a Servlet
RClick Source Packages New Other Web Servlet
ClassName: MyServlet
Package: com.ynotss.web
ServletName: MyServlet
URL Pattern: /MyServlet
Remove the following Code in MyServlet.java file
@WebServlet(name = "MyServlet", urlPatterns = {"/MyServlet"})
Configure Servlet in web.xml file
<servlet>
<servlet-name>MyServlet</servlet-name>
<servlet-class>com.ynotss.web.MyServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>MyServlet</servlet-name>
<url-pattern>/FirstDemo</url-pattern>
</servlet-mapping>
Run the Servlet
http://localhost:8084/ServletsNfiltersProj/FirstDemo

Servlet Filters
A filter is an object that is invoked at the preprocessing and post processing of a request. It is pluggable, i.e. its entry is
defined in the web.xml file, if we remove the entry of filter from the web.xml file, filter will be removed automatically and we
don't need to change the servlet. So it will be easier to maintain the web application.
A servlet filter can intercept requests both for servlets, JSP's, HTML files or other static content, as illustrated in the
diagram below:

Usage of Filter
Recording all incoming requests, Logs the IP addresses of the computers from which the requests originate, Conversion
data compression, encryption and decryption, input validation etc.
Advantage of Filter: Filter is pluggable.
Filter API
Like servlet filter have its own API.The javax.servlet package contains the three interfaces of Filter API
Filter, FilterChain, FilterConfig
1) Filter interface
For creating any filter, you must implement the Filter interface. Filter interface provides the life cycle methods for a filter.
public void init(FilterConfig config): init() method is invoked only once it is used to initialize the filter.
public void doFilter(HttpServletRequest request,HttpServletResponse response, FilterChain chain): doFilter() method is
invoked every time when user request to any resource, to which the filter is mapped.It is used to perform filtering tasks.
public void destroy():This is invoked only once when filter is taken out of the service.
Creating a Filter
RClick Source Packages New Other Web Filter
FilterName: SimpleFilter

public class SimpleFilter implements Filter {


public SimpleFilter() {
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
String ipAddress = request.getRemoteAddr();
System.out.println("Do Filter");
System.out.println("IP "+ ipAddress + ", Time " + new Date().toString());
chain.doFilter(request, response);
}
public void destroy() {
System.out.println("Filter Destroy");
}
public void init(FilterConfig filterConfig) {
System.out.println("Filter Initial");
}
}
When the servlet filter is loaded the first time, its init() method is called, just like with servlets.
When a HTTP request arrives at your web application which the filter intercepts, the filter can inspect the request URI, the
request parameters and the request headers, and based on that decide if it wants to block or forward the request to the
target servlet, JSP etc.

Using MySQL
Connect MySQL with ROOT user
mysql> CREATE USER 'springuser'@'localhost' IDENTIFIED BY 'springuserpw';
Query OK, 0 rows affected (0.03 sec)
mysql> CREATE DATABASE ngspring;
Query OK, 1 row affected (0.00 sec)
mysql> GRANT ALL ON ngspring.* to springuser@localhost;
Query OK, 0 rows affected (0.03 sec)
Exit and connect with springuser
>mysql -u springuser -p
Enter password: ************
mysql> use ngspring;
Database changed
mysql> CREATE TABLE college(id int(5) primary key auto_increment, name varchar(50), code varchar(50));
Query OK, 0 rows affected (0.18 sec)
mysql> insert into college (name, code) values('MyCollege', 'MC001');

RESTful Web Services


Web services are distributed application components that are externally available.
Web services are language and platform independent because vendors have agreed on common web service standards.
Several programming models are available to web service developers.
These models fall into two categories:
SOAP/WSDL-based. In traditional web service models, web service interfaces are exposed through WSDL documents
(a type of XML), which have URLs. Subsequent message exchange is in SOAP, another type of XML document. For more
details, see SOAP-based Web Services.
REST-based. REpresentational State Transfer is a new way to create and communicate with web services. In REST,
resources have URIs and are manipulated through HTTP header operations.
REST-based ("RESTful") web services are collections of web resources identified by URIs. Every document and every
process is modeled as a web resource with a unique URI. Message exchange can be conducted in any formatXML,
JSON, HTML, etc. In many cases a web browser can serve as the client.
HTTP is the protocol in REST. Only four methods are available: GET, PUT, POST, and DELETE.

Spring MVC Framework


Spring is an Enterprise Application Framework. Version 4.0 is the latest major release of the Spring Framework and the
first to fully support Java 8 features. Spring framework consists of more than 20 modules grouped together. These are
largely categorized as Core Container, Data Access/Integration, Web, AOP (Aspect Oriented Programming),
Instrumentation, and Test.

Advantages of Spring MVC Framework


Supports RESTful URLs.
Annotation based configuration(i.e. you may reduce the metadata file or less of configuration).
Supports to plug with other MVC frameworks like Struts, Struts2, WebWorks etc.
Flexible in supporting different view types like JSP, velocity, XML, PDF, Tiles etc.
Spring MVC4 Project Setup
Create a new Java Web Project
Add Spring4 Libraries
Add Jackson-core-asl.1.9.11.jar, Jackson-mapper-asl.1.9.11.jar
Add mysqlconnector.jar file
Spring MVC4 Configuration (XML)
1. Create and Modify deployment descriptor as below:
<servlet>
<servlet-name>rest</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>rest</servlet-name>
<url-pattern>/api/*</url-pattern>
</servlet-mapping>
2. Spring Configuration File (rest-servlet.xml) in web-inf folder. RClick WebPages New Other Spring
Spring XML Configuration file, select context namespace.
3. Add mvc namespace by typing in rest-servlet.xml file
<?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:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context4.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
">
<context:component-scan base-package="com.ynotss.controller"/>
<mvc:annotation-driven/>

</beans>
With ComponentScan tag, Spring auto scans all elements in the provided base package and all its child packages for
Controller servlet. Also, we have used <mvc:annotation-driven> tag instead of ViewResolver, with which we can directly
send response data from the controller.
Creating a Model Class
package com.ynotss.model;
public class College {
private int id;
private String name;
private String code;
public College() {
}
public College(int id, String name, String code) {
this.id = id;
this.name = name;
this.code = code;
}
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 getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
}
Create a DAO Class
package com.ynotss.dao;
import com.ynotss.model.College;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
public class CollegeDao {
private Connection getConnection() {
Connection con = null;
try {
Class.forName("com.mysql.jdbc.Driver");

con = DriverManager.getConnection("jdbc:mysql://localhost/ngspring", "springuser", "springuserpw");


}catch(Exception e) {
System.out.println("Error..." + e);
}
return con;
}
public ArrayList<College> getAllColleges() throws Exception {
ArrayList<College> colleges = new ArrayList<College>();
Connection con = getConnection();
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM college");
while(rs.next()) {
College c = new College(rs.getInt("id"), rs.getString("name"), rs.getString("code"));
colleges.add(c);
}
return colleges;
}
}
Create a Controller Class
package com.ynotss.controller;
import com.ynotss.dao.CollegeDao;
import com.ynotss.model.College;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
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.annotation.RestController;
@RestController
@RequestMapping("/mycollege")
public class CollegeController {
@RequestMapping(method=RequestMethod.GET, value="/list", produces = "application/json")
public List<College> getAllColleges() {
List<College> colleges = null;
try {
CollegeDao clgdao = new CollegeDao();
colleges = clgdao.getAllColleges();
}catch(Exception e) {
colleges = new ArrayList<College>();
}
/*response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "x-requested-with");*/
return colleges;
}
}
One of the new features of API improvements is new @RestController annotation which is inherited from the @Controller
annotation.
Prior to the version 4.0, all the Spring MVC components has to use the common @Controller annotation to mark that as
the controller servlet. When you implement a RESTful web services, the response would be always sent with the
response body. To make this simple, Spring 4.0 has provided a specialized version of controller. Look at the definition of
the @RestController implementation.
@RequestMapping' annotation is used for defining incoming request urls for class and method levels.
Testing Web Service
Open Browser and Type: http://localhost:8084/SpringMySqlNg/api/mycollege/list

[{"id":1,"name":"MyCollege","code":"MC001"}]
Creating AngularJS Client
1. Setup Angular Environment. The complete Project Structure as below:

<!DOCTYPE html>
<html ng-app="MyApp">
<head>
<title>College Management</title>
<link rel="stylesheet" href="css/bootstrap.min.css"/>
<script src="js/angular.min.js"></script>
</head>
<body>
<h1>Spring College REST Example</h1>
<div ng-controller="CollegeController">
<table class="table table-bordered table-condensed">
<tr>
<th>College Name</th><th>Code</th><th>Action</th>
</tr>
<tr ng-repeat="college in colleges">
<td>{{college.name}}</td>
<td>{{college.code}}</td>
<td>
<a href="javascript:void(0)" ng-click="delete(college.id)">Delete</a></td>
</tr>
</table>
{{message}}
</div>
<script>
var myapp = angular.module("MyApp",[]);
myapp.controller('CollegeController', function($scope, $http){
$scope.message = "";
$http.get('api/mycollege/list').success(function(data) {
$scope.colleges = data;
$scope.message = "";
});
});
</script>
</body>

</html>
Consuming AngularJS client from other Domain
1. Create a CORS (Cross-Origin Resource Sharing) Filter
package com.ynotss.controller;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
public class SimpleCORSFilter implements Filter{
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest request, ServletResponse resp, FilterChain chain) throws IOException,
ServletException {
HttpServletResponse response=(HttpServletResponse) resp;
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "x-requested-with");
chain.doFilter(request, resp);
}
@Override
public void destroy() {
}
}
2. Configure Filter
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<servlet>
<servlet-name>rest</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>rest</servlet-name>
<url-pattern>/api/*</url-pattern>
</servlet-mapping>
<filter>
<filter-name>cors</filter-name>
<filter-class>com.ynotss.controller.SimpleCORSFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>cors</filter-name>
<url-pattern>/api/*</url-pattern>
</filter-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
</web-app>

Creating Generic Data Access Object and its Implementation


package com.ynotss.dao;
import java.io.Serializable;
import java.util.List;
public interface GenericDao<E, PK extends Serializable> {
E save(E newInstance);
E update(E transientObject);
E saveOrUpdate(E transientObject);
void delete(E persistentObject);
E findById(PK id);
List<E> findAll();
List<E> findAllByProperty(String propertyName, Object value);
}
GenericDaoImpl.java
public abstract class GenericDaoImpl<E, PK extends Serializable> implements GenericDao<E, PK> {
. All the Persistence Stuff ..
}
Using in Project
package com.ynotss.dao;
import java.util.List;
import com.ynotss.model.College;
public interface CollegeDao extends GenericDao<College, Integer> {
List<College> findActiveColleges();
}
Implementation
public class CollegeDaoImpl extends GenericDaoImpl<College, Integer> implements CollegeDao {
protected Class<College> getEntityClass() {
Class<College> result = College.class;
return result;
}
@SuppressWarnings("unchecked")
public List<College> findActiveColleges() {
try {
.. Code returns List of Colleges .
} catch (Exception e) {
e.printStackTrace();
throw e;
}
}
}

Das könnte Ihnen auch gefallen