【问题标题】:My action class is being mapped without Struts.xml mappins or java annotations我的动作类在没有 Struts.xml 映射或 java 注释的情况下被映射
【发布时间】:2016-08-19 06:35:19
【问题描述】:

我有一个调用登录操作类的 JSP 登录页面。我使用 Struts 注释而不是 struts.xml 进行映射,一切正常。我随机尝试了一些新的东西,所以我从我的动作类中删除了所有注释,我的struts.xml 没有映射但不知何故我的login.jsp 能够调用我的动作类。我的动作类怎么可能在没有使用Struts.xml 配置或struts 注释的情况下被调用?

login.jsp

    <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="s" uri="/struts-tags"%>    
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Welcome to Popular Movies</title>

<style type="text/css">
.errors {
    background-color:#FFCCCC;
    border:1px solid #CC0000;
    width:400px;
    margin-bottom:8px;
}
.errors li{ 
    list-style: none; 
}
</style>

</head>
<body>

<h2>Please Log in</h2>
<div  id="errorMessage" >   
        <s:if test="hasActionErrors()">
           <div class="errors" >
               <s:actionerror/>
           </div>
        </s:if>
</div>      
   <s:form action="login" method="post" name="myForm" onSubmit="return preValidate(errorMessage, userName, userPassword)" >
      <s:textfield name="userName" label="Name" size="20" id="userName" />
      <s:password name="password" label="Password" size="20" id="userPassword" />
      <s:hidden name="registration" value="false" />
      <s:submit value="Submit" align="center" />
   </s:form>

   <hr>

   <a href="/PopularMovies/registration.jsp">Sign up free</a> 
</body>

<script type="text/javascript" src="validation.js">

</script>
</html>

登录.java

    package com.esi.actions;

import com.opensymphony.xwork2.ActionSupport;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

import com.sans.model.Movie;
import com.sans.model.Movies;
import com.sans.model.user_account;
import org.hibernate.HibernateException;
import org.hibernate.Query;

@SuppressWarnings("serial")
public class Login extends ActionSupport {
    private String password;
    private String userName;
    private String email;
    private String firstName;
    private String lastName;
    private String registration;
    private static SessionFactory sessionFactory; 

    @SuppressWarnings("deprecation")
    public String execute() {
        boolean isRegistration = Boolean.parseBoolean(registration);

        System.out.println("Action called from struts.xml");
        try {
            //Setting up Hibernate configuration
            System.out.println("Attempting Database connection...");
            sessionFactory = new Configuration().configure().buildSessionFactory();
        }
        catch(Exception ex){
            System.out.println("Failed to create sessionFactory object. " + ex.toString());     
            return INPUT;
        }

        // If Registration flag is set to true then it means user is trying to register
        // else authenticate user
        if(isRegistration) {
            if(this.addUser()) {
                return SUCCESS;
            }
            else {
                return INPUT;
            }
        }
        else {
            if(this.authenticateUser(this.getUserName())) {
                return SUCCESS;
            }
            else {
                return INPUT;
            } 
        }
    }

    public boolean addUser() {
        boolean result = false;
        user_account user = new user_account();
        user.setUser_Name(this.getUserName());
        user.setFirstName(this.getFirstName());
        user.setLastName(this.getLastName());
        user.setEmail(this.getEmail());
        user.setUser_Password(this.getPassword());

        Session session = sessionFactory.openSession();
        try{
            session.beginTransaction();
            session.save(user);     
            session.getTransaction().commit();
            result = true;
            addActionMessage("Welcome " + user.getUser_Name());
        }
        catch(HibernateException e){
            if(session.getTransaction() != null)
                session.getTransaction().rollback();        
            System.out.println("Error trying to insert user to database.. " + e.getMessage() + "\nStack Trace: ");
            e.printStackTrace();
        }

        finally {
            session.close();
        }
        return result;
    }

