struts

1.struts初步了解

什么是框架:

  框架简单来说是一个半成品的项目,用了框架之后我们会更快,更好的完成项目。

 

什么是struts:

  strut2是处理访问服务器的请求

  取代serylet

struts下载

 

2.使用传统的servlet编写用户登录功能

 

3.使用struts2编写用户登录功能

 

4.对比两种方式

  •      (1)启动:

servlet:无

struts:配置filter

web.xml中配置如下:       启动项

 

 

 

  •  (2)创建:

servlet:继承HttpServlet,重写doget与dopost方法

             添加注解或者配置web.xml

struts: 继承ActionSupport,写一个返回值为String而且抛出一个异常。

          配置struts.xml

<package name="MyPackage" namespace="/" extends="struts-default">
<action name="loginAction" class="com.web.UserAction" method="execute">
<!-- 默认为转发 -->
<result name="success" type="redirect">/index.html</result>
<result name="error">/login.jsp</result>
</action>
</package>

  • (3)封装数据:

servlet:使用BeanUtils工具通过name封装,BeanUtils.populate(user,request,getParameterMap)

struts:实现ModelDriven接口,实现getModel方法,返回一个对象就是我们封装数据的对象。(先把对象new出来)

         也是通过name属性进行封装的。

  • (4)转发与重定向

servlet:  

          重定向:response.sendRedirect(request.getContextPath()+"/index.html");

  请求转发:request.getRequestDispatcher("/login.jsp").forward(request, response);

 struts:

  重定向:<result name="success" type="redirect">/index.html</result>

       转发(默认):<result name="error">/login.jsp</result>

5.学习struts2重点

          struts.xml   ----------书写Action

        -----核心配置

name:配置包名 

namespace:给action的访问路径定义一个命名空间

action:配置action类
name:决定了action访问的资源名称

servlet:url-pattern
class:action的完整类名
method:指定调用了action中的哪个方法来处理请求

 

        ------动态方法调用

        -----结果集的处理

        -------转发

        ------重定向

        -------转发到Action

        ------重定向到Action

     

 

动态方法调用如下:

    主要配置:                  

  • <constant name="struts.devMode" value="true"></constant>
  • <constant name="struts.enable.DynamicMethodInvocation" value="true"></constant>
  • <global-allowed-methods>login,register,kill</global-allowed-methods>

允许该action下的所有请求: 

<global-allowed-methods>regex:.*</global-allowed-methods>

 

dao

package com.dao;

import java.sql.SQLException;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;

import com.domain.User;
import com.yl.lain.utils.C3p0DataSourceUtils;

public class UserDao {

    public User findUser(User user) throws SQLException {
        QueryRunner runner=new QueryRunner(C3p0DataSourceUtils.getDataSource());
        String sql="select * from user where username=? and password=?";
        runner.query(sql, new BeanHandler<User>(User.class),user.getUsername(),user.getPassword());
        
        return null;
    }

}
View Code

domain:

package com.domain;

public class User {
    private String username;
    private String password;
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    public User(String username, String password) {
        super();
        this.username = username;
        this.password = password;
    }
    public User() {
        super();
        // TODO Auto-generated constructor stub
    }
    
}
View Code

 

service:

package com.serive;

import java.sql.SQLException;

import com.dao.UserDao;
import com.domain.User;

public class UserService {

    public boolean findUser(User user) throws SQLException {
        UserDao userDao=new UserDao();
        User temp=userDao.findUser(user);
        
        return temp==null?false:true;
    }

}
View Code

 

web:

package com.web;

public class DefaultAction {
    public String execute() {
        System.err.println("这是一个普通的Action");
        return null;
    }
}
View Code
package com.web;

import com.opensymphony.xwork2.Action;

public class ImplAction implements Action{

    @Override
    public String execute() throws Exception {
        System.err.println("这是实现了action接口的Action");
        return null;
    }
    
    

}
View Code
package com.web;



import org.apache.struts2.ServletActionContext;

import com.domain.User;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import com.serive.UserService;

public class UserAction extends ActionSupport implements ModelDriven<User>{
    public User user=new User();

    // execute方法
    public String login() throws Exception {
        System.err.println("login方法....");
        UserService userService=new UserService();
        boolean success=userService.findUser(user);
        if(success) {
            return "success";
        }else {
            ServletActionContext.getRequest().setAttribute("error", "用户名或者密码错误");
            return "error";
        }
    }
    public String register() throws Exception{
        System.err.println("register方法....");
        return null;
    }
    public String kill() throws Exception{
        System.err.println("kil方法....");
        return null;
    }
    @Override
    public User getModel() {
        // TODO Auto-generated method stub
        return user;
    }


}
View Code

