Java Web学习笔记(七)struts2

FilterDispatcher是早期struts2的过滤器,后期的都用StrutsPrepareAndExecuteFilter了,如 2.1.6、2.1.8。StrutsPrepareAndExecuteFilter名字已经很能说明问题了,prepare与execute,前者表示准备,可以说是指filter中的init方法,即配制的导入;后者表示进行过滤,指doFilter方法,即将request请求,转发给对应的 action去处理。
FilterDispatcher是struts2.0.x到2.1.2版本的核心过滤器.!
StrutsPrepareAndExecuteFilter是自2.1.3开始就替代了FilterDispatcher的.!
这样的改革当然是有好处的.!
为什么这么说.? 应该知道如果我们自己定义过滤器的话, 是要放在strtus2的过滤器之前的, 如果放在struts2过滤器之后,你自己的过滤器对action的过滤作用就废了,不会有效!除非你是访问jsp/html!
那我现在有需求, 我必须使用Action的环境,而又想在执行action之前拿filter做一些事, 用FilterDispatcher是做不到的.!
那么StrutsPrepareAndExecuteFilter可以把他拆分成StrutsPrepareFilter和StrutsExecuteFilter,可以在这两个过滤器之间加上我们自己的过滤器.!
给你打个比喻, 现在有病人要做手术, 现在struts2要做两件事, 搭病床(环境),执行手术.! 那么打麻药的工作呢.? 不可能要病人站着打吧, 所以必须有病床的环境,打完麻药之后再动手术.! 这个比喻非常形象了.!

加减乘除实例:

CalculatorAction.java

package action;

import java.util.Map;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;

import entity.Cal;

@SuppressWarnings("serial")
public class CalculatorAction extends ActionSupport implements ModelDriven<Cal> {
	private Cal cal = new Cal();
	
	public String add() {
		ActionContext act = ActionContext.getContext();
		@SuppressWarnings("unchecked")
		Map<String,Object> req = (Map<String, Object>) act.get("request");
		int result = cal.getA() + cal.getB();
		req.put("result",result);
		return SUCCESS;
	}
	
	public String sub() {
		ActionContext act = ActionContext.getContext();
		@SuppressWarnings("unchecked")
		Map<String,Object> req = (Map<String, Object>) act.get("request");
		int result = cal.getA() - cal.getB();
		req.put("result",result);
		return SUCCESS;
	}
	
	public String mul() {
		ActionContext act = ActionContext.getContext();
		@SuppressWarnings("unchecked")
		Map<String,Object> req = (Map<String, Object>) act.get("request");
		int result = cal.getA() * cal.getB();
		req.put("result",result);
		return SUCCESS;
	}
	
	public String div() {
		ActionContext act = ActionContext.getContext();
		@SuppressWarnings("unchecked")
		Map<String,Object> req = (Map<String, Object>) act.get("request");
		int result = cal.getA() / cal.getB();
		req.put("result",result);
		return SUCCESS;
	}
	
	@Override
	public Cal getModel() {
		// TODO Auto-generated method stub
		return cal;
	}

}

Cal.java

package entity;

public class Cal {
	private Integer a;
	private Integer b;
	
	public Integer getA() {
		return a;
	}

	public void setA(Integer a) {
		this.a = a;
	}

	public Integer getB() {
		return b;
	}

	public void setB(Integer b) {
		this.b = b;
	}
}

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="ex1" extends="struts-default" namespace="/">
		<action name="helloWorld" class="ex1.HelloWorldAction">
			<result>/HelloWorld.jsp</result>
		</action>
		<!-- 
		<action name="add" class="ex1.AddAction">
			<result>/calculator.jsp</result>
		</action>
		<action name="sub" class="ex1.SubAction">
			<result>/calculator.jsp</result>
		</action>
		<action name="mul" class="ex1.MulAction">
			<result>/calculator.jsp</result>
		</action>
		<action name="div" class="ex1.DivAction">
			<result>/calculator.jsp</result>
		</action>
		 -->
		<action name="add" class="action.CalculatorAction" method="add">
			<result>/calculator.jsp</result>
		</action>
		<action name="sub" class="action.CalculatorAction" method="sub">
			<result>/calculator.jsp</result>
		</action>
		<action name="mul" class="action.CalculatorAction" method="mul">
			<result>/calculator.jsp</result>
		</action>
		<action name="div" class="action.CalculatorAction" method="div">
			<result>/calculator.jsp</result>
		</action>
	</package>
</struts>

web.xml