    public boolean authenticateUser(String userName) {
        boolean result = false;

        Session session = sessionFactory.openSession();
        try{
            session.beginTransaction();
            String hql = "FROM user_account U WHERE U.User_Name = :userName";
            Query query = session.createQuery(hql);
            query.setParameter("userName", userName);
            List results = query.list();

            //If the query result size is 0, then it means user does not exist in database
            if(results.size() != 0) {
                user_account user = (user_account)results.get(0);

                if(this.getUserName().equals(user.getUser_Name()) && this.getPassword().equals(user.getUser_Password())) {
                    addActionMessage("Welcome " + user.getUser_Name());
                    result = true;
                }
                else {
                    addActionError("Invalid User");
                    result = false;
                }
            }
            else {
                addActionError("Invalid User");
                result = false;
            }
            session.getTransaction().commit();  
        }
        catch(HibernateException e){
            if(session.getTransaction() != null)
                session.getTransaction().rollback();        
            System.out.println("Error trying to insert user to database.. " + e.toString());
        }
        catch(IndexOutOfBoundsException e) {

        }
        catch(Exception ex) {
            System.out.println("Something went wrong: " + ex.toString());
        }

        finally {
            session.close();
        }
        return result;
    }


    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
    public String getRegistration() {
        return registration;
    }

    public void setRegistration(String registration) {
        this.registration = registration;
    }



}

Struts.xml

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

<struts>

    <action name="login" class="com.esi.actions.Login">
        <result name="success">/success.jsp</result>
    </action> 

</struts>

Web.xml

    <?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>PopularMovies</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>


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

</web-app>

根据我从 struts 框架中了解到的情况,只有在 struts.xml 中映射或使用注释时才能调用动作类。

【问题讨论】:

  • Struts2 首先在动作配置中搜索动作,不管是谁提供的。

标签: java jsp configuration struts2 struts2-convention-plugin


【解决方案1】:

在 Struts2 中,注解由 Convention Plugin 提供。

名称说明了一切:约定优于配置

这意味着您可以配置它的各个方面,但如果您遵循某些约定,它也将默认工作;这样,您必须花时间仅配置那些与标准行为不同的情况。

Specifically:

默认情况下,Convention 插件会查找所有符合 实现 com.opensymphony.xwork2.Action 或名称以 特定包中的单词 Action。

这些包是由 Convention 插件通过搜索找到的 方法。首先,Convention 插件找到名为 struts 的包, struts2,动作或动作。任何与这些名称匹配的包都是 考虑了 Convention 插件的根包。接下来, 插件查看这些包中的所有类以及 子包并确定类是否实现 com.opensymphony.xwork2.Action 或者如果他们的名字以 Action 结尾(即 FooAction)。这是公约中的几个类的示例 插件会发现:

Classes 

com.example.actions.MainAction
com.example.actions.products.Display (implements com.opensymphony.xwork2.Action)
com.example.struts.company.details.ShowCompanyDetailsAction

您扩展了实现 Action 接口的 ActionSupport……因此,即使未配置,也会找到 login 操作。


编辑

我忘了提到有一个插件可以帮助您调试动作/拦截器/结果配置:Struts2 Config Browser Plugin。只需将 JAR 包含在您的 WAR/EAR 中,然后调用

http://YOUR_DOMAIN/YOUR_WEBAPP/config-browser/index.action

您将清楚地看到您的 web 应用程序中配置的每个操作(通过约定隐式或通过配置显式)。

请记住在部署到生产环境之前删除此插件,否则攻击者将有(方式)更多机会攻击您。

【讨论】:

  • 注解仅用于方便覆盖按约定创建的配置。
  • 是的:如果您遵循某些约定,它也将默认工作;这样,您必须花时间只配置那些与标准行为不同的情况
【解决方案2】:

好久没用Struts了,不知道是不是用类名来做映射,试试下面的一个选项看看对不对:

1- 将 action="login" 更改为 action="login2"
要么
2-将类名更改为Login2

看看它是否有效!

【讨论】:

  • 是的,你是对的,它正在使用类名来进行映射。但是现在我更新了我的 struts.xml 以将操作映射到正确的 jsp,但我一直收到以下错误“没有为操作 com.esi.actions.Login 定义结果和结果成功”
  • 你能粘贴你的struts映射吗?您是否添加了这样的成功结果? /login.jsp
  • 您还需要添加其他标签 {最佳实践} /error.jsp/login. jsp
  • 我已经粘贴了我的 struts 映射
  • 你的struts映射成功了所有小写字母,你可以试试所有大写字母吗? /success.jsp
猜你喜欢
  • 2014-06-06
  • 1970-01-01
  • 1970-01-01
  • 2022-12-03
  • 2014-04-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-08
相关资源
最近更新 更多