学习struts2的第一个程序,这里只会涉及到简单的代码编写。
一、引入struts2支持的jar包,在web.xml中配置struts2的拦截器。
<?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" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0"> <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>*.action</url-pattern> </filter-mapping> </web-app>
二、定义一个简单的首页index.jsp,用于跳转到struts的Action。
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>Insert title here</title> </head> <body> <h3><a href="hello.action">Hello World</a></h3> </body> </html>
三、定义一个Action,这是struts中处理的最小单元。
package com.huhx.struts; import com.opensymphony.xwork2.ActionSupport; public class HuhxAction extends ActionSupport { private static final long serialVersionUID = 1L; @Override public String execute() throws Exception { System.out.println("hello world."); return SUCCESS; } }
四、在src下创建的struts.xml中定义acton映射
<?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> <package name="default" namespace="/" extends="struts-default"> <action name="hello" class="com.huhx.struts.HuhxAction"> <result name="success">/huhx.jsp</result> </action> </package> </struts>
五、定义一个action返回的页面huhx.jsp。
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>Insert title here</title> </head> <body> <h2>Hello huhx.</h2> </body> </html>
原文:http://www.cnblogs.com/huhx/p/baseStruts1.html