【问题标题】:How to change from using Servlet to Struts2?如何从使用 Servlet 更改为 Struts2?
【发布时间】:2014-03-10 20:31:33
【问题描述】:

我对 struts2 很陌生。我的 Web 应用程序中有几个 Servlet,我想更改它以便使用 Struts2 框架。我该如何做这件事并在代码中保持相同的逻辑?我也在使用 Hibernate,也想将 Struts2 与 Hibernate 一起使用。

例如,我的 Web 应用程序中有这个 servlet:

package com.webapp.servlets;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.hibernate.Session;

import com.webapp.entity.UserEntity;
import com.webapp.util.HibernateUtil;

/**
 * Servlet implementation class SignUpServlet
 */
@WebServlet("/SignUpServlet")
public class SignUpServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public SignUpServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doProcess(request, response);
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doProcess(request, response);
    }


    protected void doProcess(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("in process");
        String userName = request.getParameter("userName");
        String password = request.getParameter("password");
        String email = request.getParameter("email");
        String firstName = request.getParameter("firstName");
        String lastName = request.getParameter("lastName");
        String contactNo = request.getParameter("contactNo");
        String address = request.getParameter("address");

        UserEntity userEntity = new UserEntity();

        userEntity.setUserName(userName);
        userEntity.setPassword(password);
        userEntity.setEmail(email);
        userEntity.setFirstName(firstName);
        userEntity.setLastName(lastName);
        userEntity.setAddress(address);
        userEntity.setContactNo(contactNo);

        Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        session.beginTransaction();

        session.save(userEntity);

        session.getTransaction().commit();

        response.sendRedirect("jsp/login.jsp");
    }
}

还有模特

package com.webapp.entity;

import java.io.Serializable;

import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.xml.bind.annotation.XmlRootElement;
@Entity
@Table(name = "Users")
public class UserEntity implements Serializable{

/**
 * 
 */
private static final long serialVersionUID = 1L;

@Id
@Basic(optional = false)
 @GeneratedValue(strategy= GenerationType.IDENTITY)
@Column(name = "userId")
private Long userId ;

@Column(name = "userName")
private String userName;

@Column(name = "password")
private String password;

@Column(name = "roleId")
private Long roleId;

@Column(name = "email")
private String email;

@Column(name = "firstName")
private String firstName;

@Column(name = "lastName")
private String lastName;

@Column(name = "address")
private String address;

@Column(name = "contactNo")
private String contactNo;





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 getAddress() {
    return address;
}

public void setAddress(String address) {
    this.address = address;
}

public String getContactNo() {
    return contactNo;
}

public void setContactNo(String contactNo) {
    this.contactNo = contactNo;
}

public Long getUserId() {
    return userId;
}

public void setUserId(Long userId) {
    this.userId = userId;
}

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 Long getRoleId() {
    return roleId;
}

public void setRoleId(Long roleId) {
    this.roleId = roleId;
}

public String getEmail() {
    return email;
}

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

}

还有 SignUp.jsp 的视图

