Showing posts with label java struts. Show all posts
Showing posts with label java struts. Show all posts

February 09, 2017

Interceptors



Used to control a request
They are invoked by the controller (Filter Dispatcher)
Interceptors perform action such as
o Logging
o validation
o file upload
o double submit guard etc.

 How Interceptor works?
1. Request is generated by user and sent to Servlet container.
2. Servlet container invokes FilterDispatcher filter which in turn determines appropriate action.
3. One by one Intercetors are applied before calling the Action. Interceptors perform tasks such as Logging, Validation, File Upload, Double-submit guard etc.
4. Action is executed and the Result is generated by Action.
5. The output of Action is rendered in the view (JSP, Velocity, etc) and the result is returned to the user.

Explanation: -

1. Request is generated by user and sent to Servlet container http://localhost:8080/StrutsValidationEx/ - web.xml
2. Servlet container invokes FilterDispatcher filter which in turn determines appropriate action. Invoking filter Dispatcher (web.xml)

<filter>

<filter-name>Struts2</filter-name>

<filter-
class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>

</filter>

<filter-mapping>

<filter-name>Struts2</filter-name>

<url-pattern>/*</url-pattern>

</filter-mapping>


Determining Appropriate action (struts.xml) Welcome.jsp

index.jsp 

Configuring interceptor in struts: -
<interceptors>

<interceptor name="mylogging"

class="net.viralpatel.struts2.interceptor.MyLoggingInterceptor">

</interceptor>

<interceptor-stack name="loggingStack">



<interceptor-ref name="mylogging" />

<interceptor-ref name="defaultStack" />

</interceptor-stack>

</interceptors>



This code has to be added after <result-types > tag in <package>

</package>

Note that creation of interceptor stack with the name “logginstack” is to

make sure that struts2 calls all the default interceptors as well while calling

the custom interceptor mylogging.

This is important because the validation logic will not works in our

application if we ignore default stack of interceptor.



http://javabelazy.blogspot.in/

December 31, 2013

Struts application in java


Java struts login page application source code


This application is for beginner. copy paste the code to respective folder.  The application shows you how login  with struts work.

Login page

Login.jsp

Java struts login page application source code


<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%@ taglib prefix="s" uri="/struts-tags"%>
<html>
<head>

<title> Java struts web application source code </title>
</head>
<body>

<h2>Sample web application</h2>

<s:actionerror />

<s:form action="login.action" method="post">
    <s:textfield name="username" key="label.username" />
    <s:password name="password" key="label.password" />
    <s:submit method="execute" key="label.login" align="center" />
</s:form>

</body>
</html>

This jsp teach you how struts tag works

<%@ taglib prefix="s" uri="/struts-tags"%> adding a struts tag to jsp page

<s:form action="login.action" method="post">  as like form in html. once you submit the form the corresponding login action in struts.xml is called.

key="label.login" will be defined in application.properties

Welcome page.jsp   ( Second page)


<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title> struts JSP jquery application</title>
</head>
<body>
<h2> Welcome to java lazy blog, Java web application </h2>
</body>
</html>


Web.xml


<?xml version="1.0" encoding="UTF-8"?>

<web-app id="WebApp_9" version="2.4"
    xmlns="http://java.sun.com/xml/ns/j2ee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

   
    <display-name>Struts2 application</display-name>

    <filter>
        <filter-name>StrutsNew</filter-name>
        <filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
    </filter>

    <filter-mapping>
        <filter-name>StrutsNew</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <welcome-file-list>
        <welcome-file>Login.jsp</welcome-file>
    </welcome-file-list>

</web-app>

---

    <filter>
        <filter-name>StrutsNew</filter-name>
        <filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
    </filter>

    <filter-mapping>
        <filter-name>StrutsNew</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

Through this filter class in struts.xml we are re directing each every url [ <url-pattern>/*</url-pattern>]  through filterdispatcher <filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>



Jar file needed. you have to put this in lib folder






LoginAction.java inside src folder


package com.blazy.strutsSpringapplication;
/*
* Action class in struts
*/
public class LoginAction {
   
    private String username = null;
    private String password = null;
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
   
    public String execute()
    {
        if(username.equals("u") & (password.equals("p")))
           // code for validation
        {
            System.out.println(" Struts frame work example download "+username + password);
        return "success";
        }
        else
            return "error";
       
    }

}

--

public class LoginAction  implements ......

ApplicationResources.properties file inside resources folder


label.username = username
label.password = password
label.login = Login
error.login = Invalid user try again later



Struts.xml file  inside resource folder


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>

    <constant name="struts.enable.DynamicMethodInvocation" value="false" />
    <constant name="struts.devMode" value="false" />
    <constant name="struts.custom.i18n.resources" value="ApplicationResources" />

    <package name="default" extends="struts-default" namespace="/">
     <action name="login" class="com.org.strutsNew.LoginAction" converter="" method="save">
            <result name="success">Welcome.jsp</result>
            <result name="error">Login.jsp</result>
        </action>
     </package>
</struts>

we have created the login class above
<action name="login" class="com.org.strutsNew.LoginAction" converter="" method="save">

This is only a small program. please try this.

Wish you a Happy New year

+Deepu A.B.


Similar posts

  1. Java spring model view and controller - hello world example



