struts2数据库操作
Struts 2 provide a lot of custom tags for development and we have already looked into Data Tags, Control Tags and UI Tags. Today we will look into two tags that are related to action class response that we can use in the result pages.
Struts 2提供了许多用于开发的自定义标签,我们已经研究了数据标签 , 控制标签和UI标签 。 今天,我们将研究与可在结果页中使用的动作类响应相关的两个标记。
Struts 2操作错误和操作消息 (Struts 2 Action Error and Action Message)
- actionerror tag: This tag is used in conjunction with Action class validation for form fields. If validation fails for any form fields, we can add action errors and then Struts 2 API forwards the request to “input” result page where we can use this tag to show the error messages. This tag is helpful in server side validation of form fields and then returning the input page with error message. Syntax of this tag is:
<s:actionerror/>
We will look it’s usage with a simple project to explain how easy
actionerror标记 :此标记与Action类验证一起用于表单字段。 如果对任何表单字段的验证失败,我们可以添加操作错误,然后Struts 2 API将请求转发到“输入”结果页面,在这里我们可以使用此标记显示错误消息。 此标记有助于服务器端验证表单字段,然后返回带有错误消息的输入页面。 该标签的语法是:s:actionerror
is to use.<s:actionerror/>
我们将通过一个简单的项目来了解它的用法,以说明
s:actionerror
的使用方法有多么容易。 - actionmessage tag: This tag is used to show some custom message added by Action classes in the result page. For example, we can use this tag to welcome a user and show them last login time at the top of the page. Syntax of this tag is:
actionmessage标记 :此标记用于显示由结果类中的Action类添加的一些自定义消息。 例如,我们可以使用此标记来欢迎用户,并在页面顶部显示他们的上次登录时间。 该标签的语法是:<s:actionmessage/>
<s:actionmessage/>
Both these tags generated an unordered list of action errors or messages added in the action class. Let’s create a simple project to show their usage. Our final project will look like below image.
这两个标记均生成无序的操作错误列表或在操作类中添加的消息。 让我们创建一个简单的项目来显示其用法。 我们的最终项目将如下图所示。
Struts 2配置文件 (Struts 2 Configuration Files)
web.xml
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance" xmlns="https://java.sun.com/xml/ns/javaee" xsi:schemaLocation="https://java.sun.com/xml/ns/javaee https://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>Struts2ActionErrorMessages</display-name>
<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>
</web-app>
pom.xml
pom.xml
<project xmlns="https://maven.apache.org/POM/4.0.0" xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="https://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>Struts2ActionErrorMessages</groupId>
<artifactId>Struts2ActionErrorMessages</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<dependencies>
<dependency>
<groupId>org.apache.struts</groupId>
<artifactId>struts2-core</artifactId>
<version>2.3.15.1</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>2.3</version>
<configuration>
<warSourceDirectory>WebContent</warSourceDirectory>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
</plugins>
<finalName>${project.artifactId}</finalName>
</build>
</project>
struts.xml
struts.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
"https://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
<!-- constant to define result path locations to project root directory -->
<constant name="struts.convention.result.path" value="/"></constant>
<!-- constant to define global properties file for i18n messages -->
<constant name="struts.custom.i18n.resources" value="global"></constant>
<package name="user" namespace="/" extends="struts-default">
<action name="login">
<result>/login.jsp</result>
</action>
<action name="Welcome" class="com.journaldev.struts2.actions.WelcomeAction">
<result name="success">/welcome.jsp</result>
<result name="input">/login.jsp</result>
</action>
</package>
</struts>
Configuration files are self understood and used to configure maven web application project to use Struts2 framework. The important point to note is the struts.custom.i18n.resources
where we are providing property file name for global messages. We will use this file for labels in result pages for internationalization.
配置文件是易于理解的,并用于配置Maven Web应用程序项目以使用Struts2框架。 需要注意的重要点是struts.custom.i18n.resources
,我们在其中为全局消息提供属性文件名。 我们将使用此文件作为结果页面中的标签进行国际化。
Another point to notice is the “input” result page for Welcome action, it’s used incase of any form field validation failure.
需要注意的另一点是“欢迎”操作的“输入”结果页面,用于任何表单字段验证失败的情况。
global.properties
global.properties
#global messages
msg.welcome=Hi
label.username=User Name
label.password=Password
label.submit.login=Login
#error messages
error.username.required=User Name is required field
error.password.required=Password is required field
A simple property file that will be used in result pages for labels.
一个简单的属性文件,将在标签的结果页中使用。
Struts 2动作类 (Struts 2 Action Class)
WelcomeAction.java
WelcomeAction.java
package com.journaldev.struts2.actions;
import com.opensymphony.xwork2.ActionSupport;
public class WelcomeAction extends ActionSupport {
@Override
public String execute() {
return SUCCESS;
}
@Override
public void validate() {
if("pankaj".equalsIgnoreCase(getUsername()) && "admin".equalsIgnoreCase(getPassword())){
addActionMessage("Welcome Admin, do some work.");
}else{
if(!"pankaj".equalsIgnoreCase(getUsername())){
addActionError("User name is not valid");
}
if(!"admin".equalsIgnoreCase(getPassword())){
addActionError("Password is wrong");
}
}
}
// java bean properties
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;
}
}
We are extending ActionSupport
class and overriding validate method where we are adding action errors and action messages to ValueStack. Other part of action classes include execute() method and java bean properties with getter setter methods.
我们正在扩展ActionSupport
类并覆盖validate方法,在其中向ValueStack添加操作错误和操作消息。 动作类的其他部分包括execute()方法和带有getter setter方法的java bean属性。
Struts 2结果页面 (Struts 2 Result Pages)
login.jsp
login.jsp
<%@ page language="java" contentType="text/html; charset=US-ASCII"
pageEncoding="US-ASCII"%>
<%@ taglib uri="/struts-tags" prefix="s" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "https://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Login Page</title>
<!-- Adding CSS for Styling of error messages -->
<style type="text/css">
.errorDiv{
background-color:gray;
border:1px solid black;
width:400px;
margin-bottom:8px;
}
</style>
</head>
<body>
<h3>Struts2 ActionError Example</h3>
<%-- hasActionErrors() method is defined in ActionSupport --%>
<s:if test="hasActionErrors()">
<div class="errorDiv">
<s:actionerror/>
</div>
</s:if>
<s:form action="Welcome">
<s:textfield name="username" key="label.username"></s:textfield>
<s:password name="password" key="label.password"></s:password>
<s:submit key="label.submit.login" align="center" name="submit"></s:submit>
</s:form>
</body>
</html>
We are using Struts2 if conditional tag to check if there are any action error messages are present or not. hasActionErrors()
method is defined in ActionSupport class that returns true if any action errors exists in the ValueStack.
如果条件标签用于检查是否存在任何操作错误消息,我们将使用Struts2。 在ActionSupport类中定义了hasActionErrors()
方法,如果ValueStack中存在任何操作错误,则该方法返回true。
Notice that we are using CSS for styling of error messages and using key attributes of UI tags to generate the label from property file configured in struts configuration file. We are not using actionmessage
tag here because if validation doesn’t fail, we are not returning to this page.
请注意,我们正在使用CSS设置错误消息的样式,并使用UI标记的关键属性从struts配置文件中配置的属性文件生成标签。 我们此处未使用actionmessage
标签,因为如果验证没有失败,我们将不会返回此页面。
welcome.jsp
welcome.jsp
<%@ page language="java" contentType="text/html; charset=US-ASCII"
pageEncoding="US-ASCII"%>
<%@ taglib uri="/struts-tags" prefix="s" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "https://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Welcome Page</title>
<style type="text/css">
.welcome {
background-color:green;
border:1px solid black;
width:400px;
}
//ul.actionMessage is added by Struts2 API
ul.actionMessage li {
color:yellow;
}
</style>
</head>
<body>
<h3>Struts2 ActionMessage Example</h3>
<s:if test="hasActionMessages()">
<div class="welcome">
<s:actionmessage/>
</div>
</s:if>
<br><br>
<s:property value="getText('msg.welcome')" /> <s:property value="username"/>
</body>
</html>
A simple result page where we are utilizing actionmessage tag. Since this tag generates list with class name as actionMessage
, we can use it for styling purpose. hasActionMessages()
method is defined in ActionSupport class and returns true if there are any action messages present.
一个简单的结果页面,我们在其中使用actionmessage标签。 由于此标记生成的列表的类名称为actionMessage
,因此我们可以将其用于样式目的。 hasActionMessages()
方法在ActionSupport类中定义,如果存在任何操作消息,则返回true。
When we run above application, we get following response pages.
当我们运行上面的应用程序时,我们得到以下响应页面。
Generated HTML snippet of actionerror
tag is:
生成的actionerror
标记HTML代码段是:
<ul class="errorMessage">
<li><span>User name is not valid</span></li>
<li><span>Password is wrong</span></li>
</ul>
Generated HTML snippet of actionmessage
tag is:
生成的actionmessage
标签HTML代码段是:
<ul class="actionMessage">
<li><span>Welcome Admin, do some work.</span></li>
</ul>
As you can see it’s very easy to use action errors and action messages tags in result pages and since generated html contains class for tags, we can easily add CSS rules for specific styling purposes. Download project from below link and play around with it for better understanding.
如您所见,在结果页面中使用动作错误和动作消息标记非常容易,并且由于生成的html包含标记的类,因此我们可以轻松地为特定样式目的添加CSS规则。 从下面的链接下载项目,并进行尝试以更好地理解。
翻译自: https://www.journaldev.com/2274/struts-2-action-error-action-message
struts2数据库操作