您的位置:首页 > 编程语言 > Java开发

struts2使用总结

2015-10-21 10:52 459 查看
          struts2是我最先使用的java MVC框架,在天朝也是很火热的,公司的项目也全部用struts2习惯了struts2的开发模式后,甚至感觉web后台开发就是struts2模式,因为估计本文会很长,所以会不间断地更新。首先,是struts2的官方api,他是放在struts官网中下载频道的fullleast那个包里(反正就是最大的那个包),下以后打开有个doc文件夹,里面还有个doc文件夹,打开里面的index.html即可。如图:



也可以直接在这里下载:Struct2 API下载

1,struts2安装

       我采用的是maven安装方法,请先参考J2ee开发环境的建立,然后是查看最新的struts2的版本是哪个,这个不用去struts2的官网,可以直接在mavenSearch中查看,输入struts2,下面显示的最新可用版本是2.3.24.1,好,在项目中的pom.xml中加入如下代码:

<dependency>
<groupId>org.apache.struts</groupId>
<artifactId>struts2-core</artifactId>
<version>2.3.24.1</version>
</dependency>


保存,在eclipse中就会自动下载文件并添加到项目路径,然后在项目中的web.xml中,加入如下代码

<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>
</filter-mapping>


即可安装成功。

2,struts.xml配置

     在src/main/resources(为什么是这个目录,请看maven教程)中新建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>

<constant name="struts.devMode" value="true"></constant>
<package name="felcx" extends="struts-default">
<action name="register*" class="action.RegisterAction" method="{1}">
            <result name="success">/register.jsp</result>
            <result name="input">/register.jsp</result>
            </action>
</package>
</struts>
个人很喜欢上面这种配置,如果访问的是registercreate,就会使用RegisterAction中的create方法,既没有难看的!,可以实现一个action处理多个不同的请求,关于这个配置,有大神写有文章:structs2.xml配置非常不错的

3,运行程序

      运行程序,如果是在eclipse中运行程序,可参考J2ee开发环境的建立,打开服务器后,在浏览器中输入localhost:8080/项目名/index.action,即可跳到index

二、Struts taglib

   Struts的tag是个好东西,运用好的话可以节省很多的开发时间。

首先是引用struts库,这里有个技巧,利用jsp的静态引用方法,引用一个base.jsp文件,如

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<!doctype html >
<html>
<head>

</head>
<body>

</body>
</html>


也可以加入js,css,等通用性的文件,这样就一劳永逸。

在其他jsp页面中,这样引用:

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@include file="Base.jsp" %>
<!doctype html >
即可使用通用性的功能。

1、<s:property>      输出服务端的值,即服务器,网页内容传值。

首先,服务器中的值需要有set,get方法(不能使用mMesss)这样一个小写后面一个大写的形式,因为eclipse生成set,get方法后是setMmEsss,非常不好看,并且structs识别不出,请使用最少2个小写开头的变量。如:

public class HelloAction extends BaseAction {
private MessageStore message;

public String execute() throws Exception{
message=new MessageStore("hello man");
logger.error("hello");
return SUCCESS;
}

public MessageStore getMessage() {
return message;
}

public void setMessage(MessageStore message) {
this.message = message;
}

}


那么在jsp中,可以这样用:

<h1><s:property value="message.msg"/></h1>


前提条件是在strut.xml中设置,并且请求hello.action.

'

<action name="hello" class="action.HelloAction">
<result name="success">/hello.jsp</result>
</action>


2、<s:url>    链接文件

   其实请求后台的action有个问题,就是根目录的路径,如果不用<s:url>就需要在网址前加上<%=request.getContextPath()%>,很蛋疼,有这个标签就简单多了,

无参数:

<a href="<s:url action='hello'/>">hello world</a>
有参数:

<s:url action="hello" var="helloLink">
<s:param name="userName">FelcxHuang</s:param>
</s:url>
<p><a href="${helloLink}">tiao zhuan</a></p>


3、<s:form>,<s:textfield>,<s:submit>     表单

    struct的这3个标签的提供了一个简单的,还过得去的表单,比如:

<s:form action="hello">
<s:textfield name="userName" label="Your name"/>
<s:submit value="Submit"/>
</s:form>


会解析出:

<table class="wwFormTable">
<tbody><tr>
<td class="tdLabel"><label for="hello_userName" class="label">Your name:</label></td>
<td><input name="userName" value="" id="hello_userName" type="text"></td>
</tr>

<tr>
<td colspan="2"><div align="right"><input id="hello_0" value="Submit" type="submit">
</div></td>
</tr>

</tbody></table>


很明显,代码量减少很多,其结果也基本过得去。

还有其他的标签,使用差不多,请参考api。

三、Struts session

session和request是常用的传值工具,request struts已经封装成上面讨论的传值方法了,而session,也封装得很好实用,在BaseAction中加入以下代码:

public class BaseAction extends ActionSupport implements SessionAware,ParameterNameAware{
public static final Logger logger=LogManager.getLogger(BaseAction.class);
public Map<String,Object> userSession;
@Override
public void setSession(Map<String, Object> arg0) {
// TODO Auto-generated method stub
userSession=arg0;
}
@Override
public boolean acceptableParameterName(String parameterName) {

boolean allowedParameterName=true;
if(parameterName.contains("session")||parameterName.contains("request")){
allowedParameterName=false;
}
return allowedParameterName;
}

}

其必须实现
SessionAware
接口,另外一个接口是基于安全考虑,把请求参数名带有的session或request的参数不理会,其他类只要继承这个类,就可以通过
userSession

使用了,如下所示:

private void incressHello(){
Integer count=(Integer)userSession.get(HELLO_COUNT);
if(null==count){
count=1;
}else{
count++;
}
userSession.put(HELLO_COUNT, count);
}

最后,关于struts生成的html美化,可以在<head>中用style重写以下内容:

.wwFormTable {}
.label {font-style:italic; }
.errorLabel {font-style:italic; color:red; }
.errorMessage {font-weight:bold; color:red; }
.checkboxLabel {}
.checkboxErrorLabel {color:red; }
.required {color:red;}
.tdLabel {text-align:right; vertical-align:top; }

最后的最后,sturts2外界裹贬不一,好的是其MVC思想非常彻底,也容易理解,不好的就是性能听说不是很好。这个主要看项目的用途,听说现在很多公司都用spring MVC,速度好像比struts快,但还是那句话,应该注意业务而非技术。

源代码链接

示例代码
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息