struts2综合例子--------拦截器(登陆检查,日志记录),校验validate,

列表Action

package he.action;

import he.dao.UserDAO;

import java.sql.SQLException;
import java.util.LinkedList;
import java.util.List;

public class ListAction {

    private List<User> users = new LinkedList<User>();

    public List<User> getUsers() {
        return users;
    }

    public void setUsers(List<User> users) {
        this.users = users;
    }

    public String list(){
        System.out.print("list");
        UserDAO dao = new UserDAO();
        try {
            users = dao.list();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return "error";
        }

        return "success";
    }

}

UserAction ------delete   add    see方法

package he.action;

import java.sql.SQLException;

import com.opensymphony.xwork2.ActionSupport;

import he.dao.UserDAO;

public class UserAction extends ActionSupport{

    private User user;
    private String pwd;

    public String getPwd() {
        return pwd;
    }

    public void setPwd(String pwd) {
        this.pwd = pwd;
    }

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    public void validateAdd() {
        // TODO Auto-generated method stub
        super.validate();
        if(user.name==null||"".equals(user.name)){
            this.addFieldError("name", "name can not be null");
        }
        if(user.name.length()>20){
            this.addFieldError("name", "name too long");
        }
        if(user.pwd==null||"".equals(user.pwd)){
            this.addFieldError("pwd", "pwd can not be null");
        }
        if(!user.pwd.equals(pwd)){
            this.addFieldError("pwd", "pwds are not same");
        }
        if(user.name.equals(user.pwd)){
            this.addFieldError("pwd", "name is same to pwd,too dangerous");
        }
    }

    public String add(){
        UserDAO dao = new UserDAO();
        try {
            dao.add(user);
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return "error";
        }
        return "add";
    }

    public String delete(){
        System.out.print("delete in");
        UserDAO dao = new UserDAO();
        try {
            dao.delete(user.getId());
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return "errror";
        }

        return "delete";
    }

    public String see(){
        UserDAO dao = new UserDAO();
        try {
            user = dao.findById(user.id);
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return "error";
        }
        System.out.println("see over");
        return "see";
    }

}

LoginAction

package he.action;

import java.util.Map;

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

public class LoginAction extends ActionSupport{
    private User user;

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    public String execute(){
        if("scott".equals(user.name)&&"1234".equals(user.pwd)){
            Map<String,Object> session = ActionContext.getContext().getSession();
            session.put("user", user);
            return "success";
        }
        this.addFieldError("userOrPwd", "username or pwd error");
        return "login";
    }

}

UserDAO

package he.dao;

import he.action.User;
import he.util.DBUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class UserDAO {
        Connection conn=null;
        PreparedStatement prep=null;
        ResultSet res = null;
        List<User> lu=null;
        //写一个函数将String[]转成String
        public static String arrToStr(String[] sarr){
            String s = "";
            for(int i = 0;i<sarr.length;i++){
                s=s+sarr[i]+",";
            }
            return s;
        }
        public int add(User user) throws SQLException{
            conn=DBUtil.getConnetion();
            prep = conn.prepareStatement("insert into s_user values(?,?,?,?,?,?)");
            prep.setString(1, user.getName());
            prep.setString(2, user.getPwd());
            prep.setString(3, user.getSex());
            prep.setInt(4, user.getAge());
            prep.setString(5, user.getEmail());
            prep.setString(6,arrToStr(user.getLoves()));
            int i = prep.executeUpdate();
            return i;
        }

        public void delete(int id) throws SQLException{
            conn=DBUtil.getConnetion();
            prep = conn.prepareStatement("delete from s_user where id=?");
            prep.setInt(1, id);
            prep.executeUpdate();
            DBUtil.close();
        }

        public User findById(int id) throws SQLException{
            User user = new User();
            conn=DBUtil.getConnetion();
            prep = conn.prepareStatement("select * from s_user where id=?");
            prep.setInt(1, id);
            res=prep.executeQuery();
            if(res.next()){
                user.setId(res.getInt(1));
                user.setName(res.getString(2));
                user.setPwd(res.getString(3));
                user.setSex(res.getString(4));
                user.setAge(res.getInt(5));
                user.setEmail(res.getString(6));
                user.setLoves(res.getString(7).split(","));
            }
            DBUtil.close();
            return user;
        }

        public List<User> list() throws SQLException{
            lu = new ArrayList<User>();
            User user = null;
            conn=DBUtil.getConnetion();
            prep = conn.prepareStatement("select * from s_user");
            res=prep.executeQuery();
            while(res.next()){
                user = new User();
                user.setId(res.getInt(1));
                user.setName(res.getString(2));
                user.setPwd(res.getString(3));
                user.setSex(res.getString(4));
                user.setAge(res.getInt(5));
                user.setEmail(res.getString(6));
                user.setLoves(res.getString(7).split(","));
                lu.add(user);
            }
            DBUtil.close();
            return lu;
        }

}

