JAVA SERVLET Server-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 public void forward(servletrequest request,servletresponse response) throws ServletException,java.io.IOException Include: can also be used to include the content of another resource public void include(servletrequest request,servletresponse response) throws ServletException,java.io.IOException RequestDispatcher rd=request.getrequestdispatcher( Myservlet"); rd.forward(request, response); 3
REQUESTDISPATCHER SRC: https://www.javatpoint.com/requestdispatcher-in-servlet 4
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 public void sendredirect(string URL)throws IOException; response.sendredirect("http://www.google.com"); 6
SENDREDIRECT forward() method It works at server side. It sends the same request and response objects to another servlet. It can work within the server only. Request method sendredirect() method It works at client side. It always sends a new request. It can be used within and outside the server. Response method 7
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 ServletConfig config=getservletconfig(); 8
SERVLETCONFIG public String getinitparameter(string name) public Enumeration getinitparameternames() public String getservletname() public ServletContext getservletcontext() 9
SERVLETCONFIG Defining init Paramters @WebServlet( urlpatterns = "/ParameterServlet", initparams = { @WebInitParam(name = "email", value = abc@xyz.com"), @WebInitParam(name = "phone", value = 5555555555") ) Accessing init Parameters private String email, phone; @Override public void init(servletconfig config) throws ServletException { email = config.getinitparameter("email"); phone = config.getinitparameter("phone"); 10
SERVLETCONFIG Web.xml <web-app> <servlet>... <servlet-name>parameterservlet</servlet-name> <servlet-class> myservlet.parameterservlet</servlet-class> <init-param> <param-name>email</param-name> <param-value>abc@xyz.com</param-value> </init-param>... </servlet> </web-app> 11
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 ServletContext application=getservletcontext(); 12
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 private String email, phone; @Override public void init(servletconfig config) throws ServletException { ServletContext ctx = config.getservletcontext(); email = ctx.getinitparameter("email"); phone = ctx.getinitparameter("phone"); 14
SERVLETCONTEXT Web.xml <web-app> <context-param> <param-name>email</param-name> <param-value>abc@xyz.com</param-value> </context-param> <context-param> <param-name>phone</param-name> <param-value>555555555</param-value> </context-param> <servlet>...... </servlet> </web-app> 15
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>"); 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); for (int i = 1; i <= columncount; i++) { out.print("<th>" + rsmd.getcolumnname(i)); finally { out.println("</body></html>"); 29 out.println(); out.close();
REFERENCES https://docs.oracle.com/javaee/7/jeett.pdf https://www.javatpoint.com/servlet-tutorial 30
THANK YOU 31 SRC: https://tunza.eco-generation.org/resourcesview.jsp?boardid=worldreport&viewid=13336