Struts2+Jdbc登录样例


扒掉框架主要是为了熟悉一下各个配置文件和jdbc的辅助类 .



1.  struts.xml

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

<struts>  
     
    <package name="struts2login" extends="struts-default">  
        <!-- 这里的Class是由Spring里面制定的ID,如果单独用struts2,则这里是包名+类名 -->  
        <action name="UserLogin" class="com.rt.action.LoginAction">  
            <result name="success" >/WEB-INF/page/success.jsp</result>  
            <result name="input">/WEB-INF/page/login.jsp</result>  
        </action>       
    </package> 
     
</struts>  


2.  web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
	id="WebApp_ID" version="2.5">
	<display-name></display-name>

	<!-- Struts2配置 -->
	<filter>
        <filter-name>struts2</filter-name>
        <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>struts2</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
	<!-- 设置程序的默认欢迎页面-->
	<welcome-file-list>
		<welcome-file>index.jsp</welcome-file>
	</welcome-file-list>
	
	
		<!-- 对Spring容器进行实例化 
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath:applicationContext-*.xml</param-value>
	</context-param>
	 OpenSessionInViewFilter过滤器 
	<filter>
		<filter-name>openSessionInViewFilter</filter-name>
		<filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class>
	</filter>
	<filter-mapping>
		<filter-name>openSessionInViewFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>-->
	
</web-app>


3.  struts.properties

struts.i18n.encoding=UTF-8


4.  LoginAction

public class LoginAction extends ActionSupport {  
  
    private Person per;  
  
    private static final long serialVersionUID = 1L;  
  
    public String execute() throws Exception {  
        PersonDao dao = new PersonDaoImpl();  
        boolean flag = dao.isPersonCanLogin(per.getUsername(), per.getPassword());  
        if(flag){  
            Map session=(Map)ActionContext.getContext().get(ActionContext.SESSION);  
            session.put("user", per.getUsername());  
            return SUCCESS;  
        } else {  
            return INPUT;  
        }  
    }  
  
    public Person getPer() {  
        return per;  
    }  
  
    public void setPer(Person per) {  
        this.per = per;  
    }  
}  


5.  Dao

package com.rt.dao;

public interface PersonDao {  
	  

    public boolean isPersonCanLogin(String username, String password) ;
        
}


6.  DaoImpl

import com.rt.util.JdbcHelper;


public class PersonDaoImpl implements PersonDao {

	@Override
	public boolean isPersonCanLogin(String username, String password) {
		
		String tar = null;
		JdbcHelper jh = new JdbcHelper();
		
		try {
			tar = jh.queryUserPassword(username);
		} catch (SQLException e) {
			
			e.printStackTrace();
		}
		
		return tar.equals(password) ? true : false;		
	}
	
}  
	


7.  JdbcHelper

package com.rt.util;

import java.sql.Connection;  
import java.sql.DriverManager;  
import java.sql.PreparedStatement;  
import java.sql.ResultSet;  
import java.sql.SQLException;  
import java.sql.Statement;  
  
public class JdbcHelper {  
  
    private static final String DB_DRIVER = "com.mysql.jdbc.Driver";  
    //jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8
    //com.mysql.jdbc.Driver
    //oracle.jdbc.driver.OracleDriver
    //"jdbc:oracle:thin:@localhost:1521:ORCL"
    private static final String DB_CONNECTION = "jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8";  
    private static final String DB_USER = "root";  
    private static final String DB_PASSWORD = "890307";  
      