User

package he.action;

public class User {
    int id;
    String name;
    String pwd;
    String sex;
    int age;
    String email;
    String[] loves;
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getPwd() {
        return pwd;
    }
    public void setPwd(String pwd) {
        this.pwd = pwd;
    }
    public String getSex() {
        return sex;
    }
    public void setSex(String sex) {
        this.sex = sex;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
    public String[] getLoves() {
        return loves;
    }
    public void setLoves(String[] loves) {
        this.loves = loves;
    }

}

日志记录拦截器LoggerInterceptor

package he.interceptor;

import he.action.User;

import java.io.FileWriter;
import java.io.PrintWriter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

public class LoggerIntercptor extends AbstractInterceptor{

    @Override
    public String intercept(ActionInvocation invocation) throws Exception {
        // TODO Auto-generated method stub
        String result = invocation.invoke();//调用后续的拦截器或者Action
        String msg="";
        Map<String,Object> session = invocation.getInvocationContext().getSession();
        if(session.get("user")!=null){
            msg+=(((User)session.get("user")).getName());
        }
         Date date=new Date();
         DateFormat format=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
         String time=format.format(date);
        String actionName = invocation.getProxy().getActionName();
        String methodName = invocation.getProxy().getMethod();
        FileWriter fw = new FileWriter("d:/demo.log",true);
        PrintWriter pw = new PrintWriter(fw);
         msg=msg+actionName+"   "+methodName+time;
        pw.println(msg);
        pw.close();
        return result;
    }

}

登陆检查拦截器LoginInterceptor

package he.interceptor;

import java.util.Map;

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.MethodFilterInterceptor;

public class LoginInterceptor extends MethodFilterInterceptor{

    @Override
    protected String doIntercept(ActionInvocation invocation) throws Exception {
        // TODO Auto-generated method stub

        //登陆检查
        Map<String,Object> session = invocation.getInvocationContext().getSession();
        Object user = (Object)session.get("user");
        if(user==null){
            return "login";
        }

        return invocation.invoke();//调用add,delete,see 方法
    }

}

sruts.xml是这么配置的:

<?xml version="1.0" encoding="UTF-8" ?>

<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.1.7//EN"
    "http://struts.apache.org/dtds/struts-2.1.7.dtd">

<struts>
    <package name="strudemo1" extends="struts-default">
        <interceptors>
            <interceptor name="mylogger" class="he.interceptor.LoggerIntercptor"></interceptor>
            <interceptor name="mylogin" class="he.interceptor.LoginInterceptor">
                <param name="includeMethod">delete</param>
            </interceptor>
        </interceptors>
        <global-results>
            <result name="login">/login.jsp</result>

        </global-results>

        <action name="opt_*" method="{1}" class="he.action.ListAction">
            <interceptor-ref name="mylogin"/>
            <interceptor-ref name="mylogger"/>
            <interceptor-ref name="defaultStack"/>
            <result name=‘success‘ type=‘dispatcher‘>/WEB-INF/ok.jsp</result>
        </action>