struts.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.5//EN"
    "http://struts.apache.org/dtds/struts-2.5.dtd">
<struts>

<!-- 动态方法调用 -->
<constant name="struts.devMode" value="true"></constant>
<constant name="struts.enable.DynamicMethodInvocation" value="true"></constant>

<!-- name:配置包名  namespace:给action的访问路径定义一个命名空间-->
    <package name="MyPackage" namespace="/" extends="struts-default">
    
       <global-allowed-methods>login,register,kill</global-allowed-methods>
       
       <!-- action:配置action类
            name:决定了action访问的资源名称  servlet:url-pattern
            class:action的完整类名
            method:指定调用了action中的哪个方法来处理请求
            -->
        
        <action name="loginAction_*" class="com.web.UserAction" method="{1}">
        <!-- 默认为转发 -->
            <result name="success" type="redirect">/index.html</result>
            <result name="error">/login.jsp</result>
        </action>
        <!-- <action name="loginActionregister" class="com.web.UserAction" method="register">
        默认为转发
            
        </action> -->
        <action name="loginActionDefault" class="com.web.DefaultAction" method="execute">
        </action>
        <action name="loginActionImpl" class="com.web.ImplAction" method="execute"></action>
    </package>
</struts>
View Code

c3p0.xml

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

    <default-config>
        <property name="driverClass">com.mysql.jdbc.Driver</property>
        <property name="jdbcUrl">jdbc:mysql://localhost:3306/world?useSSL=false</property>
        <property name="user">root</property>
        <property name="password">root</property>
        <property name="initialPoolSize">5</property>
        <property name="maxPoolSize">20</property>
    </default-config>


    <named-config name="oracel">
        <property name="driverClass">oracle.jdbc.driver.OracleDriver</property>
        <property name="jdbcUrl">jdbc:oracle:thin:@//192.168.40.128/orcl</property>
        <property name="user">scott</property>
        <property name="password">scott</property>
    </named-config>


</c3p0-config>
View Code

 

http://localhost:8080/strutsforum/loginAction_kill

 

struts实现请求转发

 

struts.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.5//EN"
    "http://struts.apache.org/dtds/struts-2.5.dtd">
<struts>

<!-- 动态方法调用 -->
<constant name="struts.devMode" value="true"></constant>
<constant name="struts.enable.DynamicMethodInvocation" value="true"></constant>

<!-- name:配置包名  namespace:给action的访问路径定义一个命名空间-->
    <package name="MyPackage" namespace="/" extends="struts-default">
    
       <global-allowed-methods>login,register,kill</global-allowed-methods>
       
       <!-- action:配置action类
            name:决定了action访问的资源名称  servlet:url-pattern
            class:action的完整类名
            method:指定调用了action中的哪个方法来处理请求
            -->
        
        <action name="loginAction_*" class="com.web.UserAction" method="{1}">
        <!-- 默认为转发 -->
            <result name="success" type="redirect">/index.html</result>
            <result name="error">/login.jsp</result>
        </action>
        <!-- <action name="loginActionregister" class="com.web.UserAction" method="register">
        默认为转发
            
        </action> -->
        <action name="loginActionDefault" class="com.web.DefaultAction" method="execute">
        </action>
        <action name="loginActionImpl" class="com.web.ImplAction" method="execute">
           <!-- 转发到loginActionDefault -->
           <result name="defaultAction" type="chain">loginActionDefault</result>
        </action>
    </package>
</struts>
View Code

web下的:

package com.web;

import com.opensymphony.xwork2.Action;

public class ImplAction implements Action{

    @Override
    public String execute() throws Exception {
        System.err.println("这是实现了action接口的Action");
        return "defaultAction";
    }
    
    

}
View Code

 

Struts实现重定向

 

 

解决中文乱码:

web.xml中的配置:

 

     参数传递

 (1)接收参数(3种接收参数的方式)

  • 模型驱动

原理:

实现ModelDriven<T>接口种的getmodel方法,

 

  • 属性驱动

原理

 

再实现属性的get set方法;

package com.web;



import org.apache.struts2.ServletActionContext;

import com.domain.User;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import com.serive.UserService;

