Struts2注解+JDBC+MySQL小项目应用

很简易的Struts2,用JDBC连接MySQL数据库。用于学习Struts2注解和JDBC基础。

一、创建数据库。小哆安装的MySQL数据库

/*
Navicat MySQL Data Transfer

Source Server         : myStruts
Source Server Version : 50142
Source Host           : localhost:3308
Source Database       : myStrutsDB

Target Server Type    : MYSQL
Target Server Version : 50142
File Encoding         : 65001

Date: 2012-01-01 10:30:30
*/

SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for `user`
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
  `userName` varchar(20) NOT NULL,
  `passWord` varchar(20) NOT NULL,
  `registeredTime` char(12) NOT NULL,
  PRIMARY KEY (`userName`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES ('111111', '111111', '201112311022');
INSERT INTO `user` VALUES ('admin', 'admin', '201112311026');

二、创建Struts2 Project

New – Dynamic Web Project<myStruts2>

导入jar包
Struts2注解+JDBC+MySQL小项目应用_第1张图片

1、项目中各部分介绍

1.1  WEBContent包含:

     1.1.1 login.jsp(可根据url直接登录)

     1.1.2 WEB-INF中: 1.1.2.1 web.xml

                    1.1.2.2 success.jsp

                   1.1.2.3  failure.jsp

PS:一般web应用将jsp放在WEB-INF文件夹下的用意:WEB-INF下面的文件会受到保护,通过浏览器无法直接访问,必须通过servlet,action跳转访问

1.2. src包含:

     1.2.1 action包:所有Action类,必须实现getter/setter,与jsp直接交互

     1.2.2 dao包:连接数据库的类

     1.2.3 dmo包:实体类,与数据表字段对应

     1.2.4 impl包:业务操作的实现类



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>myStruts2</display-name>

	<!-- 用户键入的URL不包含action名称、JSP页面或其他资源,依次寻找文件 -->
	<welcome-file-list>
		<welcome-file>login.jsp</welcome-file>
	</welcome-file-list>

	<filter>
		<!--过滤器名字 -->
		<filter-name>struts2</filter-name>
		<!-- struts2过滤器支持的StrutsPrepareFilter类 -->
		<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>

		<!-- 添加使用注解必须的参数,指定查找Action类的路径 -->
		<!-- 
		<init-param>
			<param-name>actionPackages</param-name>
			<param-value>action</param-value>
		</init-param>
 		-->
	</filter>

	<filter-mapping>
		<!--过滤器拦截名字 -->
		<filter-name>struts2</filter-name>
		<!--过滤器拦截文件路径名字 -->
		<!-- 通配符/*表示拦截所有HTTP请求 -->
		<url-pattern>/*</url-pattern>
	</filter-mapping>

</web-app>

3、编写login.jsp

<%@ page language="java" contentType="text/html; charset=utf-8"
	pageEncoding="utf-8"%>
<!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>login</title>
</head>

<body>

<form action="register!register.action">
<table>
	<tr>
		<td>用户名:</td>
		<td colspan=2><input type="text" name="userName" /></td>
	</tr>
	<tr>
		<td>密码:</td>
		<td colspan=2><input type="password" name="passWord" /></td>
	</tr>
	<tr>
		<td><input type="reset" name="reset" value="重置" /></td>
		<td colspan=2><input type="submit" name="register" value="注册" /></td>
	</tr>
</table>
</form>

<form action="login!login.action">
<table>
	<tr>
		<td>用户名:</td>
		<td colspan=2><input type="text" name="userName" /></td>
	</tr>
	<tr>
		<td>密码:</td>
		<td colspan=2><input type="password" name="passWord" /></td>
	</tr>
	<tr>
		<td><input type="reset" name="reset" value="重置" /></td>
		<td colspan=2><input type="submit" name="login" value="登录" /></td>
	</tr>
</table>
</form>

</body>
</html>

4、创建操作结果提示JSP<success.jsp/failure.jsp>

success.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<!-- Struts2标签taglib -->
<%@ 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> success </title>
</head>
<body>
<!-- 用session传输数据 -->
${sessionScope.userName}
<!-- 先声明taglib,value即对应传输数据,对应字段名;为接收到数据时,显示默认default -->
success<h1><s:property value="resultMsg" default="未接收到信息"/></h1>
</body>
</html>

failure.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<!-- Struts2标签taglib -->
<%@ 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>failure</title>
</head>
<body>
failure<h1><s:property value="resultMsg" default="未接收到信息"/></h1>
</body>
</html>

5、创建JDBC连接<dao.DBConn.java>

     

package dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

/**
 * 
 * 数据库操作
 *
 * @author 莫小哆_ly 2011-12-31
 */
public class DBConn {
    
    private Connection conn;
    /**
     * 连接数据库
     * @return
     */
    public Connection getConn(){
        String url = "jdbc:mysql://localhost:3308/myStrutsDB"; // 数据库地址[jdbc:mysql://<IP>:<db-port>/<db-name>]
        String user = "root"; // 数据库用户名
        String pwd = ""; // 数据库密码
        try {
            Class.forName("com.mysql.jdbc.Driver"); // 加载驱动
            conn = DriverManager.getConnection(url, user, pwd);// 注册驱动程序
            if (!conn.isClosed()) {
                System.out.println("连接成功");
            }
            if (conn == null) {
                System.out.println("连接数据库失败,从检查后重新启动!");
            }

        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return conn;
    }
    /**
     * 关闭数据库连接
     */
    public void closeConn(){
        if(conn!=null) {
            try{
                conn.close();
            }catch(Exception e){
                e.printStackTrace();
            }
        }
    }
}
6、创建实体类<dmo.User.java>

package dmo;

/**
 * 
 * 用户信息
 *
 * @author 莫小哆_ly 2012-1-1
 */
public class User {
    /**
     * 用户名
     */
    private String userName;
    /**
     * 密码
     */
    private String passWord;
    /**
     * 注册时间yyMMddHHmmss
     */
    private String registeredTime;
    
    public User() {
        
    }
    public User(String userName,String passWord,String registeredTime) {
        this.userName = userName;
        this.passWord = passWord;
        this.registeredTime = registeredTime;
    }
    
    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 getRegisteredTime() {
        return registeredTime;
    }
    public void setRegisteredTime(String registeredTime) {
        this.registeredTime = registeredTime;
    }
}

7、创建业务实现类,包括登录、注册、数据库操作<impl>

7.1 impl. InsertConOpera.java(实现insert操作)

package impl;

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.Date;

import dao.DBConn;

/**
 * 
 * 本页代码包含 【insert】功能
 * 
 * @author 莫小哆_ly 2011-12-31
 */
public class InsertConOpera {
    
    //注册时间yyMMddHHmmss
    private String registeredTime;
    
    /**
     * 用户注册功能
     * @param userName
     * @param passWord
     */
    public int save(String userName, String passWord) {
        int count = 0;
        try {
            DBConn db = new DBConn();
            Connection conn = db.getConn();
            
            // 执行静态SQL语句
            Statement stmt = conn.createStatement();
            
            //生成注册时间
            Date now = new Date();
            SimpleDateFormat format = new SimpleDateFormat("yyMMddHHmmss");
            registeredTime = format.format(now);

            String sql0 = "INSERT INTO user(userName,passWord,registeredTime) " + " VALUES (" + "'"
                    + userName + "','" + passWord + "','" + registeredTime + "')";
            count = stmt.executeUpdate(sql0);
            if (stmt != null) { // 关闭声明
                try {
                    stmt.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (conn != null) { // 关闭连接对象
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            db.closeConn();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return count;
    }
}

7.2 impl. SelectConOper.java (实现select操作)

package impl;

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

import dao.DBConn;
/**
 * 
 * 本页代码包含 【select】功能
 *
 * @author 莫小哆_ly 2012-1-1
 */
public class SelectConOper {
    
    /**
     * 注册时检测功能
     * @param userName
     * @return
     */
    public int select(String userName) {
        int count=0;
        try {
            DBConn db = new DBConn();
            Connection conn = db.getConn();
            Statement stmt = conn.createStatement() ;
            
            String sq20 = "SELECT count(*) FROM user WHERE userName = " 
                + "'" + userName + "'";
            //执行给定的 SQL 语句,该语句返回单个 ResultSet对象
            ResultSet rs = stmt.executeQuery(sq20) ;
            while(rs.next()){ 
                count = rs.getInt(1);
            }
            if(rs != null){ // 关闭记录集
                try{ 
                    rs.close() ; 
                }catch(SQLException e){ 
                    e.printStackTrace() ;
                } 
            } 
            if(stmt != null){ // 关闭声明 
                try{
                    stmt.close() ; 
                }catch(SQLException e){
                    e.printStackTrace() ;
                }
            } 
            if(conn != null){ // 关闭连接对象
                try{
                    conn.close() ;
                }catch(SQLException e){ 
                    e.printStackTrace() ; 
                }
            }
            db.closeConn();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return count;
    }
    
    /**
     * 静态SQL语句
     * @param userName
     * @param passWord
     * @return
     */
    public int selectStatement(String userName,String passWord) {
        int count=0;
        try {
            DBConn db = new DBConn();
            Connection conn = db.getConn();
            Statement stmt = conn.createStatement() ;
            
            String sq20 = "SELECT count(*) FROM user WHERE userName = " 
                + "'" + userName + "' and userName = '" + passWord + "'";
            
            ResultSet rs = stmt.executeQuery(sq20) ;
            while(rs.next()){ 
                count = rs.getInt(1);
            }
            if(rs != null){ // 关闭记录集
                try{ 
                    rs.close() ; 
                }catch(SQLException e){ 
                    e.printStackTrace() ;
                } 
            } 
            if(stmt != null){ // 关闭声明 
                try{
                    stmt.close() ; 
                }catch(SQLException e){
                    e.printStackTrace() ;
                }
            } 
            if(conn != null){ // 关闭连接对象
                try{
                    conn.close() ;
                }catch(SQLException e){ 
                    e.printStackTrace() ; 
                }
            }
            db.closeConn();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return count;
    }
    
    /**
     * 动态SQL语句
     * @param userName
     * @param passWord
     * @return
     */
    public int selectPreparedStatement(String userName,String passWord) {
        int count=0;
        try {
            DBConn db = new DBConn();
            Connection conn = db.getConn();
            
            String sq30 = "SELECT count(*) FROM user WHERE userName = ? and passWord = ?";
            PreparedStatement pstmt = conn.prepareStatement(sq30);
            
            pstmt.setString(1,userName);
            pstmt.setString(2,passWord);
            
            ResultSet rs = pstmt.executeQuery() ;
            
            while(rs.next()){ 
                count = rs.getInt(1);
            }
            if(rs != null){ // 关闭记录集
                try{ 
                    rs.close() ; 
                }catch(SQLException e){ 
                    e.printStackTrace() ;
                } 
            } 
            if(pstmt != null){ // 关闭声明 
                try{
                    pstmt.close() ; 
                }catch(SQLException e){
                    e.printStackTrace() ;
                }
            } 
            if(conn != null){ // 关闭连接对象
                try{
                    conn.close() ;
                }catch(SQLException e){ 
                    e.printStackTrace() ; 
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return count;
    }
}

此处动态SQL和静态SQL二选其一即可。

7.3 impl.RegisterImpl.java (实现注册相关业务操作)

package impl;

/**
 * 
 * 实现注册相关业务
 *
 * @author 莫小哆_ly 2012-1-1
 */
public class RegisterImpl {
 
    SelectConOper selectConn = new SelectConOper();
    InsertConOpera insertConn = new InsertConOpera();
    
    //校验业务,select
    public int findByUserName(String userName) {
        int count = selectConn.select(userName);
        return count;
    }
    
    //注册业务,insert
    public int register(String userName, String passWord) {
        int count = insertConn.save(userName,passWord);
        return count;
    }
}

7.4 impl. LoginImpl.java (实现insert操作)

package impl;

import dmo.User;

/**
 * 
 * 实现登录相关业务
 *
 * @author 莫小哆_ly 2012-1-1
 */
public class LoginImpl {
    
    SelectConOper selectConn = new SelectConOper();
    
    //登录业务,select
    public int login(User user) {
        int count = selectConn.selectStatement(user.getUserName(), user.getPassWord());
        return count;
    }
}

8、编写Action类,与jsp交互<action.LoginAction.ava>

package action;

import java.util.Map;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;

import impl.RegisterImpl;
import impl.SelectConOper;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

@Namespace("")
@Results({ @Result(name = "loginSuccess", location = "/WEB-INF/success.jsp"),
        @Result(name = "loginFailure", location = "/WEB-INF/failure.jsp"),
        @Result(name = "checkSuccess", location = "/WEB-INF/success.jsp"),
        @Result(name = "checkFailure", location = "/WEB-INF/failure.jsp") })
public class LoginAction extends ActionSupport {

    private static final long serialVersionUID = 1L;

    private String            userName;
    private String            passWord;
    private String            resultMsg;
    private int               resultInt;
    
    RegisterImpl              regImpl          = new RegisterImpl();

    // 对应的jsp:
    // Namespace/类名!方法名.action
    // <form action="action/login!login.action">

    // Action!方法名.action
    // <form action="login!login.action">

    // 提交注册
    @Action("register")
    public String register() {
        // 验证用户名是否重复
        resultInt = regImpl.findByUserName(userName);
        if (resultInt != 0) {
            resultMsg = "用户名已被使用,请重新输入";
            return "registerFailure";
        } else {
            resultInt = regImpl.register(userName, passWord);
            if (1 == resultInt) {
                // 1. 将用户信息保存到Session中。
                Map<String, Object> session = ActionContext.getContext().getSession();
                session.put("userName", userName);
                session.put("passWord", passWord);
                // 2. taglib标识传递
                resultMsg = "注册成功";
                return "registerSuccess";
            } else {
                resultMsg = "注册失败";
                return "registerFailure";
            }
        }
    }

    // 登录
    @Action("login")
    public String login() {
        resultMsg = null;
        // 对用户的输入格式进行验证//应定义在jsp页面javScript
        if ("".equals(userName) || userName == null) {
            resultMsg = "用户名不能为空";
            return "checkFailure";
        } else if ("".equals(passWord) || passWord == null) {
            resultMsg = "密码不能为空";
            return "checkFailure";
        } else {
            if (passWord.length() < 4 || passWord.length() > 10) {
                resultMsg = "密码必须在4到10之间";
                return "checkFailure";
            }
        }
        // 数据库查询,根据用户输入与数据库中数据匹配情况
        SelectConOper selectConOpe = new SelectConOper();
        int resultInt = selectConOpe.selectStatement(userName, passWord);
        // int resultInt =
        // selectConOpe.selectPreparedStatement(userName,passWord);

        if (1 == resultInt) {
            resultMsg = "登录成功";
            return "loginSuccess";
        } else {
            resultMsg = "登录失败";
            return "loginFailure";
        }
    }

    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 getResultMsg() {
        return resultMsg;
    }

    public void setResultMsg(String resultMsg) {
        this.resultMsg = resultMsg;
    }
}

这样,一个很简单的Struts2注解的WEB项目,就完成了。


另外,小哆在安装MySQL时,遇到了不大不小的麻烦,安装总是异常,当时就选了一个文档看了看。

百度文库MYSQL 

链接http://wenku.baidu.com/view/b7dbf904e87101f69e3195a4.html


我还特意追了下文档源头

百度文库mysql5.1()

链接如下: http://wenku.baidu.com/view/4de81840be1e650e52ea99ef.html



源码下载: http://download.csdn.net/detail/sdsky1987/4024192






你可能感兴趣的:(数据库,mysql,jdbc,struts,String,action)