Vaadin框架學習(login DEMO)

来源:互联网 发布:python字符串截取 编辑:程序博客网 时间:2024/06/10 11:36
 

vaadin是一個基於組件(Component)的表現層框架,具體的編程風格和CS很像,採取事件觸發式編程(event-listener)。所有的客戶端請求被vaadin框架內的ApplicationServlet捕獲,找到對應的application實例,然後通過GoogleToolKit轉化成普通HTML。所有的操作都在服務器端完成,包括js。vaadin的界面風格比較美觀,由於所有代碼都由java寫成,對平台的顧慮較少,可以用於移動和web應用,但是對服務器端要求較高。
下面是簡單的login demo,步驟4、5可以跳過自行實現驗證方式:
1、首先需要在web.xml加入vaadin的核心servlet:
 <!--可有可無的配置,如果是正式發布建議設為true,開發環境設為false-->
 <context-param>
  <description>
  Vaadin production mode</description>
  <param-name>productionMode</param-name>
  <param-value>false</param-value>
 </context-param>
 <!--vaadin的核心servlet,如有需要可複寫-->
 <servlet>
  <servlet-name>Vaadinui Application</servlet-name>
  <servlet-class>com.vaadin.terminal.gwt.server.ApplicationServlet</servlet-class>
  <!-- 默認vaadin的web應用首頁,取代welcome-file-list,這裡是demo裡面用到的類-->
  <init-param>
   <description>Vaadin application class to start</description>
   <param-name>application</param-name>
   <param-value>com.arlen.ui.applications.VaadinTrialApplication</param-value>
  </init-param>
 </servlet>
 <!--路徑映射,需要就改-->
 <servlet-mapping>
  <servlet-name>Vaadinui Application</servlet-name>
  <url-pattern>/*</url-pattern>
 </servlet-mapping>
2、編寫application類,繼承Application:
import com.arlen.ui.component.windows.*;
import com.vaadin.Application;

public class VaadinTrialApplication extends Application {
 /**
  *
  */
 private static final long serialVersionUID = 1654864768764L;

 @Override
 public void init() {
  LoginWindow lw = new LoginWindow();
  this.setMainWindow(lw);
 }

}
3、Window是最基礎的組件,所有組件都需要附著在window上,編寫LoginWindow類:
import java.sql.SQLException;
import static com.vaadin.ui.Window.Notification.TYPE_ERROR_MESSAGE;
import com.arlen.dbUtil.DataOp;
import com.vaadin.ui.Button;
import com.vaadin.ui.FormLayout;
import com.vaadin.ui.PasswordField;
import com.vaadin.ui.TextField;
import com.vaadin.ui.Window;
import com.vaadin.ui.Button.ClickEvent;

public class LoginWindow extends Window {
 private static final long serialVersionUID = 1L;
 private TextField loginField;
 private PasswordField passwordField;
 private Button submitButton;
 public LoginWindow() {
  loginField = new TextField("Login", "jack");
  passwordField = new PasswordField("Password");
  submitButton = new Button("Submit");
  submitButton.addListener(ClickEvent.class, this, "authenticate");
  setCaption("Twaattin Login");
  FormLayout formLayout = new FormLayout();
  formLayout.setMargin(true);
  formLayout.addComponent(loginField);
  formLayout.addComponent(passwordField);
  formLayout.addComponent(submitButton);
  addComponent(formLayout);
 }
 public void authenticate(ClickEvent event) {
  String login = (String) loginField.getValue();
  String psw = (String) passwordField.getValue();
  boolean isValid=false;
  DataOp op = null;
  try {
   op=new DataOp();
   //簡單的驗證(通過數據庫SQLServer)
   isValid=op.retrieveRowNum("UUM_USER", "user_psw='"+psw+"' and user_ID='"+login+"'")==0?false:true;
  } catch (SQLException e) {
   e.printStackTrace();
  }
  finally{
   if(op!=null){
    op.close();
   }
   if(isValid){
    this.showNotification("Welcome back!"+login+" ,you will be redirected...");
    //這裡可以跳轉,比如定義一個跳轉的頁面為SearchWindow,用戶驗證通過後就可以跳轉,這裡不再列SearchWindow代碼
    this.getApplication().setMainWindow(new SearchWindow());
    this.getApplication().removeWindow(this);
   }
   else{
    showNotification("Login failed,please try again!",TYPE_ERROR_MESSAGE);
   }
  }
 }
}
4、簡單的數據庫連接類DataOp,通過tomcat取得datasource。
4、1 tomcat的context中需要加入,定義數據源:
  <Resource name="jdbc/webframe" auth="Container" type="javax.sql.DataSource"
               maxActive="100" maxIdle="30" maxWait="10000"
               username="sa" password="lz@12358" driverClassName="com.microsoft.sqlserver.jdbc.SQLServerDriver"
               url="jdbc:sqlserver://localhost:1433;database=arlen"/>