public class UserAction extends ActionSupport {
    //public User user=new User();
       public String username;
       public String password; 
    // execute方法
    public String login() throws Exception {
        System.err.println("login方法....");
        System.out.println(username+":"+password);
        User user=new User();
        user.setUsername(username);
        user.setPassword(password);
        UserService userService=new UserService();
        boolean success=userService.findUser(user);
        if(success) {
            return "success";
        }else {
            ServletActionContext.getRequest().setAttribute("error", "用户名或者密码错误");
            return "error";
        }
    }
    public String register() throws Exception{
        System.err.println("register方法....");
        return null;
    }
    public String kill() throws Exception{
        System.err.println("kil方法....");
        return null;
    }
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    


}
View Code
  • 对象驱动

原理

步骤

getset方法

改jsp种的name值

package com.web;



import org.apache.struts2.ServletActionContext;

import com.domain.User;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import com.serive.UserService;

public class UserAction extends ActionSupport {
    public User user;
    //public User user=new User();
    /*public String username;
       public String password; */
    // execute方法
    public String login() throws Exception {
        System.err.println("login方法....");
        System.out.println(user.getUsername()+":"+user.getPassword());
        /*    User user=new User();
        user.setUsername(username);
        user.setPassword(password);*/
        UserService userService=new UserService();
        boolean success=userService.findUser(user);
        if(success) {
            return "success";
        }else {
            ServletActionContext.getRequest().setAttribute("error", "用户名或者密码错误");
            return "error";
        }
    }
    public String register() throws Exception{
        System.err.println("register方法....");
        return null;
    }
    public String kill() throws Exception{
        System.err.println("kil方法....");
        return null;
    }
    public User getUser() {
        return user;
    }
    public void setUser(User user) {
        this.user = user;
    }

}
View Code
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>

<head>
<meta charset="UTF-8">

<link rel="stylesheet" href="css/head.css" />
<link rel="stylesheet" type="text/css" href="css/login.css" />
</head>

<body>
    <div class="dvhead">
        <div class="dvlogo">
            <a href="index.html">你问我答</a>
        </div>
        <div class="dvsearch">10秒钟注册账号,找到你的同学</div>
        <div class="dvreg">
            已有账号,立即&nbsp;<a href="login.html">登录</a>
        </div>
    </div>
    <section class="sec">
        <form action="${pageContext.request.contextPath}/loginAction_login" method="post">
            <div class="register-box">
                <label for="username" class="username_label"> 用 户 名 <input
                    maxlength="20" name="user.username" type="text" placeholder="您的用户名和登录名" />
                </label>
                <div class="tips" ></div>
            </div>
            <div class="register-box">
                <label for="username" class="other_label"> 设 置 密 码 <input
                    maxlength="20" type="password" name="user.password"
                    placeholder="建议至少使用两种字符组合" />
                </label>
                <div class="tips"style="color:red">${error}</div>
            </div>
            <div class="arguement">
                <input type="checkbox" id="xieyi" /> 阅读并同意 <a
                    href="javascript:void(0)">《你问我答用户注册协议》</a> <a href="register.html">没有账号,立即注册</a>
                <div class="tips"></div>
            </div>
            <div class="submit_btn">
                <button type="submit" id="submit_btn">立 即 登录</button>
            </div>
        </form>
    </section>
    <script src="js/index.js" type="text/javascript" charset="utf-8"></script>
</body>
View Code

 

(2)传递参数

        ActionContext

        

package com.web;

import java.util.Map;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionContext;

public class ImplAction implements Action{

    @Override
    public String execute() throws Exception {
        System.err.println("这是实现了action接口的Action");
        //返回结果跟struts.xml里的<result>标签对应
        return "defaultAction";
    }
    public String login() throws Exception{
        System.err.println("这是implaction接口下的action");
    /*    ActionContext.getContext().put("username", "123");
        ActionContext.getContext().put("password", "123");*/
        //rquest中的setAttr
        ActionContext.getContext().put("username", "123");
        ActionContext.getContext().put("password", "123");
        
        Map<String, Object> session = ActionContext.getContext().getSession();
        session.put("str", "true");
        Map<String, Object> application = ActionContext.getContext().getApplication();
        application.put("context", "1");
        
        //返回值已经在struts.xml中固定
        
        return "tologin";
    }
    

}
View Code

 

 传递参数小案例

ImplAction

package com.web;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionContext;

public class ImplAction implements Action{

