Struts2实现简单输入姓名后给出欢迎信息

首先建立项目,在lib目录下导入Struts2所需要的jar包:

两个jsp页面:index.jsp:用户输入你的名字。msg.jsp:输入您好,名字信息。
index.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
   
    <title>My JSP 'index.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">   
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
  </head>
 
  <body>   
         <form action="hello2.action" type="post">
    请输入你的大名:<input type="text" name="uname" value="" /><br>
    <input type="submit" value="确定" />
    </form>
  </body>
</html>


msg.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
   
    <title>My JSP 'index.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">   
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
  </head>
 
  <body>
    ${msg }
  </body>
</html>


HelloAction2.java
package com.topnet.af.Action;

public class HelloAction2 {

private String uname;
private String msg;

public String  sayHello() {
msg = "你好:"+uname;
return "success";
}

public String getUname() {
return uname;
}

public void setUname(String uname) {
this.uname = uname;
}

public String getMsg() {
return msg;
}

public void setMsg(String msg) {
this.msg = msg;
}
}


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>
    <!-- 命名空间 -->
    <package name="struts2" extends="struts-default">
<action name="hello2" class="com.topnet.af.Action.HelloAction2" method="sayHello">
<result name="success">/msg.jsp</result>
</action>
    </package>
</struts>

启动Tomcat服务器,运行即可

你可能感兴趣的:(java,apache,tomcat,jsp,struts)