• Java——Struts2 crud 简单实例(学习struts2和ssh) 用Myeclipse实现


    1.new web project


    2.给新建的web项目添加struts2支持


    3.项目结构中有了struts.xml和struts2核心库


    4.编码

      4.1项目结构图

       

      

       4.2源代码:

      (1)DbUtil

      1 package com.phome.crud;
      2 
      3 import java.sql.Connection;
      4 import java.sql.DriverManager;
      5 import java.sql.PreparedStatement;
      6 import java.sql.ResultSet;
      7 import java.sql.SQLException;
      8 import java.sql.Statement;
      9 /**
     10  * 数据库工具类
     11  * @author yangzl
     12  *
     13  */
     14 public class DbUtil
     15 {
     16 
     17     //驱动名
     18     private static final String Driver = "com.mysql.jdbc.Driver";
     19     //数据库连接路径
     20     private static final String URL = "jdbc:mysql://localhost:3306/user";
     21     //数据库连接用户名及密码
     22     private static final String user = "root";
     23     private static final String password = "root";
     24     
     25     /**
     26      * 加载数据库驱动
     27      * @throws ClassNotFoundException(加载异常)
     28      */
     29     private static void registerDriver() throws ClassNotFoundException
     30     {
     31         try
     32         {
     33             Class.forName(Driver);
     34         }
     35         catch (ClassNotFoundException e)
     36         {
     37             System.out.println((new StringBuilder("【加载数据库驱动时,发生异常】
    ")).append(e.getMessage()).toString());
     38             throw e;
     39         }
     40     }
     41 
     42     /**
     43      * 得到数据库连接
     44      * @return
     45      * @throws SQLException
     46      * @throws ClassNotFoundException
     47      */
     48     public static Connection getConnection()
     49         throws SQLException, ClassNotFoundException
     50     {
     51         Connection conn = null;
     52         try
     53         {
     54             registerDriver();
     55             conn = DriverManager.getConnection(URL, user, password);
     56         }
     57         catch (SQLException e)
     58         {
     59             System.out.println((new StringBuilder("【得到数据库连接时,发生异常】
    ")).append(e.getMessage()).toString());
     60             throw e;
     61         }
     62         return conn;
     63     }
     64 
     65     public static int executeUpdate(String sql, Object args[])
     66     {
     67         int rows;
     68         rows = -1;
     69         Connection conn = null;
     70         PreparedStatement pst = null;
     71          try {
     72             conn=getConnection();
     73             pst=conn.prepareStatement(sql);
     74             if (args != null)
     75                 {
     76                     for (int i = 0; i < args.length; i++)
     77                         pst.setObject(i + 1, args[i]);
     78         
     79                 }
     80                 rows = pst.executeUpdate();
     81                 close(pst);
     82                 close(conn);
     83                 return rows;
     84         } catch (SQLException e) {
     85             // TODO Auto-generated catch block
     86             e.printStackTrace();
     87         } catch (ClassNotFoundException e) {
     88             // TODO Auto-generated catch block
     89             e.printStackTrace();
     90         }
     91          return -1;
     92     }
     93 
     94     public static void close(Connection conn)
     95         throws SQLException
     96     {
     97         if (conn != null)
     98             try
     99             {
    100                 conn.close();
    101             }
    102             catch (SQLException e)
    103             {
    104                 System.out.println((new StringBuilder("【数据库连接对象在关闭时,发生异常!】
    【异常信息】")).append(e.getMessage()).toString());
    105                 throw e;
    106             }
    107     }
    108 
    109     public static void close(Statement state)
    110         throws SQLException
    111     {
    112         if (state != null)
    113             try
    114             {
    115                 state.close();
    116             }
    117             catch (SQLException e)
    118             {
    119                 System.out.println((new StringBuilder("【SQL命令对象在关闭时,发生异常!】
    【异常信息】")).append(e.getMessage()).toString());
    120                 throw e;
    121             }
    122     }
    123 
    124     public static void close(PreparedStatement pst)
    125         throws SQLException
    126     {
    127         if (pst != null)
    128             try
    129             {
    130                 pst.close();
    131             }
    132             catch (SQLException e)
    133             {
    134                 System.out.println((new StringBuilder("【预处理SQL命令对象在关闭时,发生异常!】
    【异常信息】")).append(e.getMessage()).toString());
    135                 throw e;
    136             }
    137     }
    138 
    139     public static void close(ResultSet rs)
    140         throws SQLException
    141     {
    142         if (rs != null)
    143             try
    144             {
    145                 rs.close();
    146             }
    147             catch (SQLException e)
    148             {
    149                 System.out.println((new StringBuilder("【关闭结果集对象时发生异常!】
    【异常信息】")).append(e.getMessage()).toString());
    150                 throw e;
    151             }
    152     }
    153 }

      (2)UserBean.java

     1 package com.phome.crud;
     2 
     3 public class UserBean {
     4     private int id;
     5     private String loginid;
     6     private String loginpwd;
     7     private String name;
     8     private String gender;
     9     private int age;
    10     public int getId() {
    11         return id;
    12     }
    13     public void setId(int id) {
    14         this.id = id;
    15     }
    16     public String getLoginid() {
    17         return loginid;
    18     }
    19     public void setLoginid(String loginid) {
    20         this.loginid = loginid;
    21     }
    22     public String getLoginpwd() {
    23         return loginpwd;
    24     }
    25     public void setLoginpwd(String loginpwd) {
    26         this.loginpwd = loginpwd;
    27     }
    28     public String getName() {
    29         return name;
    30     }
    31     public void setName(String name) {
    32         this.name = name;
    33     }
    34     public String getGender() {
    35         return gender;
    36     }
    37     public void setGender(String gender) {
    38         this.gender = gender;
    39     }
    40     public int getAge() {
    41         return age;
    42     }
    43     public void setAge(int age) {
    44         this.age = age;
    45     }
    46     
    47 }

      (3).UserDao.java

      1 package com.phome.crud;
      2 
      3 import java.sql.Connection;
      4 import java.sql.PreparedStatement;
      5 import java.sql.ResultSet;
      6 import java.sql.SQLException;
      7 import java.util.ArrayList;
      8 import java.util.List;
      9 
     10 public class UserDao {
     11     public List<UserBean> list_users(){
     12         List<UserBean> list = new ArrayList<UserBean>();
     13         String sql = "select * from users";
     14         
     15         try {
     16             Connection conn = DbUtil.getConnection();
     17             PreparedStatement pst = conn.prepareStatement(sql);
     18             ResultSet rs = pst.executeQuery();
     19             while(rs.next()){
     20                 UserBean user = new UserBean();
     21                 user.setId(rs.getInt("id"));
     22                 user.setLoginid(rs.getString("loginid"));
     23                 user.setLoginpwd(rs.getString("loginpwd"));
     24                 user.setName(rs.getString("name"));
     25                 user.setGender(rs.getString("gender"));
     26                 user.setAge(rs.getInt("age"));
     27                 
     28                 list.add(user);
     29             }
     30             rs.close();
     31             pst.close();
     32             conn.close();
     33         } catch (SQLException e) {
     34             e.printStackTrace();
     35         } catch (ClassNotFoundException e) {
     36             e.printStackTrace();
     37         }
     38         return list;
     39     }
     40     
     41     public UserBean getUser(int id){
     42         UserBean user = new UserBean();
     43         String sql = "select * from users where id = " + id;
     44         
     45         try {
     46             Connection conn = DbUtil.getConnection();
     47             PreparedStatement pst = conn.prepareStatement(sql);
     48             ResultSet rs = pst.executeQuery();
     49             while(rs.next()){
     50                 user.setId(rs.getInt("id"));
     51                 user.setLoginid(rs.getString("loginid"));
     52                 user.setLoginpwd(rs.getString("loginpwd"));
     53                 user.setName(rs.getString("name"));
     54                 user.setGender(rs.getString("gender"));
     55                 user.setAge(rs.getInt("age"));
     56                 
     57             }
     58             rs.close();
     59             pst.close();
     60             conn.close();
     61         } catch (SQLException e) {
     62             e.printStackTrace();
     63         } catch (ClassNotFoundException e) {
     64             e.printStackTrace();
     65         }
     66         
     67         return user;
     68     }
     69     
     70     public int edit(UserBean user,int id){
     71         String sql = "UPDATE users SET name=?,gender=?,age=? WHERE id="+id;
     72         
     73         try {
     74             Connection conn = DbUtil.getConnection();
     75             PreparedStatement pst = conn.prepareStatement(sql);
     76             
     77             pst.setString(1,user.getName());
     78             pst.setString(2,user.getGender());
     79             pst.setInt(3,user.getAge());
     80             
     81             int rows = pst.executeUpdate();
     82             
     83             pst.close();
     84             conn.close();
     85             return rows;
     86         } catch (SQLException e) {
     87             e.printStackTrace();
     88         } catch (ClassNotFoundException e) {
     89             e.printStackTrace();
     90         }
     91         return -1;
     92     }
     93     
     94     public int add(UserBean user){
     95         String sql = "INSERT INTO users VALUES(DEFAULT,?,?,?,?,?)";
     96         
     97         try {
     98             Connection conn = DbUtil.getConnection();
     99             PreparedStatement pst = conn.prepareStatement(sql);
    100             
    101             pst.setString(1,user.getLoginid());
    102             pst.setString(2,user.getLoginpwd());
    103             pst.setString(3,user.getName());
    104             pst.setString(4,user.getGender());
    105             pst.setInt(5,user.getAge());
    106             
    107             int rows = pst.executeUpdate();
    108             
    109             pst.close();
    110             conn.close();
    111             return rows;
    112         } catch (SQLException e) {
    113             // TODO Auto-generated catch block
    114             e.printStackTrace();
    115         } catch (ClassNotFoundException e) {
    116             // TODO Auto-generated catch block
    117             e.printStackTrace();
    118         }
    119         return -1;
    120     }
    121 }

      (4)UserAction.java

     1 package com.phome.crud;
     2 
     3 import java.util.List;
     4 
     5 import javax.servlet.http.HttpSession;
     6 
     7 import org.apache.struts2.ServletActionContext;
     8 
     9 import com.opensymphony.xwork2.ActionSupport;
    10 
    11 public class UserAction extends ActionSupport {
    12     List<UserBean> users = null;
    13     public List<UserBean> getUsers() {
    14         return users;
    15     }
    16     public void setUsers(List<UserBean> users) {
    17         this.users = users;
    18     }
    19     
    20     UserBean user = new UserBean();
    21     public UserBean getUser() {
    22         return user;
    23     }
    24     public void setUser(UserBean user) {
    25         this.user = user;
    26     }
    27 
    28     UserDao dao = new UserDao();
    29     
    30     public String list_users(){
    31         HttpSession s = ServletActionContext.getRequest().getSession();
    32         
    33         users = dao.list_users();
    34         s.setAttribute("users", users);
    35         System.out.println(users.toArray());
    36         return SUCCESS;
    37     }
    38     
    39     public String get(){
    40         int id = Integer.parseInt(ServletActionContext.getRequest().getParameter("id"));
    41         //HttpSession s = ServletActionContext.getRequest().getSession();
    42         user = dao.getUser(id);
    43         //s.setAttribute("user", user);
    44         return SUCCESS;
    45     }
    46     public String edit(){
    47         int id = Integer.parseInt(ServletActionContext.getRequest().getParameter("id"));
    48         dao.edit(user, id);
    49         return SUCCESS;
    50     }
    51     public String add(){
    52         dao.add(user);
    53         return SUCCESS;
    54     }
    55 }

      (5)struts.xml

     1 <?xml version="1.0" encoding="UTF-8" ?>
     2 <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd">
     3 <struts>
     4     <package name="suibian" extends="struts-default" namespace="/">
     5         <action name="Test" class="com.phome.test.TestAction" method="excute">
     6             <result name="success">/list.jsp</result>
     7             
     8         </action>
     9     </package>
    10     
    11     <package name="list" extends="struts-default" namespace="/">
    12         <action name="list" class="com.phome.crud.UserAction" method="list_users">
    13             <result name="success">/list.jsp</result>
    14         </action>
    15         <action name="get" class="com.phome.crud.UserAction" method="get">
    16             <result name="success">/edit.jsp</result>
    17         </action>
    18         <action name="edit" class="com.phome.crud.UserAction" method="edit">
    19             <result name="success" type="redirectAction">list</result>
    20         </action>
    21         <action name="add" class="com.phome.crud.UserAction" method="add">
    22             <result name="success" type="redirectAction">list</result>
    23         </action>
    24     </package>
    25 </struts>    

      (6)list.jsp

     1 <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
     2 <%@ taglib  prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
     3 
     4 <%
     5     String path = request.getContextPath();
     6     String basePath = request.getScheme() + "://"
     7             + request.getServerName() + ":" + request.getServerPort()
     8             + path + "/";
     9 %>
    10 
    11 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    12 <html>
    13   <head>
    14     <title>User List</title>
    15     
    16     <script type="text/javascript">
    17     function del(src) {
    18         if (confirm("确定要删除吗?")) {
    19             window.location.href(src);
    20             return;
    21         }
    22     }
    23 </script>
    24   </head>
    25   
    26   <body>
    27    <div align="center">
    28       <h1>用户列表</h1>
    29       <a href="add.jsp"><strong>添加用户</strong></a><br/><br/>
    30     <table align="center" border="1" cellspacing="0" cellpadding="0">
    31        <thead style="background-color: #eeeeee">
    32          <tr>
    33            <th width="200px" >ID</th>
    34            <th width="200px" >姓名</th>
    35            <th width="200px" >性别</th>
    36            <th width="200px" >年龄</th>
    37            <th width="200px" >操作</th>
    38          </tr>
    39        </thead>
    40        <tbody>
    41         <c:forEach items="${users}" var="user">
    42          <tr height="15px">
    43            <td align="center">${user.id }</td>
    44            <td align="center">${user.name }</td>
    45            <td align="center">${user.gender }</td>
    46            <td align="center">${user.age }</td>
    47            <td align="center"><a href="${pageContext.request.contextPath }/get.action?id=${user.id }">修改</a>&nbsp;&nbsp;
    48                <a href="" onclick="del('bathPath')">删除</a></td>
    49          </tr>
    50         </c:forEach>
    51        </tbody>
    52     </table>
    53    </div>
    54   </body>
    55 </html>

      (7)add.jsp

    <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
    
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
      <head>
        <title>add product</title>
      </head>
      
      <body>
       <div align="center">
       <h1>add user</h1>
       <form action="${pageContext.request.contextPath }/add.action" method="post">
           <table>
             <tr>
               <td width="80px">登陆名:</td>
                 <td><input type="text" name="user.loginid" value="${user.loginid }"/></td>
          </tr>
             <tr>
               <td width="80px">登陆密码:</td>
                 <td><input type="text" name="user.loginpwd" value="${user.loginpwd }"/></td>
          </tr>
             <tr>
               <td width="80px">姓名:</td>
                 <td><input type="text" name="user.name" value="${user.name }"/></td>
          </tr>
             <tr>
               <td width="80px">性别:</td>
                 <td><input type="text" name="user.gender" value="${user.gender }"/></td>
          </tr>
             <tr>
               <td width="80px">年龄:</td>
                 <td><input type="text" name="user.age" value="${user.age }"/></td>
          </tr>
             
             <tr>
                 <td><a href="${pageContext.request.contextPath }/list.action">返回</a></td>
                 <td><input type="submit" value="添加"/></td>
          </tr>
           </table>
       </form>
       </div>
      </body>
    </html>

      (8)edit.jsp

     1 <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
     2 
     3 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
     4 <html>
     5   <head>
     6     <title>update user</title>
     7   </head>
     8   
     9   <body>
    10    <div align="center">
    11    <h1>修改user</h1>
    12    <form action="${pageContext.request.contextPath }/edit.action?id=${user.id }" method="post">
    13        <input type="hidden" name="user.id" value="${user.id }"/>
    14        <input type="hidden" name="user.loginid" value="${user.loginid }"/>
    15        <input type="hidden" name="user.loginpwd" value="${user.loginpwd }"/>
    16        <table>
    17          <tr>
    18            <td width="80px">姓名:</td>
    19              <td><input type="text" name="user.name" value="${user.name }"/></td>
    20       </tr>
    21          <tr>
    22            <td width="80px">性别:</td>
    23              <td><input type="text" name="user.gender" value="${user.gender }"/></td>
    24       </tr>
    25          <tr>
    26            <td width="80px">年龄:</td>
    27              <td><input type="text" name="user.age" value="${user.age }"/></td>
    28       </tr>
    29          
    30          <tr>
    31              <td><a href="${pageContext.request.contextPath }/list.action">返回</a></td>
    32              <td><input type="submit" value="修改"/></td>
    33       </tr>
    34        </table>
    35    </form>
    36    </div>
    37   </body>
    38 </html>


    5.效果展示

    逃避不一定躲得过,面对不一定最难过
  • 相关阅读:
    Gstreamer 随笔
    Git 提交(commit)没有自动生成Change-Id导致无法push
    xmake构建C/C++编译环境
    编译configure常用参数详解
    ubuntu上安装meson & 如何使用meson编译C代码
    如何使用autotools/automake自动生成Makefile文件
    如何扩大镜像文件容量
    Mac OS X 键盘快捷键
    django 文件目录结构
    oh-my-zsh 更换主题后特殊字符显示错误
  • 原文地址:https://www.cnblogs.com/yangzhenlong/p/3354987.html
Copyright © 2020-2023  润新知