    @Override
    public String execute() throws Exception {
        System.err.println("这是实现了action接口的Action");
        //返回结果跟struts.xml里的<result>标签对应
        return "defaultAction";
    }
    public String login() throws Exception{
        System.err.println("这是implaction接口下的action");
    /*    ActionContext.getContext().put("username", "123");
        ActionContext.getContext().put("password", "123");*/
        //rquest中的setAttr
        ActionContext.getContext().put("username", "123");
        ActionContext.getContext().put("password", "123");
        
        Map<String, Object> session = ActionContext.getContext().getSession();
        session.put("mysession", "session域");
        Map<String, Object> application = ActionContext.getContext().getApplication();
        application.put("mycontext", "context域");
        
        //获得原生方法的request
          HttpServletRequest request = ServletActionContext.getRequest();
          
          //获得原生的response
          HttpServletResponse response = ServletActionContext.getResponse();
          
          
        //返回值已经在struts.xml中固定
        
        return "tologin";
    }
    

}
View Code
package com.web;



import org.apache.struts2.ServletActionContext;

import com.domain.User;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import com.serive.UserService;

public class UserAction extends ActionSupport implements ModelDriven<User>{
    public User user=new User();
    //public User user=new User();
    /*public String username;
       public String password; */
    // execute方法
    public String login() throws Exception {
        System.err.println("login方法....");
        System.out.println(user.getUsername()+":"+user.getPassword());
        
        System.out.println("session域:"+ActionContext.getContext().getSession().get("mysession"));
        System.out.println("servletcontext域:"+ActionContext.getContext().getApplication().get("mycontext"));

        UserService userService=new UserService();
        boolean success=userService.findUser(user);
        if(success) {
            return "success";
        }else {
            ServletActionContext.getRequest().setAttribute("error", "用户名或者密码错误");
            return "error";
        }
    }
    public String register() throws Exception{
        System.err.println("register方法....");
        return null;
    }
    public String kill() throws Exception{
        System.err.println("kil方法....");
        return null;
    }
    @Override
    public User getModel() {
        // TODO Auto-generated method stub
        return user;
    }
    

}
View Code

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.5//EN"
    "http://struts.apache.org/dtds/struts-2.5.dtd">
<struts>

    <!-- 动态方法调用 -->
    <constant name="struts.devMode" value="true"></constant>
    <constant name="struts.enable.DynamicMethodInvocation"
        value="true"></constant>

    <!-- name:配置包名 namespace:给action的访问路径定义一个命名空间 -->
    <package name="MyPackage" namespace="/"
        extends="struts-default">

        <!-- <global-allowed-methods>login,register,kill</global-allowed-methods> -->
          <global-allowed-methods>regex:.*</global-allowed-methods>

        <!-- action:配置action类 name:决定了action访问的资源名称 servlet:url-pattern class:action的完整类名 
            method:指定调用了action中的哪个方法来处理请求 -->

        <action name="loginAction_*" class="com.web.UserAction"
            method="{1}">
            <!-- 默认为转发 -->
            <result name="success" type="redirect">/index.html</result>
            <result name="error">/login.jsp</result>
        </action>
        
        
        <!-- <action name="loginActionregister" class="com.web.UserAction" method="register"> 
            默认为转发 </action> -->
        <action name="loginActionDefault" class="com.web.DefaultAction"
            method="execute">
        </action>
        <action name="loginActionImpl_*" class="com.web.ImplAction"
            method="{1}">
            <!-- 转发到loginActionDefault -->
            <result name="defaultAction" type="chain">loginActionDefault</result>
            <!-- 重定向到action(loginaction) -->
            <result name="tologin" type="redirectAction">
                <param name="actionName">loginAction_login</param>
                <param name="username">${username}</param>
                <param name="password">${password}</param>
            </result>
        </action>
    </package>
</struts>
View Code

 

ActionContext的总结

  • ActionContext生命周期是一次请求,每次发出请求都会创建一个新的ActionContext

就和request一样,每次创建新的Actioncontext时都会重新引用那些对象。

  • 而且不只是生命周期一样,它本身也具备了request域的功能,可以从后台携带数据到前台,

也和request一样。

  • 通过ActionContext的子类servletActionContext可以获得那些对象
  • 通过ActionContext可以直接获得session和application各自的域对象,操作方便
  • 最重要的一点是,ActionContext本身是一个map,他存储了很多对象例如request、response,

当然除了这些还有我们没有见过的对象

 

struts和ognl常用标签

struts标签配置

在jsp开头引入struts标签库

struts常用标签

<s:iterator value="pastelist" var="paste">     iterator:  循环   value:表示传入的值,可以是集合,数组等    var:该值中的每一个变量。

<s:property value="answernum"/>               表示元素集中的属性。比如对象中的answernum属性

<s:if test="answernum%2==0">张大值</s:if>     

<s:else>Lara</s:else>

如果要访问的是包装类型,要用#

package com.web;

import java.util.List;

import com.domain.Paste;
import com.domain.User;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.serive.PasteService;

