在上一篇文章中,我们一起了解了一下struts2的工作机制原理,接下来让我们进行一下简单应用的开发
(一)配置环境
1、建立web项目
2、导入jar包
其中struts2中有很多jar包,我们不需要全部引用,因为很多jar涉及第三方jar包。如果我们只导入struts里面的而没有导入第三方jar包所依赖的jar包,就会报错,影响开发
3、配置web.xml
- <?xml version="1.0" encoding="UTF-8"?>
- <web-app version="2.5"
- xmlns="http://java.sun.com/xml/ns/javaee"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
- http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
-
-
- <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>
- <!-- <dispatcher>REQUEST</dispatcher>
- <dispatcher>FORWARD</dispatcher> -->
- </filter-mapping>
- <display-name></display-name>
- <welcome-file-list>
- <welcome-file>index.jsp</welcome-file>
- </welcome-file-list>
- </web-app>
4、配置struts.xml
- <?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>
- <package name="StrutsTest" namespace="/Test" extends="struts-default">
- <action name="helloworld" class="/StrutsTest/src/Test/HelloWorld" method="execute">
- <result name="success">/WEB-INF/jsp/hello.jsp</result>
- </action>
- </package>
- </struts>
配置完成后,启动项目,没有报异常则证明环境搭建成功。
(二)进行简单应用开发
1、对应的Action类
- package Test;
- public class HelloWorld {
- private String info;
-
- public String getInfo(){
- return info;
- }
-
- public String execute(){
- info="电话:18333617223"+"\n"+"姓名:李卫中";
- return "success";
- }
- }
2、配置对应的jsp视图
- <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
- <%
- String path = request.getContextPath();
- String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
- %>
- <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
- <html>
- <head>
- <base href="<%=basePath%>">
- <title>struts</title>
- <meta http-equiv="pragma" content="no-cache">
- <meta http-equiv="cache-control" content="no-cache">
- <meta http-equiv="expires" content="0">
- <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
- <meta http-equiv="description" content="This is my page">
- </head>
- <body>
- ${info} <br>
- </body>
- </html>
(三)运行:
简单应用开发成功
小结:
struts2在环境配置上相对简单,开发应用上也比较容易,接下来,我会就struts与struts2的相关学习做出比较,对比一下struts与struts2的应用方向与应用场景,以及两者之间的异同点。