Struts 2 简明教程
Struts 2 - Database Access
本节将指导您使用 Struts 2 以简单的步骤访问数据库。Struts 是 MVC 框架,而不是数据库框架,但它为 JPA/Hibernate 集成提供了出色的支持。我们将在后面的章节中了解 Hibernate 集成,但在本节中我们将使用普通的旧 JDBC 访问数据库。
This chapter will teach you how to access a database using Struts 2 in simple steps. Struts is a MVC framework and not a database framework but it provides excellent support for JPA/Hibernate integration. We shall look at the hibernate integration in a later chapter, but in this chapter we shall use plain old JDBC to access the database.
本节的第一步是设置并启动我们的数据库。我使用 MySQL 作为本示例中的数据库。我在计算机上安装了 MySQL,并创建了一个名为 “struts_tutorial” 的新数据库。我创建了一个名为 login 的表,并在其中填充一些值。以下是创建和填充表的脚本。
The first step in this chapter is to setup and prime our database. I am using MySQL as my database for this example. I have MySQL installed on my machine and I have created a new database called "struts_tutorial". I have created a table called login and populated it with some values. Below is the script I used to create and populate the table.
我的 MYSQL 数据库的默认用户名是 “root”,密码是 “root123”
My MYSQL database has the default username "root" and "root123" password
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 文件夹中。完成此操作后,我们现在可以创建 Action 类。
Next step is to download the MySQL Connector jar file and placing this file in the WEB-INF\lib folder of your project. After we have done this, we are now ready to create the action class.
Create Action
Action 类具有与数据库表中的列对应的属性。我们有 user, password 和 name 作为字符串属性。在 Action 方法中,我们使用用户和密码参数检查用户是否存在,如果是,我们在下一个屏幕中显示用户名。
The action class has the properties corresponding to the columns in the database table. We have user, password and name as String attributes. In the action method, we use the user and password parameters to check if the user exists, if so, we display the user name in the next screen.
如果用户输入了错误信息,我们将他们再次发送到登录屏幕。
If the user has entered wrong information, we send them to the login screen again.
以下是 LoginAction.java 文件的内容:
Following is the content of LoginAction.java file −
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;
}
}
Create Main Page
现在,让我们创建一个 JSP 文件 index.jsp 来收集用户名和密码。此用户名和密码将与数据库进行比对。
Now, let us create a JSP file index.jsp to collect the username and password. This username and password will be checked against the database.
<%@ 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>
Create Views
现在让我们创建 success.jsp 文件,该文件将在 Action 返回成功时调用,但如果 Action 返回错误,我们将有另一个视图文件。
Now let us create success.jsp file which will be invoked in case action returns SUCCESS, but we will have another view file in case of an ERROR is returned from the action.
<%@ 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>
在 Action 返回错误时,以下是视图文件 error.jsp 。
Following will be the view file error.jsp in case of an ERROR is returned from the action.
<%@ 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>
Configuration Files
最后,让我们使用 struts.xml 配置文件将所有内容组合在一起,如下所示:
Finally, let us put everything together using the struts.xml configuration file as follows −
<?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 文件的内容:
Following is the content of web.xml file −
<?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>
现在,右键单击项目名称并单击 Export > WAR File 以创建 War 文件。然后将此 WAR 部署在 Tomcat 的 webapps 目录中。最后,启动 Tomcat 服务器并尝试访问 URL http://localhost:8080/HelloWorldStruts2/index.jsp 。这将生成以下屏幕:
Now, right click on the project name and click Export > WAR File to create a War file. Then deploy this WAR in the Tomcat’s webapps directory. Finally, start Tomcat server and try to access URL http://localhost:8080/HelloWorldStruts2/index.jsp. This will produce the following screen −
输入错误的用户名和密码。您应该会看到下一页。
Enter a wrong user name and password. You should see the next page.
现在输入 scott 作为用户名,输入 navy 作为密码。您应该会看到下一页。
Now enter scott as user name and navy as password. You should see the next page.