public class PasteAction extends ActionSupport{

    public String getAllPaste() throws Exception {
        PasteService pasteservice=new PasteService();
        List<Paste> pastelist=pasteservice.FindAllPaste();
        
        User user=new User();
        user.setUsername("lara");
        user.setPassword("111");
        ActionContext.getContext().put("pastelist", pastelist);
        ActionContext.getContext().put("user", user);
        System.out.println(pastelist);
        return "index";
    }

}
View Code
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!-- 引入struts标签库 -->
<%@taglib uri="/struts-tags" prefix="s"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<link rel="stylesheet" type="text/css" href="css/index.css">
</head>
<div class="dvhead">
    <div class="dvlogo">
        <a href="index.html">你问我答</a>
    </div>
    <div class="dvsearch">10秒钟注册账号,找到你的同学</div>
    <div class="dvreg">
        已有账号,立即&nbsp;<a href="login.html">登录</a>
    </div>
</div>
<div class="dvContent">
    <div class="dvquesleft">

        <div class="dvqstitle">
            <image class="imgbean" src="images/bean.jpg"> <span
                class="qsTitle">问答</span> <span class="back"><ab href="">《《返回上一页</a></span>
        </div>
        <div class="dvtabhead">
            <div class="tabheads tabcurrent">全部问题</div>
            <div class="tabheads">我的问题</div>
            <div class="tabheads">关注问题</div>
            <div class="tabheads">问题标签</div>
        </div>
        <div class="tabContent">
            <div class="dvtags">
                <a class="curenttag">待解决</a><span class="line"></span><a>高分</a><span
                    class="line"></span><a>新回答</a><span class="line"></span><a>已解决</a>
            </div>
            <div class="tab">

                <s:iterator value="pastelist" var="paste">
                    <div class="dvques">
                        <div class="quesCount">
                            <div class="count">
                                <s:property value="answernum" />
                            </div>
                            <div class="ques">回答数</div>
                        </div>
                        <div class="quesContent">
                            <div class="quesTitle">
                                <s:property value="offer" />
                                <image src="images/bean.jpg" class="bean"> <span
                                    class="spanques"><s:property value="title" /></span>
                            </div>
                            <div class="qContent">
                                <s:property value="content" />
                            </div>
                            <div class="tags">
                                <span class="tag">excel</span><span class="tag">程序</span>
                            </div>
                            <div class="quesUser">
                                <image src="images/0.gif" class="imguser" />
                                <div class="userName">
                                <!-- 访问对象里的值要加个# -->
                                    <s:property value="#user.username"/>
                                    <div class="liulan">浏览(9) 30分钟前</div>
                                </div>

                            </div>
                        </div>
                    </div>
                </s:iterator>
            </div>
            <div class="tab hidden">2</div>
            <div class="tab hidden">3</div>
            <div class="tab hidden">4</div>
        </div>
    </div>
    <div class="dvquesright">
        <div>
            <buton class="btnques" onclick="location.href='add.html'">提个问题</buton>
        </div>
        <div class="dvorder">
            <div class="orderTitle">专家排行榜</div>
            <div class="users">
                <image class="userface" src="images/0.gif" />
                <div class="dvuser">
                    <div class="userTitle">陈有龙</div>
                    <div class="userdeital">大牛6级 豆:14006</div>
                </div>
            </div>
            <div class="users">
                <image class="userface" src="images/1.gif" />
                <div class="dvuser">
                    <div class="userTitle">陈有龙</div>
                    <div class="userdeital">大牛6级 豆:14006</div>
                </div>
            </div>
            <div class="users">
                <image class="userface" src="images/2.gif" />
                <div class="dvuser">
                    <div class="userTitle">陈有龙</div>
                    <div class="userdeital">大牛6级 豆:14006</div>
                </div>
            </div>
            <div class="users">
                <image class="userface" src="images/3.gif" />
                <div class="dvuser">
                    <div class="userTitle">陈有龙</div>
                    <div class="userdeital">大牛6级 豆:14006</div>
                </div>
            </div>
            <div class="users">
                <image class="userface" src="images/4.gif" />
                <div class="dvuser">
                    <div class="userTitle">陈有龙</div>
                    <div class="userdeital">大牛6级 豆:14006</div>
                </div>
            </div>
            <div class="users">
                <image class="userface" src="images/5.gif" />
                <div class="dvuser">
                    <div class="userTitle">陈有龙</div>
                    <div class="userdeital">大牛6级 豆:14006</div>
                </div>
            </div>
            <div class="users">
                <image class="userface" src="images/6.gif" />
                <div class="dvuser">
                    <div class="userTitle">陈有龙</div>
                    <div class="userdeital">大牛6级 豆:14006</div>
                </div>
            </div>


        </div>

    </div>

