struts1+jdbc增删改查

struts1+jdbc实现增删改查

数据库建表

工程目录

jar包

home.jsp

</head>
<body>
    <a href="http://localhost:8080/myStruts1/login.jsp">登录</a><br/>
    <a href="http://localhost:8080/myStruts1/register.jsp">注册</a>
 
</body>
</html>

login.jsp

<title>登录</title>
</head>
<body>
    <form action="login.do" method="post">
            用户名:<input type="text" name="username">
             密码:<input type="password" name="password">
            <input type="submit" value="登录">
    </form>
    
    <%
    String msg = (String)request.getAttribute("message");
    if(msg != null){
        out.print("<script  language = 'javascript'>alert("+ msg +")</script>");
    }
    %>
</body>

register.jsp

<body>
    <form action="addUser.do" method="post">
                用户名<input type="text" name="username"><br/><br/><br/>
                密码<input type="password" name="password"><br/><br/><br/>
                <input type="submit" value="提交">
                <input type="reset" value="取消">
    </form>
</body>
</html>

success.jsp

<body>
    
    <script language = "javascript">  
      alert("成功!");  
      window.location.href="http://localhost:8080/myStruts1/login.jsp";
      </script>
    
</body>

userList.jsp

<body>
<form action=" " method="post">
    <table border="1">
        <thead >
            <tr>
                <th>编号</th>
                <th>用户名</th>
                <th>密码</th>
                <th colspan="2">操作</th>
            </tr>
        </thead>
        
        <%
           List<User> list= (List) request.getAttribute("users");
           if(list != null){
               Iterator iter = list.iterator();
               while(iter.hasNext()){
                   User user = (User)iter.next();
                   
               %>
        <tbody>
            <tr>
                <td><input type="text" name="id" value="<%=user.getId() %>"></td>
                <td><input type="text" name="username" value="<%=user.getUsername() %>"></td>
                <td><input type="text" name="password" value="<%=user.getPassword() %>"></td>
                <td>
                    <a href="updateUser.do?id=<%=user.getId() %>">修改</a>
                </td>
                 <td>
                    <a href="deleteUser.do?id=<%=user.getId() %>">删除</a>
                </td>
            </tr>
            <%
             }
               
           }
           %>
           <a href="http://localhost:8080/myStruts1/register.jsp">添加</a>
        </tbody>
        
    </table>
   </form>
</body>

oneUserUpdate.jsp

<body>
    <form action="update.do" method="post">
        <table border="1">
            <tr>
                <td>编号</td>
                <td>用户名</td>
                <td>密码</td>
            </tr>
            <tr>
            <%
                User u =(User)request.getAttribute("user");
                
            %>
                   <td><input type="text" name="id" value="<%=u.getId() %>"></td>
                   <td><input type="text" name="username" value="<%=u.getUsername() %>"></td>
                   <td><input type="text" name="password" value="<%=u.getPassword() %>"></td>
                </tr>
        </table>
        <input type="submit" value="确定">
    </form>
</body>

public class User {
    