4、2 web.xml加入,加入數據源:
 <resource-ref>
  <description>DB Connection</description>
  <res-ref-name>jdbc/webframe</res-ref-name>
  <res-type>javax.sql.DataSource</res-type>
  <res-auth>Container</res-auth>
 </resource-ref>
4、3 DataOp類
package com.arlen.dbUtil;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.sql.DataSource;

import org.apache.log4j.Logger;

public class DataOp {
 public final static String MSS_CLASS_NAME ="com.microsoft.sqlserver.jdbc.SQLServerDriver";
// private  static String DB_USER ="sa";
// private  static String DB_PASSWORD ="lz@12358";
// private  static String DB_NAME ="arlen";
// private  static String HOST_NAME ="localhost";
 private Connection conn = null;
 private Statement stmt = null;
 private Logger logger=Logger.getLogger(DataOp.class);
 
 private Connection getConnection()throws SQLException{
    Connection conn=null;
    DataSource ds = DataSourcePool.getDataSource();
    conn = ds.getConnection();
//    Class.forName(MSS_CLASS_NAME);
//    StringBuffer urlString=new StringBuffer("jdbc:sqlserver://").append(HOST_NAME)
//    .append(";database=").append(DB_NAME);
//    conn = DriverManager.getConnection(urlString.toString(),DB_USER,DB_PASSWORD);
    return conn;
 }
 /**
  * get an instance of
  * @return
  * @throws Exception
  */
 public DataOp()throws SQLException{
  conn=getConnection();
  stmt=conn.createStatement();
 }
 /**
  * to retrieve rows,you need append parameter like COLUMN_NAME1=COLUMN_VALUE1 AND/OR COLUMN_NAME2=COLUMN_VALUE2....
  * @param tableName table name stored in the database
  * @param condition condition string which appended to "where" cluster
  * @return
  */
 public ResultSet retrieveRows(String tableName,String condition) throws SQLException{
  ResultSet rs=null;
  if(conn==null||stmt!=null){
   StringBuffer sb=new StringBuffer("select * from ");
   sb.append(tableName);
   if(condition!=null&&condition.trim()!=null){
    sb.append(" where ").append(condition);
   }
   logger.debug(sb.toString());
   rs=stmt.executeQuery(sb.toString());
  }
  return rs;
 }
 
 public ResultSet executeSQL(String SQLSatatement) throws SQLException{
  ResultSet rs=null;
  if(conn==null||stmt!=null){
   logger.debug(SQLSatatement);
   rs = stmt.executeQuery(SQLSatatement);
  }
  return rs;
 }
 
 
 public ResultSet retrieveRows(String SQLSatatement) throws Exception{
  logger.debug(SQLSatatement);
  return stmt.executeQuery(SQLSatatement);
 }

 public int retrieveRowNum(String tableName,String condition) throws SQLException{
  ResultSet rs=null;
  int count = 0;
  if(conn==null||stmt!=null){
   StringBuffer sb=new StringBuffer("select count(1) from ");
   sb.append(tableName);
   if(condition!=null&&condition.trim()!=null){
    sb.append(" where ").append(condition);
   }
   logger.debug(sb.toString());
   rs=stmt.executeQuery(sb.toString());
   if(rs!=null&&rs.next())
    count=rs.getInt(1);
  }
  else{
   logger.debug("Connection not initialized!!");
  }
  if(rs!=null)
   rs.close();
  return count;
 }
 
 public void close(){
  if(conn!=null){
   try {
    conn.close();
    if(stmt!=null)
     stmt.close();
   } catch (SQLException e) {
    logger.debug("Can not close datasource!");
    e.printStackTrace();
   }
  }
 }
}
4、4 DataSourcePool類
package com.arlen.dbUtil;

import javax.sql.DataSource;

import org.springframework.jndi.support.SimpleJndiBeanFactory;

public class DataSourcePool {
 private static final SimpleJndiBeanFactory sb = new SimpleJndiBeanFactory();
 public  static DataSource getDataSource(){
  return (DataSource)sb.getBean("jdbc/webframe",DataSource.class);
 }
 public  static DataSource getDataSource(String JNDIPath){
  return (DataSource)sb.getBean("JNDIPath");
 }
}
5、打開任意瀏覽器運行

原创粉丝点击