</div>
<script type="text/javascript" src="js/jquery-1.7.2.min.js"></script>
<script type="text/javascript">
    $(function() {

        $(".tabheads").click(
                function() {
                    $(".tabheads").removeClass("tabcurrent")
                            .eq($(this).index()).addClass("tabcurrent");
                    $(".tab").hide().eq($(this).index()).show();
                });
    });
</script>
<body>
</body>
</html>
View Code

 

valueStack运行流程


 


anction原理

 

 详情见博客https://blog.csdn.net/xie_xiansheng/article/details/51130126

 result原理

result是用于输出的组件,用于向页面输出一些内容,转发重定向可以理解为特殊方式的输出

,每一个result就是一个类型的result。他们被定义在struts-default.xml中。

struts-default.xml源码:

 

 

dispatcher: 转发

chain:转发到Action

redirect:重定向

redirectAction:重定向到Action.

 

${username}     struts遇见不认识的会在后面拼接参数。

loginActionDefalut?username=....

 

 

创建拦截器的两种方式

  •  extends MethodFilterInterceptor
  • implements Interceptor

配置拦截器

 

struts.xml中配置

 

注意:

创建拦截器只能控制访问Action,不能控制访问jsp

因为配置的拦截器中有tologin

所以经行全局配置:

  

 

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.5//EN"
    "http://struts.apache.org/dtds/struts-2.5.dtd">
<struts>

    <!-- 动态方法调用 -->
    <constant name="struts.devMode" value="true"></constant>
    <constant name="struts.enable.DynamicMethodInvocation"
        value="true"></constant>

    <!-- name:配置包名 namespace:给action的访问路径定义一个命名空间 -->
    <package name="MyPackage" namespace="/"
        extends="struts-default">


        <interceptors>
            <!-- 注册拦截器 -->
            <interceptor name="myintercepter"
                class="com.web.intercepter.MyIntercepter"></interceptor>
            <!-- 注册拦截器栈 -->
            <interceptor-stack name="mystack">
                <!-- 引入自己创建的拦截器 -->
                <interceptor-ref name="myintercepter"></interceptor-ref>
                <!-- 引入struts写好的20ge拦截器 -->
                <interceptor-ref name="defaultStack"></interceptor-ref>
            </interceptor-stack>
        </interceptors>
        <!-- 指定包中的默认拦截器栈 -->
        <default-interceptor-ref name="mystack"></default-interceptor-ref>
        <!-- <global-allowed-methods>login,register,kill</global-allowed-methods> -->
        <global-allowed-methods>regex:.*</global-allowed-methods>

        <!-- action:配置action类 name:决定了action访问的资源名称 servlet:url-pattern class:action的完整类名 
            method:指定调用了action中的哪个方法来处理请求 -->

        <action name="loginAction_*" class="com.web.UserAction"
            method="{1}">
            <!-- 默认为转发 -->
            <result name="success" type="redirect">/index.html</result>
            <result name="error">/login.jsp</result>
        </action>


        <!-- <action name="loginActionregister" class="com.web.UserAction" method="register"> 
            默认为转发 </action> -->
        <action name="loginActionDefault" class="com.web.DefaultAction"
            method="execute">
        </action>
        <action name="loginActionImpl_*" class="com.web.ImplAction"
            method="{1}">
            <!-- 转发到loginActionDefault -->
            <result name="defaultAction" type="chain">loginActionDefault</result>
            <!-- 带参的 -->
            <result name="defaultAction" type="chain">
                <param name="actionName">loginAction_login</param>
                <param name="username">${username}</param>
            </result>
            <!-- 重定向到action(loginaction) -->
            <result name="tologin" type="redirectAction">
                <param name="actionName">loginAction_login</param>
                <param name="username">${username}</param>
                <param name="password">${password}</param>
            </result>
            <!-- 不带参数的重定向 -->
            <result name="tologin" type="redirectAction">loginAction_login</result>
        </action>
    </package>
    <package name="PastePackage" namespace="/"
        extends="struts-default">
        <global-allowed-methods>regex:.*</global-allowed-methods>
        <action name="PasteAction_*" class="com.web.PasteAction"
            method="{1}">
            <result name="index">/index.jsp</result>
        </action>
    </package>
</struts>
View Code
package com.web.intercepter;

import java.util.Map;

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

public class MyIntercepter extends MethodFilterInterceptor{