https://javabelazy.blogspot.in

September 27, 2013

How to add css to struts2

 How to add css to struts2
Adding css file to struts

<%@ taglib uri="http://tiles.apache.org/tags-tiles" prefix="tiles"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title><tiles:insertAttribute name="title" ignore="true" /></title>
<link href="<s:url value ="/css/Theme.css"/>" rel="stylesheet" type="text/css"/>
</head>

August 09, 2012

ajax jquery call to servlet example

How to call a servlet using jquery ajax

Description : This is a small example to call servlet using ajax jquery. also shows servlet mapping in web.xml file (Deployment descriptor) .How to use external javascript file in java[ajax servlet Tutorial].








web.xml

<servlet>
    <description></description>
    <display-name>AjaxServlet</display-name>
    <servlet-name>AjaxServlet</servlet-name>
    <servlet-class>servlets.AjaxServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>AjaxServlet</servlet-name>
    <url-pattern>/AjaxServlet</url-pattern>
  </servlet-mapping>

 <welcome-file>index.jsp</welcome-file>


index.jsp

jquery api needed

<script type="text/javascript" src="jquery-1.3.2.js"></script>
<script type="text/javascript" src="myJquery.js"></script>
<script type="text/javascript" src="jquery-1.3.2.min.js"></script>

<div>
<input type="text" id="headText">
<input type="button" id="newButton" value="sendData">
</div>



servlet : AjaxServlet.java

public class AjaxServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
      
    /**
     * @see HttpServlet#HttpServlet()
     */
    public AjaxServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
           }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println(" inside do post "+request.getParameter("message"));
    }

}

jquery file : myjquery.js

$(document).ready(function(){
  $('#newButton').click(function(){
           sendData();
    });
   });
function sendData(){
   var mge = $('#newText').val();
    alert(mge);
    $.ajax({
        type: "POST",
        url: "AjaxServlet",
        data: { message : mge  }
      }).done(function( msg ) {
        alert( "Data Saved: " + msg );
      });
}

Description : The Example show how to call a servlet from jsp using ajax jquery. Data from jsp page will pass to servlet as parameter through ajax call


To receive response from the servlet, Change the code to following

In servlet

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws    ServletException, IOException {
        String message = request.getParameter("message");
         String respMess = message + "data saved ";
        response.setContentType("text/plain");
        response.setCharacterEncoding("UTF-8");
        response.getWriter().write(respMess);
    }

In jquey

The function sendData() will send data to post method of servlet "JqueryServlet". the data is taken from html tag whose id is " headText ". In the example i have created a text box named headtext in Index.jsp (java server page)

function sendData(){
    var mge = $('#headText').val();
   
    $.ajax({
          type: "POST",
          url: "JQueryServlets",
          data: { message : mge},
          success : function(data){
              alert('success'+data);
          }
        });
   
}



Thanking you for reading this post. Hope you will try the code...

Your feedback may help rest of the readers... so please, your valuable comments


Now take a look how cascading style sheet is applied in struts, that is a constant look and feel for all your web pages in your web application . >>> lazy java

Sunday Times 1 Bestseller New York Times 1 Bestseller the global bestseller - Origin is the latest Robert Langdon novel from the author of the Da Vinci Code. 'Fans will not be disappointed' the Times Robert Langdon, Harvard professor of symbology and religious iconology, arrives at the Guggenheim Museum Bilbao to attend the unveiling of an astonishing scientific breakthrough. The evening’s host is billionaire Edmond Kirsch, a futurist whose dazzling high-tech inventions and audacious predictions have made him a controversial figure around the world. But Langdon and several hundred guests are left reeling when the meticulously orchestrated evening is suddenly blown apart. There is a real danger that Kirsch’s precious discovery may be lost in the ensuing chaos. With his life under threat, Langdon is forced into a desperate bid to escape Bilbao, taking with him the museum’s director, Ambra Vidal. Together they flee to Barcelona on a perilous quest to locate a cryptic password that will unlock Kirsch’s secret. To evade a devious enemy who is one step ahead of them at every turn, Langdon and Vidal must navigate the labyrinthine passageways of extreme religion and hidden history. On a trail marked only by enigmatic symbols and elusive modern art, Langdon and Vidal will come face-to-face with a breathtaking truth that has remained buried – until now. ‘Dan Brown is the master of the intellectual cliffhanger’ Wall Street Journal ‘As engaging a hero as you could wish for’ Mail on Sunday ‘For anyone who wants more brain-food than thrillers normally provide’ Sunday Times

By Now Hurry- origin by dan brown


Author : +belazy

February 06, 2012

Example for POJO class

POJO Entity Class example


public class IPAddress {
   
    private int ipAddressId = 0;
    private String ipAddress = null;
    private String description = null;
   
    public int getIpAddressId() {
        return ipAddressId;
    }
    public void setIpAddressId(int ipAddressId) {
        this.ipAddressId = ipAddressId;
    }
    public String getIpAddress() {
        return ipAddress;
    }
    public void setIpAddress(String ipAddress) {
        this.ipAddress = ipAddress;
    }
    public String getDescription() {
        return description;
    }
    public void setDescription(String description) {
        this.description = description;
    }
   

}

Facebook comments