Java Servlet - WordPress.com · 3/8/2018 · EVENT AND LISTENER public class First extends...
Transcript of Java Servlet - WordPress.com · 3/8/2018 · EVENT AND LISTENER public class First extends...
JAVA SERVLETServer-side Programming
ADVANCED FEATURES
1
AGENDA
RequestDispacher
SendRedirect
ServletConfig
ServletContext
ServletFilter
SingleThreadedModel
Events and Listeners
Servlets & Database
2
REQUESTDISPATCHER
Forward: facility of dispatching the request to another resource
Include: can also be used to include the content of another
resource
3
public void forward(ServletRequest request,ServletResponse response) throws ServletException,java.io.IOException
public void include(ServletRequest request,ServletResponse response) throws ServletException,java.io.IOException
RequestDispatcher rd=request.getRequestDispatcher(“Myservlet");
rd.forward(request, response);
REQUESTDISPATCHER
4SRC: https://www.javatpoint.com/requestdispatcher-in-servlet
REQUESTDISPATCHER
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String userName=request.getParameter("userName");
String password=request.getParameter(“password");
if(userName.equals(“abc") && password.equals(“xyz") {
RequestDispatcher rd=request.getRequestDispatcher(“LoginSuccessServlet");
rd.forward(request, response); }
else{
out.print(“Sorry User Name or Password Error!");
RequestDispatcher rd=request.getRequestDispatcher("/index.html");
rd.include(request, response);
}
}
5
SENDREDIRECT
Method of HttpServletResponse interface
6
public void sendRedirect(String URL)throws IOException;
response.sendRedirect("http://www.google.com");
SENDREDIRECT
7
forward() method sendRedirect() method
It works at server side. It works at client side.
It sends the same request and
response objects to another
servlet.
It always sends a new request.
It can work within the server only. It can be used within and outsidethe server.
Request method Response method
SERVLETCONFIG
An object of ServletConfig is created by the web container for
each servlet.
This object can be used to get configuration information from
Annotation
web.xml file
Server interface/tool
Don't need to change the servlet
8ServletConfig config=getServletConfig();
SERVLETCONFIG
public String getInitParameter(String name)
public Enumeration getInitParameterNames()
public String getServletName()
public ServletContext getServletContext()
9
SERVLETCONFIG
Defining init Paramters
Accessing init Parameters
10
@WebServlet(urlPatterns = "/ParameterServlet",
initParams = {
@WebInitParam(name = "email", value = [email protected]"),
@WebInitParam(name = "phone", value = “5555555555")})
private String email, phone;
@Override
public void init(ServletConfig config) throws ServletException {
email = config.getInitParameter("email");
phone = config.getInitParameter("phone");}
SERVLETCONFIG
Web.xml
11
<web-app>
<servlet>
......
<servlet-name>ParameterServlet</servlet-name>
<servlet-class> myservlet.ParameterServlet</servlet-class>
<init-param><param-name>email</param-name>
<param-value>[email protected]</param-value>
</init-param>......
</servlet>
</web-app>
SERVLETCONTEXT
Created by the web container at time of deploying the project.
Only one ServletContext object per web application.
This object can be used to get configuration information from
Annotation
web.xml file
Server interface/tool
Don't need to change the servlet
12ServletContext application=getServletContext();
SERVLETCONTEXT
public String getInitParameter(String name)
public Enumeration getInitParameterNames()
public void setAttribute(String name,Object object)
public Object getAttribute(String name)
public void removeAttribute(String name)
13
SERVLETCONTEXT
Accessing init Parameters
14
private String email, phone;
@Override
public void init(ServletConfig config) throws ServletException {ServletContext ctx = config.getServletContext();
email = ctx.getInitParameter("email");
phone = ctx.getInitParameter("phone"); }
SERVLETCONTEXT
Web.xml
15
<web-app>
<context-param>
<param-name>email</param-name>
<param-value>[email protected]</param-value>
</context-param>
<context-param>
<param-name>phone</param-name>
<param-value>555555555</param-value>
</context-param>
<servlet>
......
......
</servlet>
</web-app>
FILTER
A filter is an object that can transform the header and content
(or both) of a request or response.
Authentication Filters.
Data compression Filters.
Encryption Filters.
16
FILTER
void init(FilterConfig config) throws ServletException
void destroy()
void doFilter(ServletRequest req, ServletResponse res, FilterChain
chain) throws IOException, ServletException
17
FILTER
public class LoginFilter implements Filter {public void init(FilterConfig config) throws ServletException {
}
public void doFilter(ServletRequest request, ServletResponse response,FilterChain chain) throws java.io.IOException, ServletException {
String password=req.getParameter("password"); if(password.equals("admin")){ chain.doFilter(req, resp);//sends request to next resource } else{
out.print("username or password error!"); RequestDispatcher rd=req.getRequestDispatcher("index.html"); rd.include(req, resp); } public void destroy( ) {
}} 18
FILTER
<filter>
<filter-name>LoginFilter</filter-name>
<filter-class>LoginFilter</filter-class>
<init-param>
<param-name>test-param</param-name>
<param-value>Initialization Paramter</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>LoginFilter</filter-name>
<url-pattern>/MyServlet</url-pattern>
</filter-mapping>
19
SINGLETHREADMODEL
Marker Interface
Ensures that servlets handle only one request at a time.
you are guaranteed that no two threads will execute
concurrently in the servlet's service method.
20
EVENT AND LISTENER
The servlet specification includes the capability to track key
events in your Web applications through event listeners.
Three levels of servlet events
Servlet context level
Session level
Request level
Each of these two levels has two event categories:
Lifecycle changes
Attribute changes
21
EVENT AND LISTENER
ServletRequestListener
ServletRequestAttributeListener
ServletContextListener
ServletContextAttributeListener
HttpSessionListener
HttpSessionAttributeListener
22
EVENT AND LISTENER
Listener that tracks the number of concurrent users
HttpSessionListener interface
void sessionCreated(HttpSessionEvent evt)
void sessionDestroyed(HttpSessionEvent evt)
23
EVENT AND LISTENER
public class CountUserListener implements HttpSessionListener{
ServletContext ctx=null;
static int total=0,current=0;
public void sessionCreated(HttpSessionEvent e) {
total++;
current++;
ctx=e.getSession().getServletContext();
ctx.setAttribute("totalusers", total);
ctx.setAttribute("currentusers", current);
}
public void sessionDestroyed(HttpSessionEvent e) {
current--;
ctx.setAttribute("currentusers",current);
}
}24
EVENT AND LISTENER
public class First extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("username");
out.print("Welcome "+n);
HttpSession session=request.getSession();
session.setAttribute("uname",n);
ServletContext ctx=getServletContext();
int t=(Integer)ctx.getAttribute("totalusers");
int c=(Integer)ctx.getAttribute("currentusers");
out.print("<br>total users= "+t);
out.print("<br>current users= "+c);
out.print("<br><a href='logout'>logout</a>");
out.close();
}
}
25
EVENT AND LISTENER
public class LogoutServlet extends HttpServlet {public void doGet(HttpServletRequest request, HttpServletResponse
response)throws ServletException, IOException {
response.setContentType("text/html");PrintWriter out = response.getWriter();
HttpSession session=request.getSession(false);session.invalidate();
out.print("You are successfully logged out");
out.close();}
}26
EVENT AND LISTENER
<web-app version="2.5" >
<listener>
<listener-class>CountUserListener</listener-class>
</listener>
<servlet>
<servlet-name>First</servlet-name>
<servlet-class>First</servlet-class>
</servlet>
<servlet>
<servlet-name>LogoutServlet</servlet-name>
<servlet-class>LogoutServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>First</servlet-name>
<url-pattern>/First</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>LogoutServlet</servlet-name>
<url-pattern>/logout</url-pattern>
</servlet-mapping>
</web-app>
27
EVENT AND LISTENER
<form action=“First">
Name:<input type="text" name="username"><br>
Password:<input type="password" name="userpass"><br>
<input type="submit" value="login"/>
</form>
28
SERVLETS - DATABASE ACCESS
PrintWriter out = response.getWriter();
try {
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/students";
String username = "root";
String password = "password";
String query = "select * from mtcse";
Class.forName(driver);
Connection con = DriverManager.getConnection(url, username,
password);
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
out.println("<TABLE BORDER=1>");
ResultSetMetaData rsmd = rs.getMetaData();
int columnCount = rsmd.getColumnCount();
out.println("<TR>");
for (int i = 1; i <= columnCount; i++) {
out.print("<TH>" + rsmd.getColumnName(i));
}
out.println();29
while (rs.next()) {
out.println("<TR>");
for (int i = 1; i <= columnCount; i++) {
if (rsmd.getColumnType(i) == java.sql.Types.INTEGER) {
out.print("<TD>" + rs.getInt(i));
} else {
out.print("<TD>" + rs.getString(i));
}
}
out.println();
}
out.println("</TABLE>");
} catch (ClassNotFoundException cnfe) {
out.println("Error loading driver: " + cnfe);
} catch (SQLException sqle) {
out.println("Error connecting: " + sqle);
} catch (Exception ex) {
out.println("Error with input: " + ex);
} finally {
out.println("</BODY></HTML>");
out.close();
}
REFERENCES
https://docs.oracle.com/javaee/7/JEETT.pdf
https://www.javatpoint.com/servlet-tutorial
30
THANK YOU
31SRC: https://tunza.eco-generation.org/resourcesView.jsp?boardID=worldReport&viewID=13336