<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>/*</url-pattern>
</filter-mapping>

calculator.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<%String path=request.getContextPath(); %>
<html>
  <head>
    <title>计算器</title>
    <script>
    function cal(obj) {
    	document.myform.action=obj;
    	document.myform.submit();
    }
    </script>
  </head>
  
  <body>
  <form action="" method="post"  name="myform">
    第一个数:<input type="text" name="a" value="${param.a }"><br />
    第二个数:<input type="text" name="b" value="${param.b }"><br />
    结    果:<input type="text" name="result" value="${requestScope.result }" /><br />
    <input type="button" value=" + " οnclick="cal('add.action')" />
    <input type="button" value=" - " οnclick="cal('sub.action')" />
    <input type="button" value=" * " οnclick="cal('mul.action')" />
    <input type="button" value=" / " οnclick="cal('div.action')" />
  </form>
  </body>
</html>

用户登录实例:

LoginAction.java

package action;

import java.util.Map;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;

import entity.UserInfo;

@SuppressWarnings("serial")
public class LoginAction extends ActionSupport implements ModelDriven<UserInfo> {
	UserInfo user = new UserInfo();
	
	public String login() throws Exception {
		ActionContext act = ActionContext.getContext();
		@SuppressWarnings("unchecked")
		Map<String,Object> req = (Map<String, Object>) act.get("request");
		Map<String,Object> session = act.getSession();
		if(user.getName().equals("张明")&&user.getPassword().equals("123456")) {
			session.put("loginUser", user.getName());
			return SUCCESS;
		}else {
			req.put("message", "用户名或密码有误!");
			return INPUT;
		}
	}
	
	@Override
	public UserInfo getModel() {
		// TODO Auto-generated method stub
		return user;
	}
}

UserInfo.java

package entity;

public class UserInfo {
	String name;
	String password;
	
	public String getName() {
		return name;
	}
	
	public void setName(String name) {
		this.name = name;
	}
	
	public String getPassword() {
		return password;
	}
	
	public void setPassword(String password) {
		this.password = password;
	}
	
}

struts.xml部分代码:

<action name="login" class="action.LoginAction" method="login">
	<result name="success">/index.jsp</result>
	<result name="input">/login.jsp</result>
</action>

login.jsp

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%
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>
    <title>用户登录</title>
    <script>
    var xmlhttp;
    
    function createxmlhttp() {
    	if(window.ActiveXObject) {
    		xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    		//xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
    		//alert("IE");
    	}else if(window.XMLHttpRequest) {
    		xmlhttp = new XMLHttpRequest();
    		//alert("firefox");
    	}
    }
    
    function checkRp() {
    	var uname = document.myform.name.value;  
		var unameUTF = encodeURI(uname);  
		 //var unameUTF = encodeURI(encodeURI(uname));  
		var url="/JavaWebTest/servlet/CheckRPServlet?name=" + unameUTF;  
    	createxmlhttp();
    	xmlhttp.onreadystatechange = back;
    	xmlhttp.open("GET", url, true);
    	xmlhttp.send(null);
    }
    
    function back() {
    	if(xmlhttp.readyState==4) {
    		if(xmlhttp.status==200) {
    			if(xmlhttp.responseText=="failure") {
    				alert("用户名已经存在!");
    			}else {
    				alert("可以使用此用户名!");
    			}
    		}
    	}
    }
    </script>
    <style>
    	#container {
    		width:800px;
    		margin:auto;
    	}
    	table {
    		width:400px;
    		margin:auto;
    		text-align: center;
    		border-collapse:collpase;
    	}
    	table tr td {
    	}
    	.c1{
    		width:70px;
    	}
    	.c2{
    		width:180px;
    	}
    </style>
  </head>
  
  <body>
	<div id="container">
	<form action="login" name="myform" method="post" >
	<table>
		<tr>
			<td class="c1">用户名:</td>
			<td class="c2"><input type="text" name="name" /></td>
			<td><span style="color:red;">${requestScope.message }</span></td>
		</tr>
		<tr>
			<td class="c1">密  码:</td>
			<td class="c2"><input type="password" name="password" /></td>
			<td></td>
		</tr>
		<tr>
			<td colspan="2">
				<input type="reset" value="重置" />    
				<input type="submit" value="登录" />
			</td>
			<td></td>
		</tr>
	</table>
	</form>
	</div>
  </body>
</html>

index.jsp部分代码:

  
<body>
  欢迎${sessionScope.loginUser }回来!
</body>

总结:

ModelDriven使用、jsp页面控件name属性定义、action值定义、js传参

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值