    private Connection conn = null;//不能是static, 多个查询需要单独实例化
    private PreparedStatement prep = null;  
      
      
    /* 仅此一个样例 
     */  
    public String queryUserPassword(String name) throws SQLException{ 
    	
    	String res =null;
    	String sql = "SELECT password FROM tt_user WHERE username =?";
    	try{  
            conn = getDBConnection();  
            prep = conn.prepareStatement(sql);  
            prep.setString(1, name);  
            System.out.println(sql);  
              
            //execute select SQL statement     
            ResultSet rs = prep.executeQuery();  
            //while(rs.next()){  
                //int id = rs.getInt("id");  
               //String username = rs.getString("username");  
                //System.out.println("id: "+ id);  
                //System.out.println("username: "+ username);  	
            //} 
            
            if(rs.next()){ 
            	res = rs.getString("password");
            }
            else
            {
            	res =  "0";
            }
            
        }catch(SQLException e){  
            System.out.println(e.getMessage());  
        }finally{  
            if (prep != null)  
            {  
                try  
                {  
                    prep.close();  
                }  
                catch (SQLException ex1)  
                {  
                }  
            }  
                
            if (conn != null)  
            {  
                try  
                {  
                    conn.close();  
                }  
                catch (SQLException ex1)  
                {  
                }  
            }  
        }  
    	
    	return res;
    }


 插入和删除要用 prep.executeUpdate();

 增加表格可以用 prep.execute();  


    private Connection getDBConnection(){  
         
        try{  
            Class.forName(DB_DRIVER);   //try中的语句尽量短  
        }catch(ClassNotFoundException e){  
            System.err.println(e.getMessage());  
        }  
          
        try{  
            conn = DriverManager.getConnection(DB_CONNECTION,DB_USER, DB_PASSWORD);  
        }catch(SQLException e){ //catch尽量多分类处理  
            System.err.println(e.getMessage());  
        }  
          
        return conn;  
    } 


8.  Model

package com.rt.model;
 
public class Person {  
  
    private String username;  
      
    private String password;  
  
    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;  
    }     
}  



9. 登陆页面

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
  
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  
<html>  
  <head>      
    <title>Struts2 Person Login Test</title>  
  </head>  
    
  <body>  
    <s:form action="UserLogin">  
        <s:textfield name="per.username" label="username"></s:textfield>  
        <s:password name="per.password" label="password"></s:password>  
        <s:submit></s:submit>  
    </s:form>  
  </body>  
</html>  


10.  index和成功页

  <body>
    
           正在跳转....
    <%
    	response.sendRedirect(basePath+"login.jsp");
    %>
  </body>


<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
 
<%  
String path = request.getContextPath();  
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";  
String username = (String)session.getAttribute("user");  
%>  
  
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  
<html>  
  <head>  
    <base href="<%=basePath%>">  
    <title>Struts2 Person Login Result</title>  
  </head>  
    
  <body>  
    Hi:<br>  
    <%=username%><br>  
    Welcome... <br>  
  </body>  
</html>  


11. 另一个Jdbc辅助类的示例

