【SSH框架实现】Struts2【1】 最简单完整实例- IDEA

来源:互联网 发布:nginx指定ip访问服务器 编辑:程序博客网 时间:2024/05/17 12:50

工具IDEA 

1.首先去Struts2官网下载jar包

http://struts.apache.org/download.cgi#struts2512


这几个是常用的。


找个文件夹存放这些jar包然后 在IDEA新建工程,依次选择。然后OK


可以看到IDEA在src 里自动给我们建立了struts.xml 以及自动在web/WEB-INF里新建了web.xml


都不用进行设置了,也就是说直接写代码就可以了。

打开struts.xml

写入:

<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE struts PUBLIC        "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"        "http://struts.apache.org/dtds/struts-2.3.dtd"><struts>    <package name="p1" extends="struts-default">        <action name="helloWorld" class="com.struts2.test.HelloWorldAction" method="sayHello">            <result name="success">/success.jsp</result>            <result name="error">/error.jsp</result>        </action>    </package></struts>

意思是建立一个包,包里储存一个action,名称是helloWorld 并且调用com.struts2.test.HelloWorldAction 类的方法 sayHello

如果给的返回值是success ,则给出结果/success.jsp,如果是error则返回/error.jsp


建立这三个jsp文件

index.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %><html>  <head>    <title>$Title$</title>  </head>  <body><a href="helloWorld.action">按此!</a>  </body></html>

success.jsp则是直接写一行成功,error.jsp直接写一行失败即可。


现在开始写java代码

建立com.struts2.test.HelloWorldAction 类的方法 sayHello

在这个类里写

package com.struts2.test;public class HelloWorldAction {    public String sayHello(){        return "error";    }}


这里锁定的返回是error。

运行tomcat

试试效果:



成功实现!


MyEclipse需要自己创建web.xml以及struts.xml

方法一样。