鍍金池/ 教程/ Java/ 數(shù)據(jù)庫訪問
注釋
主題/模板
驗證
有用的資源
Struts 2 注解類型
實例
攔截器
異常處理
表單標(biāo)簽
結(jié)果類型
值棧/OGNL
Spring 集成
數(shù)據(jù)標(biāo)簽
環(huán)境配置
配置
類型轉(zhuǎn)換
動作
Hibernate 集成
本地化
發(fā)送郵件
Ajax 標(biāo)簽
數(shù)據(jù)庫訪問
體系結(jié)構(gòu)
文件上傳
Tiles 集成
概述
基本的 MVC 架構(gòu)
控制標(biāo)簽

數(shù)據(jù)庫訪問

本章將用簡單的步驟教你如何使用 Struts 2 來訪問數(shù)據(jù)庫。Struts 是一個 MVC 框架,而不是一個數(shù)據(jù)庫框架,但它為 JPA/Hibernate 集成提供了很好的支持。我們將在后面的章節(jié)中看到 Hibernate 集成,但時在本章中我們將使用普通的 JDBC 來訪問數(shù)據(jù)庫。

本章中的第一步是設(shè)置和準(zhǔn)備我們的數(shù)據(jù)庫。在這個例子中,我使用 MySQL 作為我的數(shù)據(jù)庫。我已經(jīng)在我的機器上安裝了 MySQL,并且創(chuàng)建了一個新的數(shù)據(jù)庫,稱為 “struts_tutorial”。我創(chuàng)建了一個表,稱為 login,并且用一些值填充它。下面是用來創(chuàng)建和填充表的腳本。

MYSQL 數(shù)據(jù)庫默認(rèn)的用戶名是 “root”,密碼為 “root123”。

CREATE TABLE `struts_tutorial`.`login` (
   `user` VARCHAR( 10 ) NOT NULL ,
   `password` VARCHAR( 10 ) NOT NULL ,
   `name` VARCHAR( 20 ) NOT NULL ,
   PRIMARY KEY ( `user` )
) ENGINE = InnoDB;
INSERT INTO `struts_tutorial`.`login` (`user`, `password`, `name`)
 VALUES ('scott', 'navy', 'Scott Burgemott');

下一步是下載 MySQL Connector jar 文件,并把這個文件放在你的項目的 WEB-INF\lib 文件夾下。在我們已經(jīng)做到了這個之后,現(xiàn)在就可以準(zhǔn)備創(chuàng)建動作類。

創(chuàng)建動作

動作類有對應(yīng)于數(shù)據(jù)庫表中的列的屬性。我們把 user,passwordname 作為字符串屬性。在動作方法中,我們使用 user 和 password 參數(shù)來檢查用戶是否存在,如果存在,我們在下一個畫面中顯示用戶名。如果用戶輸入了錯誤的信息,我們再次把他們發(fā)送到登錄畫面。下面是 LoginAction.java 文件的內(nèi)容:

package com.tutorialspoint.struts2;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import com.opensymphony.xwork2.ActionSupport;
public class LoginAction extends ActionSupport {
   private String user;
   private String password;
   private String name;
   public String execute() {
      String ret = ERROR;
      Connection conn = null;
      try {
         String URL = "jdbc:mysql://localhost/struts_tutorial";
         Class.forName("com.mysql.jdbc.Driver");
         conn = DriverManager.getConnection(URL, "root", "root123");
         String sql = "SELECT name FROM login WHERE";
         sql+=" user = ? AND password = ?";
         PreparedStatement ps = conn.prepareStatement(sql);
         ps.setString(1, user);
         ps.setString(2, password);
         ResultSet rs = ps.executeQuery();
         while (rs.next()) {
            name = rs.getString(1);
            ret = SUCCESS;
         }
      } catch (Exception e) {
         ret = ERROR;
      } finally {
         if (conn != null) {
            try {
               conn.close();
            } catch (Exception e) {
            }
         }
      }
      return ret;
   }
   public String getUser() {
      return user;
   }
   public void setUser(String user) {
      this.user = user;
   }
   public String getPassword() {
      return password;
   }
   public void setPassword(String password) {
      this.password = password;
   }
   public String getName() {
      return name;
   }
   public void setName(String name) {
      this.name = name;
   }
}

創(chuàng)建主頁面

現(xiàn)在,讓我們創(chuàng)建一個 JSP 文件 index.jsp,用來收集用戶名和密碼。將對數(shù)據(jù)庫進行檢查這個用戶名和密碼。

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ 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>
<title>Login</title>
</head>
<body>
   <form action="loginaction" method="post">
      User:<br/><input type="text" name="user"/><br/>
      Password:<br/><input type="password" name="password"/><br/>
      <input type="submit" value="Login"/>        
   </form>
</body>
</html>

創(chuàng)建視圖

現(xiàn)在,讓我們創(chuàng)建 success.jsp 文件,假如動作返回 SUCCESS,該文件將被調(diào)用,但是假如動作返回 ERROR,我們將有另一個視圖。

<%@ page contentType="text/html; charset=UTF-8" %>
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
<title>Successful Login</title>
</head>
<body>
   Hello World, <s:property value="name"/>
</body>
</html>

下面將是一個視圖文件 error.jsp,假如動作返回 ERROR。

<%@ page contentType="text/html; charset=UTF-8" %>
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
<title>Invalid User Name or Password</title>
</head>
<body>
   Wrong user name or password provided.
</body>
</html>

配置文件

最后,讓我們使用 struts.xml 配置文件把一切都綜合起來,如下所示:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
   <constant name="struts.devMode" value="true" />
   <package name="helloworld" extends="struts-default"> 
      <action name="loginaction" 
         class="com.tutorialspoint.struts2.LoginAction"
         method="execute">
         <result name="success">/success.jsp</result>
         <result name="error">/error.jsp</result>
      </action>  
   </package>
</struts>

下面是 web.xml 文件的內(nèi)容:

<?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_3_0.xsd"
   id="WebApp_ID" version="3.0">  
   <display-name>Struts 2</display-name>
   <welcome-file-list>
      <welcome-file>index.jsp</welcome-file>
   </welcome-file-list>
   <filter>
      <filter-name>struts2</filter-name>
      <filter-class>
         org.apache.struts2.dispatcher.FilterDispatcher
      </filter-class>
   </filter>
   <filter-mapping>
      <filter-name>struts2</filter-name>
      <url-pattern>/*</url-pattern>
   </filter-mapping>
</web-app>

現(xiàn)在,在項目名稱上點擊右鍵,并且單擊 Export > WAR File 來創(chuàng)建一個 War 文件。然后在 Tomcat 的 webapps 目錄下部署這個 WAR。最后,啟動 Tomcat 服務(wù)器并嘗試訪問 URL http://localhost:8080/HelloWorldStruts2/index.jsp. 將會給出下面的畫面:

http://wiki.jikexueyuan.com/project/struts-2/images/helloworldstruts9.jpg" alt="" />

輸入了錯誤的用戶名和密碼。你應(yīng)該看到下面的頁面:

http://wiki.jikexueyuan.com/project/struts-2/images/helloworldstruts10.jpg" alt="" />

現(xiàn)在輸入用戶名為 scott 和密碼為 navy。你應(yīng)該看到下面的頁面:

http://wiki.jikexueyuan.com/project/struts-2/images/helloworldstruts11.jpg" alt="" />

上一篇:驗證下一篇:值棧/OGNL