程序员

Java框架之Struts2(基本配置)

2017-11-06  本文已影响91人  Miss_差不多

什么是struts2

下图是一个请求在Struts框架中的工作原理图


Struts2核心.png

建立一个Struts框架的基本流程 (先导包 13个)

1.先在wed.xml中配置核心过滤器
    <filter>
        <filter-name>struts</filter-name>
        <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>struts</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
2.建立struts.xml(xml的名字)
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
    "http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
<!--注册LoginAction  包上继承struts的默认包:struts-default"-->
<package name="aaa" extends="struts-default">
<!--action是注册类   name不能随便写  是指前台提交地址   会在form表单中的action中用到     
class指定的是全类名 目的是快速找到当前类  -->
<action name="login" class="com.lanou3g.entity.LoginAction">
  <result name="success">/success.jsp</result>
</action>

</package>
</struts>
3.建立实体类
写相应的jsp页面

注意事项:

  1. web.xml 中过滤器的名称是可以随便写 filter-name.
    2.在struts.xml中 action中的全类名 必须统一 这个struts.xml也必须是这个名字不能变.
    3.在建立的Action中有一个方法名必须是execute 这个是struts中默认的执行方法.
    4.如果shutdown端口 不能瞎改 否则服务器启动不了.
    5.核心过滤器必须有 在web.xml中.

相对路径 绝对路径

相对路径:前台路径的参照路径是当前Web服务器的根路径(http://127.0.0.1:8080

),后台路径的参照路径是当前Web应用的根路径【Web应用的根路径即WebRoot】

优先级 开发常使用struts.xml

因为是基于标签的开发 应用灵活

扩展名为例

文件优先级:struts.xml< struts.properties<web.xml

method属性

前台代表的是提交方式
后台代表提交方法(在不使用默认方法是一定要写method属性)

type属性

1.默认转发:dispatcher 地址自动跳转 参数自动携带
2.redirect 重定向
需要配置参数 获取值的时候用
在跳转的页面中需要用param来接收值
通过参数指定提交地址 通过参数指定传参

 <result type="redirect">
  <param name="location">second</param>
  <param name="username">${username}</param>
  <param name="password">${password}</param>
  </result>

3.redirectAction 重定向到Action(服务器内部跳转)

<result type="redirectAction">
  <param name="actionName">second</param>
  <param name="username">${username}</param>
  <param name="password">${password}</param>
  </result>

4.chain 转发到action 1.jsp转发到Action 2.action转发到action
通过参数(actionName)指定提交到另一个action

<action name="login" class="com.lanou3g.entity.LoginAction">
<result type="chain">
param name="actionName">second</param>
  </result>
  </action>
 <action name="second">
  <result>/success.jsp</result>
</action>

小结: 所有的转发都不需要写参数 只写跳转路径
所有的重定向需要些参数 并且指定跳转路径

会持续更新

上一篇下一篇

猜你喜欢

热点阅读