Wednesday, March 9, 2011

Login and Logout in struts2

learn java




login.jsp
<%@ taglib prefix="s" uri="/struts-tags" %>
<%@ page language="java" contentType="text/html"%>

<html>
    <head>
        <title>Insert Data here!</title>
     <link href="<s:url value="/css/main.css"/>" rel="stylesheet"
          type="text/css"/>
  </head>
    <body>
  <s:form action="loginAction1" >
      <s:textfield name="userId" label="Login Id"/><br>
      <s:password name="password" label="Password"/><br>
         <s:submit value="Login" align="center"/>
    </s:form>
  </body>
</html>

loginAction1
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package vaannila;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ActionContext;
import java.util.*;

public class loginAction1 extends ActionSupport {

    private String userId;
    private String password;

    @Override
    public String execute() throws Exception {

        if ("admin".equals(userId) && "admin".equals(password)) {
            Map session = ActionContext.getContext().getSession();
            session.put("logged-in", "true");
            return SUCCESS;
        } else {
            return ERROR;
        }
    }

    public String logout() throws Exception {

        Map session = ActionContext.getContext().getSession();
        session.remove("logged-in");
        return SUCCESS;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getUserId() {
        return userId;
    }

    public void setUserId(String userId) {
        this.userId = userId;
    }
}


struts.xml
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>
    <include file="example.xml"/>
    <!-- Configuration for the default package. -->
    <package name="default" extends="struts-default">
        <action name="loginAction1" class="vaannila.loginAction1" >      
        <result name="success" type="dispatcher">/success2.jsp</result>
       <result name="error" type="redirect">/login.jsp</result>
</action>

<action name="logoutAction" class="vaannila.logoutAction" >
       <result name="success" type="redirect">checkLogin.jsp</result>
</action>

    </package>
</struts>


success2.jsp
<%@ taglib prefix="s" uri="/struts-tags" %>
<%@ page language="java" contentType="text/html" import="java.util.*"%>
<html>
    <head>
        <title>Welcome, you have logined!</title>
  </head>
    <body>
    Welcome, you have logined. <br />
    <b>Session Time: </b><%=new Date(session.getLastAccessedTime())%>
      <br /><br />
      <a href="<%= request.getContextPath() %>/vaannila/logoutAction">Logout</a>
      <br />
    </body>
</html>

logoutAction.java
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package vaannila;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ActionContext;
import java.util.*;

public class logoutAction extends ActionSupport {
    @Override
  public String execute() throws Exception {
    Map session = ActionContext.getContext().getSession();
    session.remove("logged-in");
    return SUCCESS;
    }
}

after logoutAction it wil go to struts.xml and then to

checkLogin.jsp
<%@ taglib prefix="s" uri="/struts-tags" %>
<%@ page language="java" contentType="text/html" import="java.util.*"%>
<html>
    <head>
        <title>Check validate!</title>
  </head>
    <body>
      <s:if test="#session.login != 'admin'">
      <jsp:forward page="login.jsp" />
      </s:if>
    </body>
</html> 


output











starting struts2.0

learn java
index.jsp

<%@taglib uri="/struts-tags" prefix="s" %>
<html>
<head>
<title>Hello World</title>
</head>
<body>
    <s:form action="HelloWorld1" >
        <s:textfield name="userName" label="User Name" />
        <s:submit />
    </s:form>
</body>
</html>

helloworld.java
package vaannila;
public class HelloWorld1 {
private String message;
private String userName;


    public String execute() {
        setMessage("Hello " + getUserName());
        return "SUCCESS";
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
}
}



success.jsp
<%@taglib uri="/struts-tags" prefix="s" %>
<html>
<head>
<title>Hello World</title>
</head>
<body>
    <h1><s:property value="message" /></h1>
</body>
</html>

struts.xml
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>
    <include file="example.xml"/>
    <!-- Configuration for the default package. -->
    <package name="default" extends="struts-default">
        <action name="HelloWorld1" class="vaannila.HelloWorld1">
            <result name="SUCCESS">/success.jsp</result>
       </action>
    </package>
</struts>


output

Thursday, March 3, 2011

Cookie Example

learn java

index.jsp
 <body>
        <h1>Hello World!</h1>
        <% Cookie cookie = new Cookie ("testcookie","Visualbuilder");
        cookie.setMaxAge(60);
        response.addCookie(cookie);
        response.sendRedirect("getcookie.jsp");
         %>
  </body>  
    



getcookie.jsp
   <body>
<%
   Cookie[] cookies= request.getCookies();
   for(int i=0;i<cookies.length;i++){
   if(cookies[i].getName().equalsIgnoreCase("testcookie")){
          out.println("Cookie Value is "+ cookies[i].getValue());
      }
   }
%>
    </body>

  

Cookie

learn java

Cookie
In JSP cookie are the object of the class javax.servlet.http.Cookie.
The Http protocol is a stateless protocol means that it can't keep a state
i.e. it can't persist values. To maintain a session we used the concept of cookies.
"A token is generated which contains user's information,
By this cookie, the server is able to identify the user."

Cookie is nothing but a name- value pair, which is stored on the client machine.
The cookies are saved to clients hard disk in the form of small text file.
Cookies helps the web servers to identify web users, by this way server tracks the user.
Cookies pay very important role in the session tracking.

Two types of cookies.
1) Non- secure session cookie:
This cookie can flow between the browser and server under the SSL or non- SSL connection.