    private static final long serialVersionUID = -2671034378597589800L;
    private int id;
    private String username;
    private String password;
    
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    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 class LoginForm extends ActionForm{
    /**
     *
     */
    private static final long serialVersionUID = 753565084538894694L;
    private int id;
    
    private String username;
    
    private String password;
    
    
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    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 class DB {
    public static Connection getConnection() throws SQLException{
        String driverName = "com.mysql.jdbc.Driver";
        String url = "jdbc:mysql://172.19.1.81/struts1Demo";
        String userName = "root";
        String passWord = "navinfo";
        Connection conn = null;
        try {
            Class.forName(driverName);
            conn = DriverManager.getConnection(url, userName, passWord);
            conn.setAutoCommit(false);//支持事物
            System.out.println("connection success");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return conn;
    }
    
    public static void closeConnection(Connection conn){
        try {
            if(conn != null){
                conn.close();
            }
            conn = null;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    public static void closeStatement(Statement stmt){
        try {
            if(stmt != null){
                stmt.close();
            }
            stmt = null;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    
    public static void closeResultSet(ResultSet rs){
        try {
            if(rs != null){
                rs.close();
            }
            rs = null;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
}

public class AddUserDao {
    public void add(User user){
        Connection conn = null;
        PreparedStatement pstm = null;
        
        try {
            conn = DB.getConnection();
            String sql = "insert into userInfo(username , password) values(?,?)";
            pstm = conn.prepareStatement(sql);
            //pstm.setInt(1, user.getId());
            pstm.setString(1, user.getUsername());
            pstm.setString(2, user.getPassword());
            pstm.executeUpdate();
            System.out.println("*****");
            conn.commit();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

public class DeleteUserDao {
    public boolean delete(int id){
        Connection conn = null;
        PreparedStatement pstm = null;
        int count = 0;
        try {
            conn = DB.getConnection();
            String sql = "delete from userInfo where id = ?";
            pstm = conn.prepareStatement(sql);
            pstm.setInt(1, id);
            count = pstm.executeUpdate();
           conn.commit();
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
                try {
                    if(pstm!= null){
                        pstm.close();}
                    if(conn!=null){
                        conn.close();
                    }
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
       if(count == 0){
           return false;
       }else{
           return true;
       }
    }
}

public class FindAllUserDao {
    public List<User> find(){
        Connection conn = null;
        ResultSet rs = null;
        User user = null;
        List<User> listUser = new ArrayList<User>();
        try {
            conn = DB.getConnection();
            String sql = "select * from userInfo ";
            rs = conn.prepareStatement(sql).executeQuery();
            while(rs.next()){
                user = new User();
                user.setId(rs.getInt("id"));
                user.setUsername(rs.getString("username"));
                user.setPassword(rs.getString("password"));
                listUser.add(user);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return listUser;
    }
}

public class SearchDao {
    public User findByUsername(String username , String password){
        Connection conn = null;
        PreparedStatement pstm = null;
        ResultSet rs = null;
        User user = null;
        try {
            conn = DB.getConnection();
            String sql = "select * from userInfo where username = ? and password = ?";
            pstm = conn.prepareStatement(sql);
            pstm.setString(1, username);
            pstm.setString(2, password);
            rs = pstm.executeQuery();
            if(rs.next()){
                user = new User();
                user.setId(rs.getInt("id"));
                user.setUsername(rs.getString("username"));
                user.setPassword(rs.getString("password"));
                
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return user;
    }
}


public class UpdateUser {
    public void update(User user){
        Connection conn = null;
        PreparedStatement pstm = null;
        try {
            conn = DB.getConnection();
            String sql = "update userInfo set username= ? , password = ? where id = ?";
            pstm = conn.prepareStatement(sql);
            pstm.setString(1, user.getUsername());
            pstm.setString(2, user.getPassword());
            pstm.setInt(3, user.getId());
            pstm.executeUpdate();
            
            conn.commit();
            
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    
    
    public User getUserById(int id){
        Connection  conn = null;
        PreparedStatement pstm = null;
        ResultSet rs = null;
        User user = null;
         try {
            conn = DB.getConnection();
            String sql = "select * from userInfo where id = ?";
            pstm = conn.prepareStatement(sql);
            pstm.setInt(1,id);
            rs = pstm.executeQuery();
            if(rs.next()){
                user = new User();
                user.setId(rs.getInt("id"));
                user.setUsername(rs.getString("username"));
                user.setPassword(rs.getString("password"));
            }
        } catch (Exception e) {
            e.printStackTrace();
    }
         return user;
    }
}

public class UserByIdDao {
    public User getUserById(int id){
        Connection conn = null;
        PreparedStatement pstm = null;
        ResultSet rs = null;
        User user = null;
        try {
            conn = DB.getConnection();
            String sql = "select * from userInfo where id = ?";
            pstm = conn.prepareStatement(sql);
            pstm.setInt(1, id);
            rs = pstm.executeQuery();
            if(rs.next()){
                user = new User();
                user.setId(rs.getInt("id"));
                user.setUsername(rs.getString("username"));
                user.setPassword(rs.getString("password"));
                
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            DB.closeResultSet(rs);
            DB.closeStatement(pstm);
            DB.closeConnection(conn);
        }
        return user;
    }
}

public class AddAction extends Action{
    
    public ActionForward execute(ActionMapping mapping, ActionForm form,  
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {  
       
        AddUserDao addUserDao = new AddUserDao();
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        
        addUserDao.add(user);
        System.out.println("#########");
        return mapping.findForward("add");
    }
}

public class DeleteUserAction extends Action{
    DeleteUserDao deleteUserDao = new DeleteUserDao();
    FindAllUserDao findAllUserDao = new FindAllUserDao();
    @Override
    public ActionForward execute(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        String id  = request.getParameter("id");
        int id1 = Integer.parseInt(id);
        deleteUserDao.delete(id1);
        List<User> users = findAllUserDao.find();
        request.setAttribute("users", users);
        return mapping.findForward("success");
    }
    
}

public class FindAllAction extends Action{
    public ActionForward excute(ActionMapping mapping, ActionForm form,  HttpServletRequest request, HttpServletResponse response) throws Exception{
        FindAllUserDao findAllUserDao = new FindAllUserDao();
       List<User> users= findAllUserDao.find();
       request.setAttribute("users", users);
        return mapping.findForward("findAllUser");
    }
}

public class FindUserByIdAction extends Action{

    @Override
    public ActionForward execute(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse httpservletresponse)
            throws Exception {
        UserByIdDao userByIdDao = new UserByIdDao();
        String id = request.getParameter("id");
        int id1 = Integer.parseInt(id);
        User u = userByIdDao.getUserById(id1);
        System.out.println(u.getUsername());
        request.setAttribute("user", u);
        return mapping.findForward("success");
    }
    
}
public class LoginAction extends Action{
    @Override  
    public ActionForward execute(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
       String str = "";
       /** 1. 获取ActonForm封装的请求对象 */
      // User login = (User) form;
      // System.out.println(login.getUsername());
       SearchDao ser = new SearchDao();
       String username = request.getParameter("username");
       String password = request.getParameter("password");
       User user = ser.findByUsername(username,password);
       if(user == null){
           request.setAttribute("message", "用户名或密码不能为空");
           str = "login";
           
       }else{
           FindAllUserDao findAllUserDao = new FindAllUserDao();
           List<User> users = findAllUserDao.find();
           request.setAttribute("users", users);
           str = "success";
       }
      return mapping.findForward(str);
    }
    
}

public class UpdateAction extends Action{
   
    public ActionForward execute(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {  
        
        String id = request.getParameter("id");
        int id1 = Integer.parseInt(id);
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        try {
            UpdateUser updateDao = new UpdateUser();
            User user= new User();
            user.setId(id1);
            user.setUsername(username);
            user.setPassword(password);
            updateDao.update(user);
            System.out.println("%%%%%%%%%%");
        } catch (Exception e) {
            e.printStackTrace();
        }
        FindAllUserDao findAll = new FindAllUserDao();
        List<User> list = findAll.find();
        request.setAttribute("users", list);
        return mapping.findForward("success");
        
    }
}

struts-config.xml

<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE struts-config PUBLIC
          "-//Apache Software Foundation//DTD Struts Configuration 1.3//EN"
          "http://struts.apache.org/dtds/struts-config_1_3.dtd">
<struts-config>
<!--  该元素主要用来配置表单验证的类 -->
    <form-beans>
        <!--  --><form-bean name="loginForm" type = "com.pojo.LoginForm"/>
        <!-- <form-bean name="AddUserForm" type="com.pojo.AddUserForm"/> -->
    </form-beans>

    <global-exceptions>
    </global-exceptions>
    
    <global-forwards>
    </global-forwards>


<!-- =========================================== Action Mapping Definitions -->

    <action-mappings>
          <!-- action标签中的path就是截取到的url,type就是对应的action全路径,name是这个action对应的form。 -->  
         <action path = "/login" name = "User" scope = "request"  type = "com.action.LoginAction" validate = "false">  
                <forward name = "success" path = "/userList.jsp"/>  
                <forward name = "login" path = "/login.jsp"/>  
          </action>
          
          <action path="/addUser" name="AddUserForm" scope="request" type="com.action.AddAction" validate="false">
                <forward name="add" path="/success.jsp"></forward>
          </action>
          
          <action path="/updateUser"  scope="request" type="com.action.FindUserByIdAction" validate="false">
                <forward name="success" path="/oneUserUpdate.jsp"></forward>
          </action>
          
          <action path="/update"  scope="request" type="com.action.UpdateAction" validate="false">
                <forward name="success" path="/userList.jsp"></forward>
          </action>
          
          <action path="/findAllUser"  scope="request" type="com.action.FindAllAction" validate="false">
                <forward name="findAllUser" path="/userList.jsp"></forward>
          </action>
          
           <action path="/deleteUser"  scope="request" type="com.action.DeleteUserAction" validate="false">
                <forward name="success" path="/userList.jsp"></forward>
          </action>

    </action-mappings>
    <message-resources parameter="MessageResources" />
 

</struts-config>


web.xml

 <servlet>
        <servlet-name>action</servlet-name>
        <servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
        <init-param>
           <param-name>config</param-name>
           <param-value>/WEB-INF/struts-config.xml</param-value>
        </init-param>
        <load-on-startup>2</load-on-startup>
    </servlet>
    
    <servlet-mapping>
        <servlet-name>action</servlet-name>
        <url-pattern>*.do</url-pattern>
    </servlet-mapping>





  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值