struts2学习笔记(一)

1.搭建第一个struts2 app.

  web.xml 

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <web-app version="2.5" 
 3     xmlns="http://java.sun.com/xml/ns/javaee" 
 4     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
 5     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
 6     http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
 7   <welcome-file-list>
 8     <welcome-file>index.jsp</welcome-file>
 9   </welcome-file-list>
10   
11   <filter>
12         <filter-name>struts2</filter-name>
13         <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
14     </filter>
15 
16     <filter-mapping>
17         <filter-name>struts2</filter-name>
18         <url-pattern>/*</url-pattern>
19     </filter-mapping>
20     
21 </web-app>

  注:struts1框架由servlet启动,strust2框架由filter启动

 struts.xml

 1 <?xml version="1.0" encoding="UTF-8" ?>
 2 <!DOCTYPE struts PUBLIC
 3     "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
 4     "http://struts.apache.org/dtds/struts-2.0.dtd">
 5 
 6 <struts>
 7     <!-- Add packages here -->
 8     <package name="alibaba" extends="struts-default" namespace="/alibaba">
 9        <action name="helloWorld" method="excute" class="com.alibaba.struts2.HelloWorld">
10           <result name="success">/WEB-INF/page/helloWorld.jsp</result>
11        </action>
12     </package>
13 </struts>

注:extends="struts-default",是关键。使用struts2框架核心功能,比如说文件上传等。需要继承struts2-default 这个包

在struts-default.xml文件中可以看到

1     <package name="struts-default" abstract="true">
2     ....
3      <interceptor name="alias" class="com.opensymphony.xwork2.interceptor.AliasInterceptor"/>
4     .....

拦截器是struts的核心。

action

 1 package com.alibaba.struts2;
 2 
 3 public class HelloWorld
 4 {
 5     
 6     private String msg;
 7 
 8     public String getMessage()
 9     {
10         return msg;
11     }
12     
13     public String excute()
14     {
15         this.msg = "Hello,This is my frist struts2 app.";
16         return "success";    
17     }
18 
19 }

jsp

 1 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
 2 
 3 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
 4 <html>
 5   <head>
 6     <title>My JSP 'helloWorld.jsp' starting page</title>
 7     
 8     <meta http-equiv="pragma" content="no-cache">
 9     <meta http-equiv="cache-control" content="no-cache">
10     <meta http-equiv="expires" content="0">    
11     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
12     <meta http-equiv="description" content="This is my page">
13     <!--
14     <link rel="stylesheet" type="text/css" href="styles.css">
15     -->
16 
17   </head>
18   
19   <body>
20       ${message}
21   </body>
22 </html>

注:EL表达式中的参数和action中的getMessage()中的Message要一致。

原文地址:https://www.cnblogs.com/yiliweichinasoft/p/3594961.html