2) Secure authentication cookie:
It is used to authenticate the data. This cookie flow over SSL.
This type of authenication cookie are used where the information security is very important. 


getComment()
Returns the comment describing the purpose of this cookie.

getMaxAge()

Returns the maximum specified age of the cookie.

getName()

Returns the name of the cookie.

getPath()
Returns the prefix of all URLs for which this cookie is targeted

getValue()

Returns the value of the cookie.

setMaxAge(int)
Sets the maximum age of the cookie.

setPath(String)
This cookie should be presented only with requests beginning with this URL.

setValue(String)
Sets the value of the cookie.

Response Object

learn java
The response object is an instance of a class that implements the javax.servlet.http.HttpServletResponseT
interface.
The response object denotes the HTTP Response data.
The result or the information of a request is denoted with this object.
The response object handles the output of the client.
The response object is generally used by cookies.

The response object is also used with HTTP Headers.

Methods of response Object:
There are numerous methods available for response object. Some of them are:

    setContentType()
    addCookie(Cookie cookie)
    addHeader(String name, String value)
    containsHeader(String name)
    setHeader(String name, String value)
    sendRedirect(String)
    sendError(int status_code)

setContentType()
setContentType() method of response object is used to set the MIME type and character encoding for the page.
response.setContentType("text/html");

addCookie(Cookie cookie):

addCookie() method of response object is used to add the specified cookie to the response.
For example:
response.addCookie(Cookie exforsys);

addHeader(String name, String value):
addHeader() method of response object is used to write the header as a pair of name and value to the response.
If the header is already present, then value is added to the existing header values.
For example:
response.addHeader("Author", "Exforsys");

The output of above statement is as below:
Author: Exforsys

containsHeader(String name):
containsHeader() method of response object is used to check whether the response already includes the header given as parameter.
If the named response header is set then it returns a true value.response.containsHeader(String name)

setHeader(String name, String value):
setHeader method of response object is used to create an HTTP Header with the name and value given as string.
If the header is already present, then the original value is replaced by the current value.
For example:
response.setHeader("Content_Type","text/html");

The above statement would give output as
Content_Type: text/html

sendRedirect(String):

sendRedirect method of response object is used to send a redirect response to the client temporarily by making use of redirect location URL given in parameter. But one must note that if the JSP executing has already sent page content to the client, then the sendRedirect() method of response object will not work and will fail.response.sendRedirect(String)

Implicit Object

These objects are defined as implicit because you do not have to explicitly declare them.
Because implicit objects are declared automatically we need only use the reference
variable associated with a given object to begin calling methods on it.
JSP container will create these objects automatically and
the container makes them available to the developers.
The implicit objects are parsed by the container and
inserted into the generated servlet code. 

1.request

2.response

3.page

4.application

5.session

6.pagecontext

7.exception

8.out

9.config

Ex: request.getElementById("xyz");

here you are using 'request' object without instantiating it because this object
is readily available for you.

Example:
If i want to put my username in the session in JSP.
JSP Page:
<%
String name=request.getParameter("Username");
session.setAttribute("UserName",name);
%>

<%=request.getRequestURI()%>

Wednesday, March 2, 2011

Learn JSP


Example for displaying content from other jsp page.

index.jsp

<body>
        <h1>Hello World!</h1>
        <%=request.getRequestURI()%>
        <%=request.getProtocol()%>          
            <%request.setAttribute("information","This is information passed from outer page");%>
             <jsp:include page="success.jsp"/>      
  </body>  
success.jsp     
   <body>
        <h1>Hello World!</h1>
                <%=request.getAttribute("information")%>
    </body>


  


java-8-streams-map-examples

package com.mkyong.java8; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Arrays; import java.util.List; im...