public class NoteDAOImpl implements NoteDAO {   
        // 增加操作   
        public void insert(Note note) throws Exception {   
            String sql = "INSERT INTO note(id,title,author,content) VALUES(note_sequ.nextVal,?,?,?)" ;   
            PreparedStatement pstmt = null ;   
            DataBaseConnection dbc = null ;   
            dbc = new DataBaseConnection() ;   
            try {   
                pstmt = dbc.getConnection().prepareStatement(sql) ;   
                pstmt.setString(1,note.getTitle()) ;   
                pstmt.setString(2,note.getAuthor()) ;   
                pstmt.setString(3,note.getContent()) ;   
                pstmt.executeUpdate() ;   
                pstmt.close() ;   
            } catch (Exception e) {   
                // System.out.println(e) ;   
                throw new Exception("操作中出现错误!!!") ;   
            } finally {   
                dbc.close() ;   
            }   
        }   
        // 修改操作   
        public void update(Note note) throws Exception {   
            String sql = "UPDATE note SET title=?,author=?,content=? WHERE id=?" ;   
            PreparedStatement pstmt = null ;   
            DataBaseConnection dbc = null ;   
            dbc = new DataBaseConnection() ;   
            try {   
                pstmt = dbc.getConnection().prepareStatement(sql) ;   
                pstmt.setString(1,note.getTitle()) ;   
                pstmt.setString(2,note.getAuthor()) ;   
                pstmt.setString(3,note.getContent()) ;   
                pstmt.setInt(4,note.getId()) ;   
                pstmt.executeUpdate() ;   
                pstmt.close() ;   
            } catch (Exception e) {   
                throw new Exception("操作中出现错误!!!") ;   
            } finally {   
                dbc.close() ;   
            }   
        }   
        // 删除操作   
        public void delete(int id) throws Exception {   
            String sql = "DELETE FROM note WHERE id=?" ;   
            PreparedStatement pstmt = null ;   
            DataBaseConnection dbc = null ;   
            dbc = new DataBaseConnection() ;   
            try {   
                pstmt = dbc.getConnection().prepareStatement(sql) ;   
                pstmt.setInt(1,id) ;   
                pstmt.executeUpdate() ;   
                pstmt.close() ;   
            } catch (Exception e) {   
                throw new Exception("操作中出现错误!!!") ;   
            } finally {   
                dbc.close() ;   
            }   
        }   
        // 按ID查询,主要为更新使用   
        public Note queryById(int id) throws Exception {   
            Note note = null ;   
            String sql = "SELECT id,title,author,content FROM note WHERE id=?" ;   
            PreparedStatement pstmt = null ;   
            DataBaseConnection dbc = null ;   
            dbc = new DataBaseConnection() ;   
            try {   
                pstmt = dbc.getConnection().prepareStatement(sql) ;   
                pstmt.setInt(1,id) ;   
                ResultSet rs = pstmt.executeQuery() ;   
                if(rs.next()) {   
                    note = new Note() ;   
                    note.setId(rs.getInt(1)) ;   
                    note.setTitle(rs.getString(2)) ;   
                    note.setAuthor(rs.getString(3)) ;   
                    note.setContent(rs.getString(4)) ;   
                }   
                rs.close() ;   
                pstmt.close() ;   
            } catch (Exception e) {   
                throw new Exception("操作中出现错误!!!") ;   
            } finally {   
                dbc.close() ;   
            }   
            return note ;   
        }   
        // 查询全部   
        public List queryAll() throws Exception {   
            List all = new ArrayList() ;   
            String sql = "SELECT id,title,author,content FROM note" ;   
            PreparedStatement pstmt = null ;   
            DataBaseConnection dbc = null ;   
            dbc = new DataBaseConnection() ;   
            try {   
                pstmt = dbc.getConnection().prepareStatement(sql) ;   
                ResultSet rs = pstmt.executeQuery() ;   
                while(rs.next()) {   
                    Note note = new Note() ;   
                    note.setId(rs.getInt(1)) ;   
                    note.setTitle(rs.getString(2)) ;   
                    note.setAuthor(rs.getString(3)) ;   
                    note.setContent(rs.getString(4)) ;   
                    all.add(note) ;   
                }   
                rs.close() ;   
                pstmt.close() ;   
            } catch (Exception e) {   
                System.out.println(e) ;   
                throw new Exception("操作中出现错误!!!") ;   
            } finally {   
                dbc.close() ;   
            }   
            return all ;   
        }   
        // 模糊查询   
        public List queryByLike(String cond) throws Exception {   
            List all = new ArrayList() ;   
            String sql = "SELECT id,title,author,content FROM note WHERE title LIKE ? or AUTHOR LIKE ? or CONTENT LIKE ?" ;   
            PreparedStatement pstmt = null ;   
            DataBaseConnection dbc = null ;   
            dbc = new DataBaseConnection() ;   
            try {   
                pstmt = dbc.getConnection().prepareStatement(sql) ;   
                pstmt.setString(1,"%"+cond+"%") ;   
                pstmt.setString(2,"%"+cond+"%") ;   
                pstmt.setString(3,"%"+cond+"%") ;   
                ResultSet rs = pstmt.executeQuery() ;   
                while(rs.next()) {   
                    Note note = new Note() ;   
                    note.setId(rs.getInt(1)) ;   
                    note.setTitle(rs.getString(2)) ;   
                    note.setAuthor(rs.getString(3)) ;   
                    note.setContent(rs.getString(4)) ;   
                    all.add(note) ;   
                }   
                rs.close() ;   
                pstmt.close() ;   
            } catch (Exception e) {   
                System.out.println(e) ;   
                throw new Exception("操作中出现错误!!!") ;   
            } finally {   
                dbc.close() ;   
            }   
            return all ;   
        }   
    };  

























  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值