Beruflich Dokumente
Kultur Dokumente
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
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
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');
</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");
[{"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>