Tuesday, 17 September 2013

How to call JSP page from Flex.

Here we take example of real time applications:How Forgot password.Link is send to User E-mail ID.

1)How to send JSP page link to the user E-mail id.
2)Validation of JSP page using jquery.
3)Saving user password successfully in MySQL database using hibernate.

Create a JSP page which we want to use to reset password.
Validation is also done for textinput fields.
When click on submit button it will go to web.xml and check for servlet class.
resetpassword.jsp:

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

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<link type="text/css" rel="stylesheet" href="/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script type="text/javascript">

var id = '<%= request.getParameter("id") %>';

//validation of fields
function resetPassword(){
 var password =  document.getElementById("password").value;
 var confirmpassword = document.getElementById("confirmpassword").value;
 if(password==""){
  alert("Password should not be Empty");
  return false;
 }else if(confirmpassword==""){
  alert("Confirm password should not empty");
  return false;
 }else if(password.length<8 && confirmpassword.length<8){
 alert("Please enter minimum 8 characters.");
  return false;
 }
 else if(password != confirmpassword){
  alert("Password and Confirm password should match.");
  return false;
 }
 var data1 = "id="+id+"&password="+password;
// ajax call 
   $.ajax({
      url: "resetpassword.html",
      type: "GET",
      data: data1,
      success: function(){
          alert("Password submitted successfully");
           $("#result").html('submitted successfully');
     $("#tab").hide();
     //if success urll will be directed  
     window.location="http://localhost:8400/Sample/Sample.html";
     
      },
      error:function(){
          alert("failure");
          $("#result").html('there is error while submit');
    
      }   
    }); 
}


 function AvoidSpace(evt) { 

                        if (evt.charCode == 32) { 
                             //   event.returnValue = false;

                                return false; 
                        } 
                } 

</script>
<title>forgotpassword</title>
<style>
.error {
color: #ff0000;
}
body
{

right:100px;
width:1065px;

}
.style1 
{ 
width: 45%; 
top: 217px; 
left: 418px; 
height: 15px; 
}
.div1{
 width:600px;height:400px;margin:80px 0px 0px 350px;
background-color: #3B6331;border-radius:5px;
}
.logindiv{
text-align:center;padding-top:20px;color:#ADDAA2;font-size: 30px;
 font-weight: bolder;
}
</style>
</head>
<body >
<div>
<form id="tab">
<div  class="div1">
<div class="logindiv">Reset Password</div>
<table style="padding-left:166px;padding-top:122px;padding-bottom: 25px;" >
<tr>
<td style="font-size: medium;color:#ADDAA2;"  style="font-family:verdana;
   font-size:11px;">Password:</td>
<td ><input type="password" name="password" onkeypress="return AvoidSpace(event)" 
      id="password"  /></td>
</tr>
<tr>
<td style="font-size: medium;color:#ADDAA2;"  style="font-family:verdana;
    font-size:11px;">Confirm Password:</td>
<td ><input type="password" name="confirmpassword" 
      onkeypress="return AvoidSpace(event)"  id="confirmpassword"/></td>
</tr>
</table>
<div style= "font-size: medium;color: #ADDAA2;padding-left: 300px;">
<input type ="button" style= "font-weight: bold;" value="Submit" 
     onclick="resetPassword()"/></div>
</div>
</form>
</div>
</body>
</html>
 
 Jsp page looks like:

Need to mention location of jsp in server.
application.properties:

password.url = http://localhost:8400/Sample/resetpassword

Constants.java: 
package com.tb.module.service; import java.io.FileInputStream; import java.io.IOException; import java.util.Properties; public class Constants {
 public static final String host = "smtp.gmail.com";
 public static final String username="alekhya@gmail.com";
 public static final String password="alekhya";
 public static final String from="alekhya@gmail.com";
public static final String jsp=getResetPasswordLink(); public static String getResetPasswordLink(){ try { Properties prop = new Properties(); //load a properties file prop.load(Constants.class.getClassLoader()
            .getResourceAsStream("application.properties"));
               //get the property value and print it out
             return prop.getProperty("password.url");
     } catch (IOException ex) {
      ex.printStackTrace();
      return null;
        }
  
 }
 
}

