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";
    }
    

}
View Code

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";
    }

}
View Code

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";
    }

}
View Code

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;
        }
        
        
}
View Code

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;
    }

}
View Code

日志记录拦截器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;
    }

}
View Code

登陆检查拦截器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 方法
    }

}
View Code

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>
View Code

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>
View Code

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>
View Code

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>
View Code

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>
View Code

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>
View Code

 

posted on 2015-12-29 23:34  编世界  阅读(962)  评论(0编辑  收藏  举报