<head>
     </head>
        <body>

            <br></br>
            <br></br>
            <table width="" border="0" align="center" cellpadding="0"
                   cellspacing="0" class="maintable">
                <tr>
                    <td valign="top" align="center" class="middlesection">
                        <table width="96%" border="0" cellspacing="0" cellpadding="0">
                            <tr>
                                <td>
                                    &nbsp;
                                </td>
                            </tr>
                            <tr>
                                <td>
                                    <table width="100%" border="0" cellspacing="0" cellpadding="0">
                                        <tr>
                                            <td>
                                                <table width="100%" border="0" cellspacing="0"
                                                       cellpadding="0">
                                                    <tr>
                                                        <td align="left" valign="middle">
                                                            <h1>
                                                                Sign Up
                                                            </h1>
                                                        </td>
                                                        <td align="right" valign="bottom">
                                                            <table width="0%" border="0" cellspacing="0"
                                                                   cellpadding="0">
                                                                <tr>
                                                                    <td align="center" style="color: #00FF00">
                                                                        &nbsp;
                                                                    </td>
                                                                    <td>
                                                                        <a href="#" class="buttonash" onclick="resetForm();"><span>
                                                                                reset </span> </a>
                                                                    </td>
                                                                    <td width="5"></td>
                                                                    <td>
                                                                        <a href="#" class="buttonash" onclick="submit()"><span>
                                                                                SignUp </span> </a>
                                                                    </td>
                                                                </tr>
                                                            </table>
                                                        </td>
                                                    </tr>
                                                </table>
                                            </td>
                                        </tr>
                                        <tr>
                                            <td class="bottomboder">
                                                <img src="/WebApp/images/ashish.gif" height="1" />
                                            </td>
                                        </tr>
                                    </table>
                                </td>
                            </tr>
                            <tr>
                                <td>
                                    &nbsp;
                                </td>
                            </tr>
                            <tr>
                                <td></td>
                            </tr>
                            <tr>
                                <td>
                                    <div class="tab-content-out" style="clear: both">
                                        <div id="tabs" class="tabs">
                                            <div id="TabbedPanels1" class="TabbedPanels">

                                                <div
                                                    style="background: url(/WebApp/images/tabhdbg.gif) top repeat-x #ffffff; height: 70px;"
                                                    class="TabbedPanelsTabGroup">
                                                    <div style="width: 1px; float: left;">
                                                        <img src="/WebApp/images/tabhdline.gif" />
                                                    </div>
                                                    <div class="navi"
                                                         style="padding-left: 7px; padding-top: 9px;">
                                                        <div style="color: #4B5974; font-size: 24px;"
                                                             align="center">
                                                            <b>  SignUp Form</b>
                                                        </div>
                                                    </div>

                                                    <div style="width: 1px; float: right;">
                                                        <img src="images/tabhdline.gif" />
                                                    </div>
                                                </div>
                                            </div>
                                            <div class="TabbedPanelsContentGroup">
                                                <div class="TabbedPanelsContent">
                                                    <div style="border: 0;" class="tab-content">
                                                        <div class="entry-edit">
                                                            <div class="tebelhd" align="left">
                                                                General Information
                                                            </div>
                                                            <div class="fieldset" id="_generalbase_fieldset">
                                                                <div class="hor-scroll" align="left">
                                                                    <table class="form-list" cellspacing="0" align="center">
                                                                        <tbody>
                                                                        <form method="get" id="addCustomer" name="addCustomer" action="/WebApp/SignUpServlet"  >
                                                                        <table>
                                                                            <tr>
                                                                                <td>
                                                                                    <label>First Name</label>
                                                                                </td>
                                                                                <td>
                                                                                    <input type="text"  name="firstName" required size="51" class="required-entry required-entry input-text"/>
                                                                                </td>
                                                                                </tr>
                                                                                <tr>
                                                                                <td>
                                                                                    <label>Last Name</label>
                                                                                </td>
                                                                                <td>
                                                                                    <input type="text"  name="lastName" size="51" class="required-entry required-entry input-text"/>
                                                                                </td>
                                                                                </tr>
                                                                                <tr>
                                                                                <td>
                                                                                    <label>Adddress</label>
                                                                                </td>
                                                                                <td>
                                                                                    <input type="text"  name="address" size="51" class="required-entry required-entry input-text"/>
                                                                                </td>
                                                                                </tr>
                                                                                <tr>
                                                                                    <td>
                                                                                        <label>Contact No.</label>
                                                                                    </td>
                                                                                    <td>
                                                                                        <input type="text"  name="contactNo" size="51" class="required-entry required-entry input-text"/>
                                                                                    </td>
                                                                                </tr>
                                                                                <tr>
                                                                                    <td>
                                                                                        <label>Email</label>
                                                                                    </td>
                                                                                    <td>
                                                                                        <input type="text"  name="email" size="51" class="required-entry required-entry input-text"/>
                                                                                    </td>
                                                                                </tr>
                                                                                <tr>
                                                                                    <td>
                                                                                        <label>UserName</label>
                                                                                    </td>
                                                                                    <td>
                                                                                        <input type="text"  name="userName" size="51" class="required-entry required-entry input-text"/>
                                                                                    </td>
                                                                                </tr>
                                                                                <tr>
                                                                                    <td>
                                                                                        <label>Password</label>
                                                                                    </td>
                                                                                    <td>
                                                                                        <input type="password"  name="password" size="51" class="required-entry required-entry input-text"/>
                                                                                    </td>
                                                                                </tr>
                                                                        </table>
                                                                             </form>

                                                                        </tbody>
                                                                    </table>

                                                                </div>
                                                            </div>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </td>
                            </tr>
                        </table>
                    </td>
                </tr>
            </table>

    </body>

</html>

【问题讨论】:

    标签: java servlets struts2 struts


    【解决方案1】:

    简而言之:

    1. 不要一开始就在您的应用程序中随意编辑东西,这会导致痛苦的世界。
    2. Read a Tutorial,至少了解有关工作流程的基本概念。
    3. 使用 Maven 和 Struts2 原型之一(可能是空白约定原型)创建一个示例 Struts2 项目;让它运行,然后尝试改变一些东西,至少花几个小时来理解基础知识。
    4. 深入了解每个疑问的 Struts 文档,深入了解基础知识。永远记住,在被调用之前和之后,每个动作都通过一个拦截器堆栈(一个可自定义的拦截器列表,每个拦截器执行不同的业务),并且动作是按用户每个请求创建的,因此是线程安全的,而拦截器不是线程安全的。

    玩了几天之后,您就可以开始编辑自己的大项目了。

    在旧版本中,Struts2 将 Actions 映射到名为 struts.xml 的文件中,但使用 Convention 插件则无需这样做,Actions 将根据其方法名称(或使用 @Action 注释)进行映射.

    然后

    • 摆脱你的doGet()doPost() 方法
    • doProcess() 更改为newActionName(),这将成为操作的名称,或者将@Action(value="newActionName") 放在每个doProcess() 方法上
    • 为您的操作映射结果(正常或重定向操作),并删除对 servlet 内 response 对象的所有引用。

    如果你的项目很大,你不了解 Struts2,你会尝试在不花几天时间学习的情况下开始这种转换,你会失去更多天,结果更糟。

    【讨论】:

      【解决方案2】:

      这是我之前用过的一个例子,非常有用。

      Tutorial

      希望这会有所帮助。

      【讨论】:

      猜你喜欢
      • 2015-12-25
      • 2012-02-10
      • 2011-07-14
      • 1970-01-01
      • 2018-08-05
      • 2014-09-29
      • 2012-10-23
      • 2013-10-25
      • 2015-10-06
      相关资源
      最近更新 更多