    @Override
    protected String doIntercept(ActionInvocation invocation) throws Exception {
        System.out.println("myintercepter");
        //获取session
        Map<String, Object> session = ActionContext.getContext().getSession();
        //获取session中的user
        Object object = session.get("user");
        //判断session中是否有user数据
        if(object!=null) {
            //有,放行
            return invocation.invoke();
        }else {
            return "tologin";
        }
        
    }

}
View Code
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.5//EN"
    "http://struts.apache.org/dtds/struts-2.5.dtd">
<struts>

    <!-- 动态方法调用 -->
    <constant name="struts.devMode" value="true"></constant>
    <constant name="struts.enable.DynamicMethodInvocation"
        value="true"></constant>

    <!-- name:配置包名 namespace:给action的访问路径定义一个命名空间 -->
    <package name="MyPackage" namespace="/"
        extends="struts-default">


        <interceptors>
            <!-- 注册拦截器 -->
            <interceptor name="myintercepter"
                class="com.web.intercepter.MyIntercepter"></interceptor>
            <!-- 注册拦截器栈 -->
            <interceptor-stack name="mystack">
                <!-- 引入自己创建的拦截器 -->
                <interceptor-ref name="myintercepter"></interceptor-ref>
                <!-- 引入struts写好的20ge拦截器 -->
                <interceptor-ref name="defaultStack"></interceptor-ref>
            </interceptor-stack>
        </interceptors>
        <!-- 指定包中的默认拦截器栈 -->
        <default-interceptor-ref name="mystack"></default-interceptor-ref>
        <global-results>
           <result name="tologin" type="redirect">/login.jsp</result>
        </global-results>
        <!-- <global-allowed-methods>login,register,kill</global-allowed-methods> -->
        <global-allowed-methods>regex:.*</global-allowed-methods>

        <!-- action:配置action类 name:决定了action访问的资源名称 servlet:url-pattern class:action的完整类名 
            method:指定调用了action中的哪个方法来处理请求 -->

        <action name="loginAction_*" class="com.web.UserAction"
            method="{1}">
            <!-- 默认为转发 -->
            <result name="success" type="redirect">/index.html</result>
            <result name="error">/login.jsp</result>
        </action>


        <!-- <action name="loginActionregister" class="com.web.UserAction" method="register"> 
            默认为转发 </action> -->
        <action name="loginActionDefault" class="com.web.DefaultAction"
            method="execute">
            <!-- 配置全局的 -->
            <!-- <result name="tologin" type="redirect">/login.jsp</result> -->
        </action>
        <action name="loginActionImpl_*" class="com.web.ImplAction"
            method="{1}">
            <!-- 转发到loginActionDefault -->
            <result name="defaultAction" type="chain">loginActionDefault</result>
            <!-- 带参的 -->
            <result name="defaultAction" type="chain">
                <param name="actionName">loginAction_login</param>
                <param name="username">${username}</param>
            </result>
            <!-- 重定向到action(loginaction) -->
            <result name="tologin" type="redirectAction">
                <param name="actionName">loginAction_login</param>
                <param name="username">${username}</param>
                <param name="password">${password}</param>
            </result>
            <!-- 不带参数的重定向 -->
            <result name="tologin" type="redirectAction">loginAction_login</result>
        </action>
    </package>
    <package name="PastePackage" namespace="/"
        extends="struts-default">
        <global-allowed-methods>regex:.*</global-allowed-methods>
        <action name="PasteAction_*" class="com.web.PasteAction"
            method="{1}">
            <result name="index">/index.jsp</result>
        </action>
    </package>
</struts>
View Code

 不拦截配置:login

struts.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.5//EN"
    "http://struts.apache.org/dtds/struts-2.5.dtd">
