我是靠谱客的博主 激情白云,最近开发中收集的这篇文章主要介绍Struts2使用注解,完成请求响应,实现零配置,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

Struts2使用注解,完成请求响应,实现零配置

利用myeclipse2013搭建struts2,spring集成环境

操作步骤:

  1. 新建项目
    这里写图片描述
  2. 加入struts2的支持, 加入spring的支持
    这里写图片描述
  3. 整个程序的结构
    这里写图片描述

1、导入相关jar包
使用myeclipse自带的jar包
这里写图片描述

2、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" version="3.0">
<display-name>struts2</display-name>
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
<init-param>
<param-name>actionPackages</param-name>
<param-value>com.system</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>


actionPackages
com.system

这个参数指明struts2的action类所在的包。这是我的程序结构。
这里写图片描述

3、struts.xml的配置

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd">
<struts>
<constant name="struts.devMode" value="true" />
<constant name="struts.i18n.encoding" value="UTF-8" />
<constant name="struts.enable.DynamicMethodInvocation" value="true" />
<constant name="struts.objectFactory" value="spring" />
<constant name="struts.action.extension" value="action,do,htm" />
<constant name="struts.configuration.xml.reload" value="true" />
<constant name="struts.serve.static.browserCache" value="false" />
<!--
要求Action的命名必须以“Action”为后缀 -->
<!--
<constant name="struts.convention.action.suffix" value="Action"/> -->
<!--
要求Action必须放到action、actions、struts、struts2包中 -->
<!--
<constant name="struts.convention.package.locators" value="action,actions,struts,struts2"/> -->
<!--
Struts2约定限制结果页面必须放到/WEB-INF/content/目录中 -->
<!--
<constant name="struts.convention.result.path" value="/pages/"/> -->
</struts>

4、ApplicationContext.xml的配置

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:annotation-config/>
<context:component-scan base-package="com.system" />
</beans>

5、UserAction.java

package com.system.action;
import java.util.Map;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.interceptor.ApplicationAware;
import org.apache.struts2.interceptor.ParameterAware;
import org.apache.struts2.interceptor.RequestAware;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;
import org.apache.struts2.interceptor.SessionAware;
import org.apache.struts2.util.ServletContextAware;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import com.opensymphony.xwork2.ActionSupport;
import com.system.service.UserManager;
@SuppressWarnings("serial")
@Controller("userAction")
@Scope("prototype")
@ParentPackage("struts-default")
@Namespace("/app")
@Action(value = "userAction", results = {
@Result(name = "add", location = "/pages/user/add.jsp"),
@Result(name = "delete", location = "/pages/user/delete.jsp"),
@Result(name = "change", location = "/pages/user/change.jsp"),
@Result(name = "find", location = "/pages/user/find.jsp") })
public class UserAction extends ActionSupport implements ParameterAware,
RequestAware, SessionAware, ApplicationAware, ServletContextAware,
ServletRequestAware, ServletResponseAware {
// -----------业务的操作方法-----------------------
@Action(value="add", results = {
@Result(name = "add", location = "/pages/user/add.jsp")})
public String addUser() {
System.out.println("***********add*****************");
return "add";
}
public String deleteUser() {
System.out.println("***********delete**************");
return "delete";
}
public String changeUser() {
System.out.println("***********change**************");
return "change";
}
public String findUser() {
System.out.println("***********find*****************");
return "find";
}
@Override
public String execute() {
System.out.println("***********execute*****************");
return NONE;
}
// ------------注入业务类--------------------------
// ---------------Getter,Setter------------------
protected Map<String, String[]> parameters;
protected Map<String, Object> request;
protected Map<String, Object> session;
protected Map<String, Object> application;
protected ServletContext servletContext;
protected HttpServletRequest httpServletRequest;
protected HttpServletResponse httpServletResponse;
public void setParameters(Map<String, String[]> parameters) {
this.parameters = parameters;
}
public void setRequest(Map<String, Object> request) {
this.request = request;
}
public void setSession(Map<String, Object> session) {
this.session = session;
}
public void setApplication(Map<String, Object> application) {
this.application = application;
}
public void setServletContext(ServletContext servletContext) {
this.servletContext = servletContext;
}
public void setServletRequest(HttpServletRequest httpServletRequest) {
this.httpServletRequest = httpServletRequest;
}
public void setServletResponse(HttpServletResponse httpServletResponse) {
this.httpServletResponse = httpServletResponse;
}
public HttpServletRequest getHttpServletRequest() {
return this.httpServletRequest;
}
public void setHttpServletRequest(HttpServletRequest httpServletRequest) {
this.httpServletRequest = httpServletRequest;
}
public HttpServletResponse getHttpServletResponse() {
return this.httpServletResponse;
}
public void setHttpServletResponse(HttpServletResponse httpServletResponse) {
this.httpServletResponse = httpServletResponse;
}
public Map<String, String[]> getParameters() {
return this.parameters;
}
public Map<String, Object> getRequest() {
return this.request;
}
public Map<String, Object> getSession() {
return this.session;
}
public Map<String, Object> getApplication() {
return this.application;
}
public ServletContext getServletContext() {
return this.servletContext;
}
//--------------test------------------------
public void setManager(UserManager manager) {
// TODO 自动生成的方法存根
}
public String list() {
// TODO 自动生成的方法存根
System.out.println("------list---------");
return SUCCESS;
}
}

