Struts2 learn
Configuration
basic configuration
使用intellij 默认的maven项目管理依赖
配置maven源镜像为国内阿里
pom.xml中添加以下依赖
在properties中添加struct和log4j变量
1
2
3
4
5
6
7<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<struts2.version>2.5.14.1</struts2.version>
<log4j2.version>2.10.0</log4j2.version>
</properties>1
2. 添加具体日志和struct依赖
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17<dependency>
<groupId>org.apache.struts</groupId>
<artifactId>struts2-core</artifactId>
<version>${struts2.version}</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>${log4j2.version}</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>${log4j2.version}</version>
</dependency>
- 添加运行插件
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<plugin>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-maven-plugin</artifactId>
<version>9.4.7.v20170914</version>
<configuration>
<webApp>
<contextPath>/${build.finalName}</contextPath>
</webApp>
<stopKey>CTRL+C</stopKey>
<stopPort>8999</stopPort>
<scanIntervalSeconds>10</scanIntervalSeconds>
<scanTargets>
<scanTarget>src/main/webapp/WEB-INF/web.xml</scanTarget>
</scanTargets>
</configuration>
</plugin>1
4. 在intellij 中添加maven命令,命令格式:jetty:run
project structure
添加java文件夹:src/main/java/
/controller 和dao层 这里的view是: src/main/webapp/index.jsp
添加拦截器:用于将所有url访问拦截给struts框架 在src/main/resources/struts.xml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<struts>
<constant name="struts.devMode" value="true" />
<package name="basicstruts2" extends="struts-default">
<action name="index">
<result>/index.jsp</result>
</action>
<action name="hello" class="com.tr.controller.HelloWorldAction" method="execute">
<result name="success">/HelloWorld.jsp</result>
<result name="error">/error.jsp</result>
</action>
</package>
</struts>添加log4j的配置:src/main/resources/log4j2.xml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<Configuration>
<Appenders>
<Console name="STDOUT" target="SYSTEM_OUT">
<PatternLayout pattern="%d %-5p [%t] %C{2} (%F:%L) - %m%n"/>
</Console>
</Appenders>
<Loggers>
<Logger name="com.opensymphony.xwork2" level="debug"/>
<Logger name="org.apache.struts2" level="debug"/>
<Root level="warn">
<AppenderRef ref="STDOUT"/>
</Root>
</Loggers>
</Configuration>
example
在webapp下添加index.jsp
- ```html
<%@ page language=”java” contentType=”text/html; charset=UTF-8” pageEncoding=”UTF-8” %>
<%@ taglib prefix=”s” uri=”/struts-tags”%>Basic Struts 2 Application - Welcome Welcome To Struts 2!
<s:url action=”hello” var=”helloLink”><s:param name="userName">Bruce Phillips</s:param>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
2. 在webapp下添加HelloWorld.jsp
```html
<%--
Created by IntelliJ IDEA.
User: tr
Date: 19-3-4
Time: 下午4:18
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="s" uri="/struts-tags"%>
<html>
<head>
<title>hello world</title>
</head>
<body>
<h2><s:property value="messageStoreSuccess.message" /></h2>
</body>
</html>
- ```html
<%@ page language=”java” contentType=”text/html; charset=UTF-8” pageEncoding=”UTF-8” %>
在webapp下添加error.jsp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18<%--
Created by IntelliJ IDEA.
User: tr
Date: 19-3-5
Time: 上午10:06
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
<title>error page</title>
</head>
<body>
<h1>error info <s:property value="messageStoreError.message"/></h1>
</body>
</html>在java包内的controller文件夹建立HelloWorldAction.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40package com.tr.controller;
import com.opensymphony.xwork2.ActionSupport;
import com.tr.dao.MessageStore;
import java.util.Random;
/***
* @author tr
*/
public class HelloWorldAction extends ActionSupport {
private MessageStore messageStoreSuccess = null;
private MessageStore messageStoreError = null;
private int count = 1;
private int mgNumber = 2;
public String execute() throws Exception {
Random random = new Random();
count = random.nextInt();
if(count%mgNumber==0){
messageStoreSuccess = new MessageStore("Welcome you are the: "+count);
return SUCCESS;
}
else {messageStoreError = new MessageStore("error count value is: " + count);
return ERROR;}
}
public MessageStore getMessageStoreSuccess() {
return messageStoreSuccess;
}
public MessageStore getMessageStoreError() {
return messageStoreError;
}
}在java包内的dao文件夹建立MessageStore.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18package com.tr.dao;
/**
* @author tr
*/
public class MessageStore {
private String message;
public MessageStore(String message) {
this.message = message;
}
public String getMessage() {
return message;
}
}运行maven命令 输入 url 类似 0.0.0.:8080/
/index.action
Taglib
url tag with param
1 | <s:url action="hello" var="helloLink"> |
这会产生url的参数 ?userName=Bruce Phillips
struts2 form tag
1 | <p>Get your own personal hello by filling out and submitting this form.</p> |
这会产生一个post请求到./hello.action
struts2 property tag
1 | <s:property value="messageStore.message" /> |
自动调用对应action的getMessageStore方法 再获取内部message
注意的是每个url请求对应的action对象不同,如果希望这些不同对象同享变量,变量要加static
如果getMessageStore返回的messageStore对象执行他的.method()返回不同结果
- 返回的是string 不做变换
2. 返回的是int 变为string- 返回的是对象,自动调用toString
其实最后给人的感觉是可以直接调用java文件里的成员变量
Coding actions
action mapping in struts.xml
1 | <action name="hello" class="com.tr.controller.HelloWorldAction" method="execute"> |
action和class关联 并且确定了对view的提供
action接受输入的参数
1 | <s:form action="hello"> |
需要在控制hello的java类中创建一个userName属性并且实现setter和getter
Processing Forms
Forms and a Java model class
create a javabean,在dao层创建Person.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48package com.tr.dao;
/**
* @author tr
*/
public class Person {
private String firstName;
private String lastName;
private String email;
private int age;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String toString() {
return "First Name: " + getFirstName() + " Last Name: " + getLastName() +
" Email: " + getEmail() + " Age: " + getAge() ;
}
}view层register.jsp
1 | <%@ taglib prefix="s" uri="/struts-tags" %> |
- controller层的Register.java
1 | import com.opensymphony.xwork2.ActionSupport; |
- 注意事项:struts2会首先实例化personBean然后赋值,执行execute的时候已经有personBean这个实例了,不需要手动实例化
- 添加thankyou.jsp
1 | <%@ taglib prefix="s" uri="/struts-tags" %> |
Form Validation
总结一下就是写个validate,在struts.xml里添加
1 | <result name="input">/register.jsp</result> |
然后会自己自动显示错误信息,以下为官方详细说明:
重写action里的validata方法,这样会自动调用 方法例子:
1 | public void validate(){ |
If any errors have been added then Struts 2 will not proceed to call the execute method. Rather the Struts 2 framework will return input
as the result of calling the action.
Handle Input Being Returned
So what should we do if Struts 2 returns input
indicating that the user’s input in the form is not valid? In most cases we will want to redisplay the web page that has the form and include in the form error messages to inform the user what is wrong.
To handle the return value of input
we need to add the following result to our action node in struts.xml
.
1 | <result name="input">/register.jsp</result> |
The above result node goes just after the success result node for the register action and before the closing of the action node.
Error Messages
So when validation fails and Struts 2 returns input, the Struts 2 framework will redisplay the register.jsp
. Since we used Struts 2 form tags, automatically Struts 2 will add the error messages. These error messages are the ones we specified in the addFieldError
method call. The addFieldError method takes two arguments. The first is the form field name to which the error applies and the second is the error message to display above that form field.
So the following addFieldError
method call:
1 | addFieldError("personBean.firstName", "First name is required.") |
will cause the message First name is required to be displayed above the firstName
field on the form.
如何修改自己form表单错误提示的css
在html的head里添加<s:head />