<struts>

    <!-- 动态方法调用 -->
    <constant name="struts.devMode" value="true"></constant>
    <constant name="struts.enable.DynamicMethodInvocation"
        value="true"></constant>

    <!-- name:配置包名 namespace:给action的访问路径定义一个命名空间 -->
    <package name="MyPackage" namespace="/"
        extends="struts-default">


        <interceptors>
            <!-- 注册拦截器 -->
            <interceptor name="myintercepter"
                class="com.web.intercepter.MyIntercepter"></interceptor>
            <!-- 注册拦截器栈 -->
            <interceptor-stack name="mystack">
                <!-- 引入自己创建的拦截器 -->
                <interceptor-ref name="myintercepter">
                  <param name="excludeMethods">login</param>
                </interceptor-ref>
                <!-- 引入struts写好的20ge拦截器 -->
                <interceptor-ref name="defaultStack"></interceptor-ref>
            </interceptor-stack>
        </interceptors>
        <!-- 指定包中的默认拦截器栈 -->
        <default-interceptor-ref name="mystack"></default-interceptor-ref>
        <global-results>
           <result name="tologin" type="redirect">/login.jsp</result>
        </global-results>
        <!-- <global-allowed-methods>login,register,kill</global-allowed-methods> -->
        <global-allowed-methods>regex:.*</global-allowed-methods>

        <!-- action:配置action类 name:决定了action访问的资源名称 servlet:url-pattern class:action的完整类名 
            method:指定调用了action中的哪个方法来处理请求 -->

        <action name="loginAction_*" class="com.web.UserAction"
            method="{1}">
            <!-- 默认为转发 -->
            <result name="success" type="redirect">/index.html</result>
            <result name="error">/login.jsp</result>
        </action>


        <!-- <action name="loginActionregister" class="com.web.UserAction" method="register"> 
            默认为转发 </action> -->
        <action name="loginActionDefault" class="com.web.DefaultAction"
            method="execute">
            <!-- 配置全局的 -->
            <!-- <result name="tologin" type="redirect">/login.jsp</result> -->
        </action>
        <action name="loginActionImpl_*" class="com.web.ImplAction"
            method="{1}">
            <!-- 转发到loginActionDefault -->
            <result name="defaultAction" type="chain">loginActionDefault</result>
            <!-- 带参的 -->
            <result name="defaultAction" type="chain">
                <param name="actionName">loginAction_login</param>
                <param name="username">${username}</param>
            </result>
            <!-- 重定向到action(loginaction) -->
            <result name="tologin" type="redirectAction">
                <param name="actionName">loginAction_login</param>
                <param name="username">${username}</param>
                <param name="password">${password}</param>
            </result>
            <!-- 不带参数的重定向 -->
            <result name="tologin" type="redirectAction">loginAction_login</result>
        </action>
    </package>
    <package name="PastePackage" namespace="/"
        extends="struts-default">
        <global-allowed-methods>regex:.*</global-allowed-methods>
        <action name="PasteAction_*" class="com.web.PasteAction"
            method="{1}">
            <result name="index">/index.jsp</result>
        </action>
    </package>
</struts>
View Code

 myintercepter.class

package com.web.intercepter;

import java.util.Map;

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

public class MyIntercepter extends MethodFilterInterceptor{

    @Override
    protected String doIntercept(ActionInvocation invocation) throws Exception {
        System.out.println("myintercepter");
        //获取session
        Map<String, Object> session = ActionContext.getContext().getSession();
        //获取session中的user
        Object object = session.get("user");
        //判断session中是否有user数据
        if(object!=null) {
            //有,放行
            return invocation.invoke();
        }else {
            return "tologin";
        }
        
    }

}
View Code

login.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>

<head>
<meta charset="UTF-8">

<link rel="stylesheet" href="css/head.css" />
<link rel="stylesheet" type="text/css" href="css/login.css" />
</head>

<body>
    <div class="dvhead">
        <div class="dvlogo">
            <a href="index.html">你问我答</a>
        </div>
        <div class="dvsearch">10秒钟注册账号,找到你的同学</div>
        <div class="dvreg">
            已有账号,立即&nbsp;<a href="login.html">登录</a>
        </div>
    </div>
    <section class="sec">
        <form action="${pageContext.request.contextPath}/loginAction_login" method="post">
            <div class="register-box">
                <label for="username" class="username_label"> 用 户 名 <input
                    maxlength="20" name="username" type="text" placeholder="您的用户名和登录名" />
                </label>
                <div class="tips" ></div>
            </div>
            <div class="register-box">
                <label for="username" class="other_label"> 设 置 密 码 <input
                    maxlength="20" type="password" name="password"
                    placeholder="建议至少使用两种字符组合" />
                </label>
                <div class="tips"style="color:red">${error}</div>
            </div>
            <div class="arguement">
                <input type="checkbox" id="xieyi" /> 阅读并同意 <a
                    href="javascript:void(0)">《你问我答用户注册协议》</a> <a href="register.html">没有账号,立即注册</a>
                <div class="tips"></div>
            </div>
            <div class="submit_btn">
                <button type="submit" id="submit_btn">立 即 登录</button>
            </div>
        </form>
    </section>
    <script src="js/index.js" type="text/javascript" charset="utf-8"></script>
</body>
View Code

 

posted @ 2019-05-18 19:36  wq9  阅读(279)  评论(0编辑  收藏  举报