环境搭建
1 jar
2 web.xml
3 struts.xml
struts.xml(核心配置文件)
struts.properties(全局属性文件)
引入jar包
<properties>
<struts2.version>2.5.16</struts2.version>
</properties>
<version>${struts2.version}</version>
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.zking</groupId>
<artifactId>strutsmaven</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>strutsmaven Maven Webapp</name>
<url>http://maven.apache.org</url>
<properties>
<servlet.version>4.0.1</servlet.version>
<junit.version>3.8.1</junit.version>
<mysql.version>5.1.44</mysql.version>
<Struts2.version>2.5.16</Struts2.version>
</properties>
<dependencies>
<!-- junit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.struts/struts2-core -->
<dependency>
<groupId>org.apache.struts</groupId>
<artifactId>struts2-core</artifactId>
<version>${Struts2.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
<!-- servlet -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>${servlet.version}</version>
<scope>provided</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.version}</version>
</dependency>
</dependencies>
<build>
<finalName>strutsmaven</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.7.0</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
</plugins>
</build>
</project>
配置过滤器(web.xml)
配置struts2核心过滤器
<filter>
<filter-name>struts2</filter-name>
<filter-class>jar包</filter-class>
</filter>
配置中文乱码过滤器
struts.devMode
struts.configuration.xml.reload
先创建 util,entity,action这三个包
在util包中放入防中文乱码的工具类
EncodingFiter
package com.tang.util;
import java.io.IOException;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* 中文乱码处理
*
*/
@WebFilter(filterName = "encodingFiter",urlPatterns = "/*")
public class EncodingFiter implements Filter {
private String encoding = "UTF-8";// 默认字符集
public EncodingFiter() {
super();
}
public void destroy() {
}
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse res = (HttpServletResponse) response;
// 中文处理必须放到 chain.doFilter(request, response)方法前面
res.setContentType("text/html;charset=" + this.encoding);
if (req.getMethod().equalsIgnoreCase("post")) {
req.setCharacterEncoding(this.encoding);
} else {
// Map map = req.getParameterMap();// 保存所有参数名=参数值(数组)的Map集合
// Set set = map.keySet();// 取出所有参数名
// Iterator it = set.iterator();
// while (it.hasNext()) {
// String name = (String) it.next();
// String[] values = (String[]) map.get(name);// 取出参数值[注:参数值为一个数组]
// for (int i = 0; i < values.length; i++) {
// values[i] = new String(values[i].getBytes("ISO-8859-1"),
// this.encoding);
// }
// }
}
chain.doFilter(request, response);
}
public void init(FilterConfig filterConfig) throws ServletException {
String s = filterConfig.getInitParameter("encoding");// 读取web.xml文件中配置的字符集
if (null != s && !s.trim().equals("")) {
this.encoding = s.trim();
}
}
}
web.xml(配置过滤器)
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
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>Archetype Created Web Application</display-name>
<filter>
<filter-name>encodingFiter</filter-name>
<filter-class>com.tang.util.EncodingFiter</filter-class>
</filter>
<filter-mapping>
<filter-name>encodingFiter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>*.action</url-pattern>
</filter-mapping>
</web-app>
配置Struts配置文件struts.xml
struts-base.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.5//EN"
"http://struts.apache.org/dtds/struts-2.5.dtd">
<struts>
<!-- 开启开发者模式 -->
<constant name="struts.devMode" value="true"></constant>
<!-- 开启自动加载配置文件 -->
<constant name="struts.configuration.xml.reload" value="true"></constant>
<!--
name:表示包名
extends:继承
abstract:是否是抽象类
namespace:命名空间
-->
<package name="struts-base" extends="struts-default" abstract="true">
<global-allowed-methods>regex:.*</global-allowed-methods>
</package>
</struts>
struts.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.5//EN"
"http://struts.apache.org/dtds/struts-2.5.dtd">
<struts>
<include file="struts-base.xml"></include>
</struts>
开发
Action
1 不需要指定父类(ActionSupport)
2 业务方法的定义
public String xxx();//execute
3 Action是多例模式(注:在spring中的配置中一定要注意)
Action用来接收参数
在action包中创建一个 HelloStruts 类
HelloStruts
package com.tang.action;
/**
* 用于演示Action类
* @author tangxinlian
*
* 2020年7月17日上午11:21:44
*/
public class HelloStruts {
public String execute() {
System.out.println("hello struts");
return null;
}
}
把 HelloStruts这个 类 配置一下
struts-hello
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.5//EN"
"http://struts.apache.org/dtds/struts-2.5.dtd">
<struts>
<package name="struts-hello" extends="struts-base">
<action name="helloAction" method="execute" class="com.tang.action.HelloStruts" ></action>
</package>
</struts>
在把struts-hello配置到struts中
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.5//EN"
"http://struts.apache.org/dtds/struts-2.5.dtd">
<struts>
<include file="struts-base.xml"></include>
<include file="struts-hello.xml"></include>
</struts>
先在浏览器中输入http://localhost:8080/strutsmaven/helloAction.action
后就可以在Eclipse中看到输出的结果
参数赋值
1 Action中定义属性,并提供get/set方法
userName, getUserName/setUserName
2 ModelDriven
返回实体,不能为null,不需要提供get/set方法
3 ModelDriven返回实体和Action中属性重名,ModelDriven中优先级更高
注:ognl,ActionContext学完就知道了
与J2EE容器交互
非注入
1 耦合
ServletActionContext
2 解耦(建立使用解耦模式)
ActionContext
注入
1 耦合
ServletRequestAware/ServletResponseAware
2 解耦
核心文件配置
1 include
file
2 package
name
extends
namespace
abstract
3 action
name:helloAction,helloAction_*
class
method:execute,{1}
注1:动态方法调用,新版本中已禁用,可自行开启或关闭
注2:子控制器的访问路径:名称空间+"/"+子控制器名字_xxx+".action"
4 result
name
type:dispatcher|redirect
User(实体类)
package com.tang.entity;
import java.io.Serializable;
public class User implements Serializable{
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;
}
@Override
public String toString() {
return "User [username=" + username + ", password=" + password + "]";
}
public User() {
super();
}
public User(String username, String password) {
super();
this.username = username;
this.password = password;
}
}
UserAction
package com.tang.action;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ModelDriven;
import com.tang.entity.User;
public class UserAction implements ModelDriven<User>{
private User user = new User();
//在action中定义的刷新必须定义该属性的set和get方法
private String username;
@Override
public User getModel() {
// TODO Auto-generated method stub
return user;
}
//非注入耦合方式,和servlet关系紧密
private HttpServletRequest req;
private HttpServletResponse resp;
/*//注入耦合方式 ServletRequestAware,ServletResponseAware
@Override
public void setServletResponse(HttpServletResponse response) {
this.resp = response;
}
@Override
public void setServletRequest(HttpServletRequest request) {
this.req = request;
}*/
public String login() {
/*req = ServletActionContext.getRequest();
resp = ServletActionContext.getResponse();*/
//非注入解耦方式
/*ActionContext context = ActionContext.getContext();
Map<String, Object> req = context.getContextMap();*/
if("zhangsan".equals(user.getUsername())&&"123456".equals(user.getPassword())) {
// req.put("username", user.getUsername());
// req.setAttribute("username", user.getUsername());
return "success";
}else {
return "error";
}
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
}
struts-user.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.5//EN"
"http://struts.apache.org/dtds/struts-2.5.dtd">
<struts>
<package name="struts-user" extends="struts-base">
<action name="userAction_*" class="com.tang.action.UserAction"
method="{1}">
<!--
name:跳转路径
type:默认是转发=dispatcher,重定向=redirect
-->
<result name="success" type="dispatcher">/index.jsp</result>
<result name="error" type="redirect">/error.jsp</result>
</action>
</package>
</struts>
struts.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.5//EN"
"http://struts.apache.org/dtds/struts-2.5.dtd">
<struts>
<include file="struts-base.xml"></include>
<include file="struts-hello.xml"></include>
<include file="struts-user.xml"></include>
</struts>
jsp
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>Insert title here</title>
</head>
<body>
<form action="userAction_login.action" method="post">
<label>用户姓名:</label><input type="text" name="username" /><br/>
<label>用户密码:</label><input type="text" name="password" /><br/>
<input type="submit" value="登 陆">
</form>
</body>
</html>
index.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>Insert title here</title>
</head>
<body>
<h1>首页,您好!${username }</h1>
</body>
</html>