When user enters E-mail id to send the resetpassword link we need to direct to this class
Here we search in database for email id.
Please go to link for EmailService ,EmailVO classes 
http://alekhya07.blogspot.in/2013/09/javamail-api-sending-email-via-gmail.html 
We configure E-mail using above classes and append resetpassword URL with userid of user who want to change the password mail the url to them.
 
ForgotPasswordService.java:

package com.module.service;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

import com.session.BaseHibernateDAO;
import com.tb.vo.Users;

import email.EmailService;
import email.EmailVO;

public class ForgotPasswordService extends BaseHibernateDAO {
public Boolean forgotPassword(String eid){
 Transaction tx=null;
 Session session=getSession();
 Boolean b=false;
 try {
  EmailService emailService=new EmailService();
  session.beginTransaction();
  String s="from Users where emailId=:id";
  Query query=session.createQuery(s).setString("id", eid);
  List<Users> s2=query.list();
  System.out.println("length of s2"+s2.size());
  if(s2.size()>0){
   EmailVO emailVO=new EmailVO();
         emailVO.setTo(eid);
         emailVO.setSubject("Change Password Link");
         emailVO.setFrom(Constants.from);
         StringBuffer content = new StringBuffer();
         content.append("Dear "+s2.get(0).getFirstName()+"" 
                         +s2.get(0).getLastName()+","+"\n\n");
         content.append("To change your password, please click the below link," 
                         +"\n"+Constants.jsp+"?id="+s2.get(0).getUserId()+"\n\n");
         content.append("Thanks & Regards"+"\n");
         content.append("Alekhya");
         emailVO.setContent(content.toString());
         emailService.sendEmail(emailVO);
         b=true;
  }
     
 }catch (Exception e) {
   e.printStackTrace();
 }
 return b;
}
}

Configuring the java class for reserpassword.html.
web.xml:
<servlet>
        <servlet-name>login1</servlet-name>
        <servlet-class>com.module.service.ServletForgotPswd</servlet-class>
    </servlet>
 <servlet-mapping>
  <servlet-name>login1</servlet-name>
  <url-pattern>/resetpassword.html</url-pattern>
 </servlet-mapping>
 
When user clicks on submit button in jsp page it will redirect to 
this java method.Password is updated in database by encrypting. 
ServletForgotPswd.java:
 
package com.tb.module.service;
import java.io.*;
import java.util.List;

import javax.servlet.*;
import javax.servlet.http.*;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hsqldb.User;

import com.module.dao.PswdEnc;

public class ServletForgotPswd extends HttpServlet {

 

 // Extend HttpServlet class 
   private String message="hello";
     // private boolean isSuccess;
      String id;
      String password;
   public void doGet(HttpServletRequest request,
                     HttpServletResponse response)
             throws ServletException, IOException
   {
       // Set response content type
       response.setContentType("text/html");
       // Actual logic goes here.
       PrintWriter out = response.getWriter();
       out.println("<h1>" + message + "</h1>");
      id=request.getParameter("id");
      password= request.getParameter("password");
      // response.getWriter().write("{isSuccess: true}");
       update(password, id);
       }
//   id=24;
//   String link=Constants.jsp+"?id="+id;
//   
 public Boolean update(String pwd,String id){
  
  
  try{
   Configuration con=new Configuration();
   con.configure();
   SessionFactory sf=con.buildSessionFactory();
   Session session=sf.openSession();
   Transaction t=session.beginTransaction();
   String s="update Users set password=:p where userId=:u"
// for encrption of password
//  http://alekhya07.blogspot.in/2013/08/encrypt-and-decrypt-password-in-java.html
  String encryptpassword = PswdEnc.encrypt(pwd);
   System.out.println("Encrypted Password : "+encryptpassword);
   Query query=session.createQuery(s)
                        .setParameter("p",encryptpassword)
                        .setParameter("u",Long.parseLong(id));
      query.executeUpdate();
      t.commit();
  }catch (Exception e) {
   
   e.printStackTrace();
  }return true;
}
 public static void main(String[] args) {
  ServletForgotPswd p=new ServletForgotPswd();
  p.update("alekhya", "92");
 }
}
 

No comments: