新建一个Struts2工程,初步体验MVC
1、 新建工程
myelipse下新建一个叫struts2hello的web工程;
2、 导入jar包
将struts 2的jar包copy到web-inf/lib/目录下;
或者在工程的.classpath文件中加入:
[html]
<classpathentry kind="con" path="melibrary.com.genuitec.eclipse.struts2.myeclipse_struts21_core"/>
并刷新工程。
3、配置filter
修改web.xml文件,配置struts 2的核心filter;
[html]
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.filterdispatcher</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*.action</url-pattern>
</filter-mapping>
4、配置struts.xml
在src 目录下增加struts.xml配置文件;
[html]
<?xml version="1.0" encoding="utf-8" ?>
<!doctype struts public "-//apache software foundation//dtd struts configuration 2.1//en" "https://struts.apache.org/dtds/struts-2.1.dtd">
<struts>
<include file="struts-default.xml" />
<constant name="struts.i18n.encoding" value="utf-8" />
<package name="default" extends="struts-default">
<global-results>
<result name="login">login.</result>
<result name="index">index.jsp</result>
</global-results>
<action name="useraction" class="com.app.action.useraction" />
</package>
</struts>
5、 实现控制器
[java]
package com.app.hello;
import com.opensymphony.xwork2.action;
//pojo(plain object java object 低侵入式)
public class userworld implements action{
//获取页面上的控件,只需要要在这里注入对应的属性,提供setter和getter方法即可。(名称要完全一样)
private user user;//action类德每个属性对应于页面中的某个控件属性
private userdao userdao = new userdao();
// action默认执行方法
public string execute() {
if(!userdao.login(user.getusername(), user.getpassword())) {
actioncontext ac = actioncontext.getcontext();
ac.put("msg", "登陆信息有误"); //request.setattribute("", );
} else {
return "index"; //转发到逻辑视图对应的页面
}
return "login";
}
public user getuser() {
return user;
}
public void setuser(user user) {
this.user = user;
}
// https://localhost:8080/struts2helloworld/hello!aliasaction.action
public string aliasaction() {
name = "";
return "success";
}
}
6、 修改struts.xml文件
添加action的映射和逻辑视图转向,在<struts></struts>中添加如下内容;
[html]
<package name="default" extends="struts-default">
<action name="hello" class="com.app.hello.helloworld">
<result name="success">/helloworld.jsp</result>
</action>
</package>
7、 添加jsp视图层
取名helloworld.jsp
[html]
<%@ page contenttype="text/html; charset=utf-8" %>
<%@ taglib prefix="s" uri="/struts-tags" %>
<%@ page iselignored="false" %>
<!doctype html public "-//w3c//dtd html 4.01 transitional//en">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=gb2312" />
<title>say hello</title>
</head>
<body>
<h3>say "hello" to: </h3>
<s:property value="name"/> ${name}
<s:form action="hello">
name: <s:textfield name="user.username" />
<s:submit />
</s:form>
</body>
</html>