        <action name="login" class="he.action.LoginAction">
            <result type="redirectAction">opt_list</result>
            <result name="login">/login.jsp</result>
        </action>

        <action name="user_*" method="{1}" class="he.action.UserAction">
            <interceptor-ref name="mylogin"/>
            <interceptor-ref name="mylogger"/>
            <interceptor-ref name="defaultStack"/>
            <result name=‘see‘ type=‘dispatcher‘>/index.jsp</result>
            <result name=‘delete‘ type=‘redirectAction‘>opt_list</result>
            <result name=‘add‘ type=‘redirectAction‘>opt_list</result>
            <result name="input">/add.jsp</result>
        </action>

    </package>
</struts>

ok.jsp

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<%@taglib uri="/struts-tags"  prefix="s" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">

    <title>My JSP ‘ok.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">
    -->
<style type="text/css">
table.imagetable {
    font-family: verdana,arial,sans-serif;
    font-size:11px;
    color:#333333;
    border-width: 1px;
    border-color: #999999;
    border-collapse: collapse;
}
table.imagetable th {
    background:#b5cfd2 url(‘cell-blue.jpg‘);
    border-width: 1px;
    padding: 8px;
    border-style: solid;
    border-color: #999999;
}
table.imagetable td {
    background:#dcddc0 url(‘cell-grey.jpg‘);
    border-width: 1px;
    padding: 8px;
    border-style: solid;
    border-color: #999999;
}
</style>

<script type="text/javascript">

<script type="text/javascript">
        function getXmlHttpRequest(){
        var xmlHttpRequest = null;
     if ((typeof XMLHttpRequest) != ‘undefined‘)
     {
         //非ie浏览器
      xmlHttpRequest = new XMLHttpRequest();
     }else {
     //ie浏览器
     xmlHttpRequest =
     new ActiveXObject(‘Microsoft.XMLHttp‘);
     }
     return xmlHttpRequest;
    }

