(1)下面是转自慕课网的一个MVC模式的介绍:
(2)第一个struts2的案例步骤:
(3)接下来就需要进行创建一个web项目,然后引入相关的jar包,再build path(还缺少一个javassist-3.11.0.GAjar包)。
(4)接下来就是在web.xml中进行配置:
<?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" 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>HelloWorld</display-name>
<!-- 接下来就是进行配置,配置一个过滤器 ,filter-name表示自定义的过滤器的名称。filter-class:过滤器需要实现Filter接口-->
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<!-- 配置过滤器的映射,filter-name和上面的名称是一样的,url-pattern表示过滤器要过滤的路径,在这里是所有路径都要过滤。 -->
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
</web-app>
(5)创建一个Action类:
package com.imooc.action;
import com.opensymphony.xwork2.ActionSupport;
public class HelloWorldAction extends ActionSupport {
//在struts2中有一个默认的方法就是execute,在不指定方法名的时候用。
@Override
public String execute() throws Exception {
System.out.println("执行Action");
//调到成功页面
return SUCCESS;
}
}
(6)然后就是对核心文件struts.xml中进行配置,
上面解释错了,是因为对应的是result.jsp,所以创建一个result.jsp页面。
(8)页面如下:
<%@ 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>
hahah
</body>
</html>
(9)结果如下:
(10)知识扩展(转自慕课网)
(11)下面是struts的配置文件,可以在struts.xml中直接用constant写,不必再写struts.properties文件中,这两个文件可以放在src的目录下。
(12)深入了解struts2
1.访问servlet API
2.Action的搜索顺序
2.1这是感叹号的方式(这里怒推荐用这种方式)
2.2通配符的方式(建议使用)
也可以有下面的方式:
3.指定多个配置文件
4.默认Action
5.struts2的后缀
6.接收参数
6.1使用Action的属性接收参数
创建一个登陆界面:
再创建一个Action,这里创建一个LoginAction,
表示返回成功的时候的界面,
然后需要在配置文件进行配置:
6.2使用domainmodel方式
这时需要创建一个User类,在User类中定义属性,在LoginAction类中:
使用这种,还要注意在login.jsp页面中改成如:name=user.username
6.3使用ModelDriven方式(推荐)
这时候将User的get,set去掉,然后实例化,
login.jsp页面:
假如用户有一个数据集,有很多的书,
结果:
假如它是一个User对象:
这时候:
7.处理结果类型
8.处理结果类型