6 、UserManager.java

package com.system.service;
import org.springframework.stereotype.Service;
@Service("userManager")
public class UserManager {
}

7、OrderAction.java

package com.system.action;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.stereotype.Controller;
import com.opensymphony.xwork2.ActionSupport;
@SuppressWarnings("serial")
@Namespace("/order")
@ParentPackage("struts-default")
@Controller("orderAction")
public class OrderAction extends ActionSupport{
@Action(value="add", results={
@Result(name="success", location="/index.jsp"),
@Result(name="input", location="/add.jsp")})
public String add() {
System.out.println("add()");
return SUCCESS;
}
@Action(value="mod", results={@Result(name="success", location="/index.jsp")})
public String mod() {
System.out.println("mod()");
return SUCCESS;
}
@Action(value="del", results={@Result(name="success", location="/index.jsp")})
public String del() {
System.out.println("del()");
return SUCCESS;
}
}

8.struts2利用Junit测试action
TestStruts2.java

package com.struts2.test;
import org.apache.struts2.StrutsSpringTestCase;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.testng.annotations.Test;
import com.opensymphony.xwork2.ActionProxy;
import com.system.action.UserAction;
import com.system.service.UserManager;
public class TestStruts2 extends StrutsSpringTestCase{
private ActionProxy proxy;
private UserAction action;
private UserManager manager;
@Override
public void setUp() throws Exception{
super.setUp();
//必须

ApplicationContext
ctx = new ClassPathXmlApplicationContext(new String[]{"applicationContext.xml"});
manager = (UserManager)ctx.getBean("userManager");
}
@Test
public void testAction1() throws Exception{
proxy = this.getActionProxy("/userAction.do");
action = (UserAction)proxy.getAction();
action.setManager(manager);
String result = action.list();
assertEquals("success",result);
}
@Test
public void testAction2() throws Exception{
proxy = this.getActionProxy("/order/mod.do");
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO 自动生成的方法存根
}
}
9、log4j的配置
log4j.properties

这里写代码片

### direct log messages to stdout ###
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
### direct messages to file hibernate.log ###
#log4j.appender.file=org.apache.log4j.FileAppender
#log4j.appender.file.File=hibernate.log
#log4j.appender.file.layout=org.apache.log4j.PatternLayout
#log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
### set log levels - for more verbose logging change 'info' to 'debug' ###
log4j.rootLogger=warn, stdout
#log4j.logger.org.hibernate=info
#log4j.logger.org.hibernate=debug
### log HQL query parser activity
#log4j.logger.org.hibernate.hql.ast.AST=debug
### log just the SQL
#log4j.logger.org.hibernate.SQL=debug
### log JDBC bind parameters ###
#log4j.logger.org.hibernate.type=info
#log4j.logger.org.hibernate.type=debug
### log schema export/update ###
#log4j.logger.org.hibernate.tool.hbm2ddl=debug
### log HQL parse trees
#log4j.logger.org.hibernate.hql=debug
### log cache activity ###
#log4j.logger.org.hibernate.cache=debug
### log transaction activity
#log4j.logger.org.hibernate.transaction=debug
### log JDBC resource acquisition
#log4j.logger.org.hibernate.jdbc=debug
### enable the following line if you want to track down connection ###
### leakages when using DriverManagerConnectionProvider ###
#log4j.logger.org.hibernate.connection.DriverManagerConnectionProvider=trace

重点内容
使用Struts2的注解功能,包名一定要按照上述程序结构去创建,web.xml加入actionPackages的初始化参数,

<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
<init-param>
<param-name>actionPackages</param-name>
<param-value>com.system</param-value>
</init-param>
</filter>

与spring集成时,把action纳入spring的管理范围,要在struts2的配置文件加入,

<constant name="struts.objectFactory" value="spring" />

否则注解失效,提示没有action map的异常。

最后

以上就是激情白云为你收集整理的Struts2使用注解,完成请求响应,实现零配置的全部内容,希望文章能够帮你解决Struts2使用注解,完成请求响应,实现零配置所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(38)

评论列表共有 0 条评论

立即
投稿
返回
顶部