    function seeUser(obj){
        var xmlReq = getXmlHttpRequest();
            xmlReq.open(‘post‘,‘see.action‘,true);
            alert(obj);
            xmlReq.setRequestHeader("Content-Type",
            "application/x-www-form-urlencoded");
            xmlReq.onreadystatechange=function(){
            if(xmlReq.readyState == 4){
                    var rsTxt = xmlReq.responseText;
                    //alert(rsTxt);
                    var ss = rsTxt.evalJSON();
            }
    }

</script>

  </head>

  <body>

  <table class="imagetable">
<tr>
    <th>id</th><th>name</th><th>pwd</th><th>sex</th>
    <th>age</th><th>email</th><th>loves</th><th>somedo</th>
</tr>
<s:iterator value="users" var="user" status="stat">
<tr>
    <td ><s:property value="#user.id"/></td>
    <td ><s:property value="#user.name"/></td>
    <td><s:property value="#user.pwd"/></td>
    <td ><s:property value="#user.age"/></td>
    <td ><s:property value="#user.sex"/></td>
    <td><s:property value="#user.email"/></td>
    <td><s:property value="#user.loves"/></td>
    <td><a href=‘user_see?user.id=<s:property value="#user.id"/>‘>see</a>
    &nbsp<a href=‘user_delete?user.id=<s:property value="#user.id"/>‘>delete</a>
    &nbsp<a href=‘add.jsp‘>add</a>&nbsp</td>
</tr>
</s:iterator>
</table>

    <dir  id="d1" >

    </dir>

  </body>
</html>

seeuser.jsp

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<%@taglib uri="/struts-tags"  prefix="s"  %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">

    <title>My JSP ‘seeuser.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>
    This is my JSP page. <br>

    <s:form >
    姓名:<s:textfield  name="user.name"></s:textfield><br/>
    密码:<s:password name="user.pwd" showPassword="true"></s:password><br/>
    年龄:<s:textfield name="user.age"></s:textfield><br/>
    Email:<s:textfield name="user.email"></s:textfield><br/>
    性别:<s:radio list=‘#{"M":"男","F":"女"}‘ name="user.sex"></s:radio><br/>

    个人爱好:<s:checkboxlist name="user.loves" list="#data.loves" listKey="key" listValue="value"></s:checkboxlist>
    <br/>

</s:form>

  </body>
</html>

add.jsp

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<%@taglib  uri="/struts-tags"  prefix="s" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">

    <title>My JSP ‘add.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>
    This is my JSP page. <br>
    <s:debug></s:debug>
    <s:fielderror></s:fielderror>
    <s:form  action="user_add" theme="simple">
      姓名:<s:textfield  name="user.name"></s:textfield><br/>
    密码:<s:password name="user.pwd" showPassword="true"></s:password><br/>
    密码:<s:password name="pwd" showPassword="true"></s:password><br/>
    年龄:<s:textfield name="user.age"></s:textfield><br/>
    Email:<s:textfield name="user.email"></s:textfield><br/>
    性别:<s:radio list=‘#{"M":"男","F":"女"}‘ name="user.sex"></s:radio><br/>

    个人爱好:<s:checkboxlist name="user.loves" list="#{‘jy‘:‘交友‘,‘yq‘:‘打游戏‘,‘lt‘:‘聊天‘,‘ch‘:‘吃喝‘}" listKey="key" listValue="value"></s:checkboxlist>
    <br/>
    <s:submit value="OK"></s:submit>
 </s:form>
  </body>
</html>

index.jsp

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<%@taglib uri="/struts-tags"  prefix="s" %>
<!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>
    This is my JSP page. <br>

         姓名:<s:textfield  name="user.name"></s:textfield><br/>
    密码:<s:password name="user.pwd" showPassword="true"></s:password><br/>
    年龄:<s:textfield name="user.age"></s:textfield><br/>
    Email:<s:textfield name="user.email"></s:textfield><br/>
    性别:<s:radio list=‘#{"M":"男","F":"女"}‘ name="user.sex"></s:radio><br/>

    个人爱好:<s:checkboxlist name="user.loves" list="#{‘jy‘:‘交友‘,‘yq‘:‘打游戏‘,‘lt‘:‘聊天‘,‘ch‘:‘吃喝‘}" ></s:checkboxlist>
    <br/>

  </body>
</html>

login.jsp

<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<%@taglib uri="/struts-tags"  prefix="s" %>
<!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>
  <s:actionerror/>
    <s:form action="login" >
    <s:textfield  name="user.name" label="name" labelposition="left"></s:textfield>
    <s:fielderror fieldName="userOrPwd"></s:fielderror><br>
    <s:textfield  name="user.pwd" label="pwd" labelposition="left"></s:textfield>
    <s:submit  value="OK"></s:submit>
    </s:form>
  </body>
</html>

时间: 2024-11-04 11:53:58

struts2综合例子--------拦截器(登陆检查,日志记录),校验validate,的相关文章

ASP.NET Core搭建多层网站架构【8-使用AOP动态拦截器进行服务层日志记录】

2020/01/29, ASP.NET Core 3.1, VS2019 摘要:基于ASP.NET Core 3.1 WebApi搭建后端多层网站架构[7-编写角色业务的增删改查] 编写最简单的增删改业务,涉及到DI依赖注入的使用.AutoMapper的使用.工作单元与仓储的使用.雪花Id的生成 文章目录 此分支项目代码 本章节介绍了编写最简单的增删改查业务,涉及到DI依赖注入的使用.AutoMapper的使用.工作单元与仓储的使用 原文地址:https://www.cnblogs.com/ka

Struts2自己定义拦截器实例—登陆权限验证

版本号:struts2.1.6 此实例实现功能:用户须要指定username登陆,登陆成功进入对应页面运行操作,否则返回到登陆页面进行登陆,当直接訪问操作页面(登陆后才干訪问的页面)时则不同意,须返回登陆页面. 代码例如以下: 一.页面 login.jsp <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <!DOCTYPE HTML PUB

Struts2 过滤器与拦截器

学习Struts2时,发现有过滤器和拦截器,他们貌似都是一样的功能,但是为什么会有2个不同的名称呢?肯定是有区别的,所以打算自己整理一下. 过滤器,是在java web中,你传入的request,response提前过滤掉一些信息,或者提前设置一些参数,然后再传入servlet或者struts的 action进行业务逻辑,比如过滤掉非法url(不是login.do的地址请求,如果用户没有登陆都过滤掉),或者在传入servlet或者 struts的action前统一设置字符集,或者去除掉一些非法字

Struts2内置拦截器的简要介绍

标记有(*)要着重了解: (1)alias(别名拦截器):允许参数在跨越多个请求时使用不同别名,该拦截器可将多个Action采用不同名字链接起来,然后用于处理同一信息. (2)autowiring(自动装配拦截器):主要用于当Struts2和Spring整合时,Struts2可以使用自动装配的方式来访问Spring容器中的Bean. (3)(*)chain(链拦截器):构建一个Action链,使当前Action可以访问前一个Action的请求信息,一般和<result type="chai

关于struts2的自定义拦截器和struts2的详细流程

1.其实我们大家平常都会用struts2用的很多,但是有的时候我们并不是真正的了解struts2的运行机制,下面给大家分享一下struts2的运行流程.MVC框架 解释如下: 1.  所有请求被Struts2核心控制器StrutsPreparaedAndExecuteFilter拦截 2.根据ActionMapper提供的信息决定如何进行下一步 3.ActionMapper主要依赖Struts2的配置文件struts.xml 4.接下来为每个Action创建Action代理类ActionProx

(转)关于struts2的自定义拦截器和struts2的详细流程

转自 http://www.94cto.com/index/Article/content/id/63218.html.话说,写的真不错. 1.其实我们大家平常都会用struts2用的很多,但是有的时候我们并不是真正的了解struts2的运行机制,下面给大家分享一下struts2的运行流程.MVC框架 解释如下: 1. 所有请求被Struts2核心控制器StrutsPreparaedAndExecuteFilter拦截 2.根据ActionMapper提供的信息决定如何进行下一步 3.Actio

【struts2】struts2的execAndWait拦截器使用

使用execAndWait拦截器可以在等待较长时间的后台处理中增加等待页面.实现如下图所示的效果: 1)struts.xml主要部分 <action name="test" class="actions.ActionDemo" method="queryall"> <interceptor-ref name="defaultStack"/> <interceptor-ref name="

Struts2(十四)拦截器实现权限管理

一.认识拦截器 拦截器也是一个类 拦截器可以在Action被调用之前和之后执行代码 框架很多核心功能是拦截器实现的 拦截器的特点: 拦截器自由组合,增强了灵活性.扩展性.有利于系统解耦 拦截器可以拦截Action请求 在访问的Action执行之前和执行之后执行代码实现某项功能 Struts2: 大部分功能是在拦截器中实现的如:接收输入的参数,数据验证,文件上传,国际化等 应用程序: 需要在Action执行的前后执行特定功能 Action执行时间统计,Action访问权限管理 Action添加功能

好记性不如烂笔头49-javaWeb框架struts2中的拦截器(4)

1. Struts2的拦截器概述 Struts2拦截器是在访问某个Action或Action的某个方法之前拦截,或者在运行之后处理.Struts2拦截器是可插拔的,拦截器是AOP(Aspect Oriented Programming,面向切面编程)的一种实现 Struts2的拦截器栈(InterceptorStack)就是将拦截器按一定的顺序联结成一条链.在访问被拦截的方法或字段时,Struts2拦截器链中的拦截器就会按其之前定义的顺序被调用. Struts2规定用户自定义拦截器必须实现com