struts2框架的搭建


这段时间一直在用SSM,忽然想到SSH框架已经好长时间没用过了,不知道现在还能用不能,于是开始首先以struts入手,刚开始还比较顺利,到测试的时候,用eclipse自带的浏览器测试,怎么测怎么错,反复修改还是调用不成功。后来一不小心用极速浏览器测试一下,瞬间发现了问题,三下五除二搞定了,想想一下午大部分时间用在了这个上面,太浪费了。避免以后再犯类似的错误,写下来供后来参考。

  struts最主要的在配置上,先来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" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" 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>SSHdisplay-name>
  
  <filter>
      <filter-name>strutsfilter-name>
      <filter-class>
          org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
      filter-class>
      <init-param>   
             <param-name>configparam-name>   
           <param-value>struts-default.xml,struts-plugin.xml,resources/struts-config.xmlparam-value>   
      init-param> 
  filter>
  
  <filter-mapping>
      <filter-name>strutsfilter-name>
      <url-pattern>/*url-pattern>
  filter-mapping>
  
  
  <welcome-file-list>
    <welcome-file>login.htmlwelcome-file>
    <welcome-file>login.jspwelcome-file>
  welcome-file-list>
web-app>

web.xml中没有servlet的映射,这是因为struts的过滤器和拦截器里边已经对这些进行了处理,另外最值得注意的是:如果struts2的配置文件以struts.xml的文件名放在src目录下或者webinfo下,web.xml中filter中的就不需要了;如果想把sruts的配置文件放在自己建的文件夹下需要进行设置,放在src下的resource文件中,所以resources/struts-config.xml就是配置文件的位置

struts2的配置文件如下:

<?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>
      <constant name="struts.action.extension" value="do"/>
    <package name="struts" extends="struts-default">
        <action name="login" class="com.liusk.controller.UserAction" method="login">
            <result name="success">/index.jspresult>
        action>
    package>
struts>

这个配置是action的后缀,比如,form表单的action=login.do,package的name属性只是名字,没关系,extends说明该配置文件是struts-default配置文件的扩展类,因为struts2加载时默认首先加载struts-default.xml

action中的method是UserAction中login()方法。

后台action类:

package com.liusk.controller;

import com.opensymphony.xwork2.ActionSupport;

public class UserAction extends ActionSupport{
    
    public String login(){
        System.out.println("aaaaaa");
        return "success";
    }
}

这个action类处理后返回到index.jsp页面。

就是这么简单,费了我一下午。