6月7日 SSH 周四

时间:2021-12-15 13:55:08
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
    <session-factory>
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="connection.url">jdbc:mysql:///cms10</property>
        <property name="connection.username">root</property>
        <property name="connection.password">root</property>
        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>

        <property name="hbm2ddl.auto">update</property>
        <property name="show_sql">true</property>
        <property name="format_sql">true</property>

        <mapping resource="com/dto/User.hbm.xml"/>
    </session-factory>
</hibernate-configuration>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1.7//EN" "http://struts.apache.org/dtds/struts-2.1.7.dtd">

<struts>
    <constant name="struts.devMode" value="true"></constant>

    <package name="abc" extends="struts-default">
        <action name="u_*" class="com.action.Action" method="{1}">
            <result name="list">list.jsp</result>
        </action>
    </package>
</struts>
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
    <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>
  <display-name></display-name> 
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
    <class name="com.dto.User" table="a_user">
        <id name="id">
            <generator class="native"></generator>
        </id>
        <property name="name"/>
        <property name="sex"/>
        <property name="age"/>
    </class>
</hibernate-mapping>
package com.dto;

public class User {
    private Integer id;
    private String name;
    private String sex;
    private Integer age;
    public User() {
        super();
        // TODO Auto-generated constructor stub
    }
    public User(Integer id, String name, String sex, Integer age) {
        super();
        this.id = id;
        this.name = name;
        this.sex = sex;
        this.age = age;
    }
    @Override
    public String toString() {
        return "User [id=" + id + ", name=" + name + ", sex=" + sex + ", age="
                + age + "]";
    }
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getSex() {
        return sex;
    }
    public void setSex(String sex) {
        this.sex = sex;
    }
    public Integer getAge() {
        return age;
    }
    public void setAge(Integer age) {
        this.age = age;
    }


}
package com.action;

import java.io.IOException;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.struts2.ServletActionContext;

import com.dto.User;
import com.service.UserService;
import com.util.PageUtils;


public class Action {
    private UserService service = new UserService();
    private List<User> list;
    private User user;
    private PageUtils pu;
    private Integer cpage;
    private String *;

    public String list(){
        if(cpage==null){
            cpage = 1;
        }
        Integer pageSize = 2;
        Integer count = service.getCount();
        pu = new PageUtils(cpage, pageSize, count);
        list = service.list(pu,*);
        return "list";  
    }
    public void getUsers() throws Exception{
        user = service.getUesr(user);
        System.out.println(user);
        JSONObject jsonObject = JSONObject.fromObject(user);
        HttpServletResponse response = ServletActionContext.getResponse();
        response.setCharacterEncoding("utf-8");
        response.getWriter().print(jsonObject);
    }

    public void update() throws Exception{
        int i = service.update(user);
        System.out.println(i);
        HttpServletResponse response = ServletActionContext.getResponse();
        response.getWriter().print(i);
    }

    public void delete() throws Exception{
        int i = service.delete(user);
        System.out.println(i);
        HttpServletResponse response = ServletActionContext.getResponse();
        response.getWriter().print(i);
    }


    public List<User> getList() {
        return list;
    }


    public void setList(List<User> list) {
        this.list = list;
    }
    public void setUser(User user) {
        this.user = user;
    }
    public User getUser() {
        return user;
    }
    public PageUtils getPu() {
        return pu;
    }
    public void setPu(PageUtils pu) {
        this.pu = pu;
    }
    public Integer getCpage() {
        return cpage;
    }
    public void setCpage(Integer cpage) {
        this.cpage = cpage;
    }
    public String get*() {
        return *;
    }
    public void set*(String *) {
        this.* = *;
    }


}
package com.service;

import java.util.List;

import com.dao.UserDao;
import com.dto.User;
import com.util.PageUtils;

public class UserService {
    private UserDao dao = new UserDao();

    public List<User> list(PageUtils pu, String *) {
        // TODO Auto-generated method stub
        return dao.list(pu,*);
    }

    public User getUesr(User user) {
        // TODO Auto-generated method stub
        return dao.getUesr(user);
    }

    public int update(User user) {
        // TODO Auto-generated method stub
        return dao.update(user);
    }

    public int delete(User user) {
        // TODO Auto-generated method stub
        return dao.delete(user);
    }

    public Integer getCount() {
        // TODO Auto-generated method stub
        return dao.getCount();
    }
}
package com.dao;

import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.Transaction;

import com.dto.User;
import com.util.HibernateUtils;
import com.util.PageUtils;

public class UserDao {

    public List<User> list(PageUtils pu, String *) {
        // TODO Auto-generated method stub
        Session session = HibernateUtils.getSession();
        String sql =" select * from a_user ";
        if(*!=null){
            sql = " select * from a_user where name like '%"+*+"%'";
        }
        SQLQuery sqlQuery = session.createSQLQuery(sql).addEntity(User.class);
//      String hql =" from User ";
//      Query query = session.createQuery(hql);
//      query.setFirstResult(pu.getStartIndex()).setMaxResults(pu.getPageSize());
//      List list = query.list();
        List list = sqlQuery.list();
        session.close();

        return list;
    }

    public User getUesr(User user) {
        // TODO Auto-generated method stub
        Session session = HibernateUtils.getSession();
        String sql =" select * from a_user where id="+user.getId();
        SQLQuery sqlQuery = session.createSQLQuery(sql).addEntity(User.class);
        User u = (User) sqlQuery.uniqueResult();
//      User u = (User) session.get(User.class, user.getId());
        return u;
    }

    public int update(User user) {
        // TODO Auto-generated method stub
        Session session = HibernateUtils.getSession();
//      try {
//          Transaction transaction = session.beginTransaction();
//          session.saveOrUpdate(user);
//          transaction.commit();
//          return 1;
//      } catch (HibernateException e) {
//          // TODO Auto-generated catch block
//          e.printStackTrace();
//          return 0 ;
//      }finally {
//          session.close();
//      }
        String sql =" update a_user set name='"+user.getName()+"',sex='"+user.getSex()+"',age="+user.getAge()+" where id="+user.getId();
        if(user.getId()==null){
            sql = " insert into a_user set name='"+user.getName()+"',sex='"+user.getSex()+"',age="+user.getAge();
        }
        Transaction transaction = session.beginTransaction();
        SQLQuery sqlQuery = session.createSQLQuery(sql);
        int i = sqlQuery.executeUpdate();
        transaction.commit();
        session.close();
        return i;
    }

    public int delete(User user) {
        // TODO Auto-generated method stub
        Session session = HibernateUtils.getSession();
        String sql =" delete from a_user where id = "+user.getId();
        //      try {
//          Transaction transaction = session.beginTransaction();
//          session.delete(user);
//          transaction.commit();
//          return 1;
//      } catch (HibernateException e) {
//          // TODO Auto-generated catch block
//          e.printStackTrace();
//          return 0 ;
//      }finally {
//          session.close();
//      }
        Transaction transaction = session.beginTransaction();
        SQLQuery sqlQuery = session.createSQLQuery(sql);
        int i = sqlQuery.executeUpdate();
        session.close();
        return i;
    }

    public Integer getCount() {
        // TODO Auto-generated method stub
        Session session = HibernateUtils.getSession();
        Query query = session.createQuery("select count(*) from User");
        String s = query.uniqueResult().toString();
        Integer count = Integer.valueOf(s);
        session.close();

        return count;
    }

}
package com.dao;

import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.Transaction;

import com.dto.User;
import com.util.HibernateUtils;
import com.util.PageUtils;

public class UserDao {

    public List<User> list(PageUtils pu, String *) {
        // TODO Auto-generated method stub
        Session session = HibernateUtils.getSession();
        String sql =" select * from a_user ";
        if(*!=null){
            sql = " select * from a_user where name like '%"+*+"%'";
        }
        SQLQuery sqlQuery = session.createSQLQuery(sql).addEntity(User.class);
//      String hql =" from User ";
//      Query query = session.createQuery(hql);
//      query.setFirstResult(pu.getStartIndex()).setMaxResults(pu.getPageSize());
//      List list = query.list();
        List list = sqlQuery.list();
        session.close();

        return list;
    }

    public User getUesr(User user) {
        // TODO Auto-generated method stub
        Session session = HibernateUtils.getSession();
        String sql =" select * from a_user where id="+user.getId();
        SQLQuery sqlQuery = session.createSQLQuery(sql).addEntity(User.class);
        User u = (User) sqlQuery.uniqueResult();
//      User u = (User) session.get(User.class, user.getId());
        return u;
    }

    public int update(User user) {
        // TODO Auto-generated method stub
        Session session = HibernateUtils.getSession();
//      try {
//          Transaction transaction = session.beginTransaction();
//          session.saveOrUpdate(user);
//          transaction.commit();
//          return 1;
//      } catch (HibernateException e) {
//          // TODO Auto-generated catch block
//          e.printStackTrace();
//          return 0 ;
//      }finally {
//          session.close();
//      }
        String sql =" update a_user set name='"+user.getName()+"',sex='"+user.getSex()+"',age="+user.getAge()+" where id="+user.getId();
        if(user.getId()==null){
            sql = " insert into a_user set name='"+user.getName()+"',sex='"+user.getSex()+"',age="+user.getAge();
        }
        Transaction transaction = session.beginTransaction();
        SQLQuery sqlQuery = session.createSQLQuery(sql);
        int i = sqlQuery.executeUpdate();
        transaction.commit();
        session.close();
        return i;
    }

    public int delete(User user) {
        // TODO Auto-generated method stub
        Session session = HibernateUtils.getSession();
        String sql =" delete from a_user where id = "+user.getId();
        //      try {
//          Transaction transaction = session.beginTransaction();
//          session.delete(user);
//          transaction.commit();
//          return 1;
//      } catch (HibernateException e) {
//          // TODO Auto-generated catch block
//          e.printStackTrace();
//          return 0 ;
//      }finally {
//          session.close();
//      }
        Transaction transaction = session.beginTransaction();
        SQLQuery sqlQuery = session.createSQLQuery(sql);
        int i = sqlQuery.executeUpdate();
        session.close();
        return i;
    }

    public Integer getCount() {
        // TODO Auto-generated method stub
        Session session = HibernateUtils.getSession();
        Query query = session.createQuery("select count(*) from User");
        String s = query.uniqueResult().toString();
        Integer count = Integer.valueOf(s);
        session.close();

        return count;
    }

}
package com.util;

public class PageUtils {

    private Integer cpage;//褰撳墠椤�
    private Integer pageSize;//姣忛〉灞曠ず鏈�ぇ鏉℃暟
    private Integer count;//鏁版嵁鎬绘潯鏁�
    private Integer totalPage;//鎬婚〉鏁�
    private Integer startIndex;//璧峰涓嬫爣
    private Integer prevPage;//涓婁竴椤�
    private Integer nextPage;//涓嬩竴椤�
    //浣跨敤姝ゅ伐鍏风被锛岃皟鐢ㄨ繖涓瀯閫犲櫒
    public PageUtils(Integer cpage, Integer pageSize, Integer count) {
        this.cpage = cpage;
        this.pageSize = pageSize;
        this.count = count;
        calPrevPage();
        calStartIndex();
        calTotalPage();
        calNextPage();
    }
    private void calTotalPage(){//璁$畻鎬婚〉鏁�
        this.totalPage = count/pageSize + (count%pageSize==0?0:1);
    }
    private void calStartIndex(){//璁$畻璧峰涓嬫爣
        this.startIndex = (cpage-1)*pageSize;
    }
    private void calPrevPage(){//璁$畻涓婁竴椤�
        this.prevPage = cpage==1?1:(cpage-1);
    }
    private void calNextPage(){//璁$畻涓嬩竴椤�
        this.nextPage = cpage.equals(totalPage)?totalPage:(cpage+1);
    }
    public Integer getCpage() {
        return cpage;
    }
    public void setCpage(Integer cpage) {
        this.cpage = cpage;
    }
    public Integer getPageSize() {
        return pageSize;
    }
    public void setPageSize(Integer pageSize) {
        this.pageSize = pageSize;
    }
    public Integer getCount() {
        return count;
    }
    public void setCount(Integer count) {
        this.count = count;
    }
    public Integer getTotalPage() {
        return totalPage;
    }
    public void setTotalPage(Integer totalPage) {
        this.totalPage = totalPage;
    }
    public Integer getStartIndex() {
        return startIndex;
    }
    public void setStartIndex(Integer startIndex) {
        this.startIndex = startIndex;
    }
    public Integer getPrevPage() {
        return prevPage;
    }
    public void setPrevPage(Integer prevPage) {
        this.prevPage = prevPage;
    }
    public Integer getNextPage() {
        return nextPage;
    }
    public void setNextPage(Integer nextPage) {
        this.nextPage = nextPage;
    }
}
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">

    <title>My JSP 'list.jsp' starting page</title>

    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!-- <link rel="stylesheet" type="text/css" href="styles.css"> -->

  <script type="text/javascript" src="js/jquery-1.8.2.js"></script>
  <script type="text/javascript"> function del(id){ if(confirm("确认要删除吗?")){ $.post( "u_delete", {"user.id":id}, function (obj){ if(obj==1){ alert("删除成功"); location="u_list"; }else if(obj==0){ alert("删除失败"); } } ); } } function gopage(cpage){ location = " u_list?cpage="+cpage; } </script>
  </head>

  <body>
    <table border="1px">
        <tr>
            <th>id</th>
            <th>name</th>
            <th>sex</th>
            <th>age</th>
            <th><input type="button" value="添加" onclick="location='update.jsp'"></th>
        </tr>
        <c:forEach var="u" items="${list}">
            <tr>
                <th>${u.id}</th>
                <th>${u.name}</th>
                <th>${u.sex}</th>
                <th>${u.age}</th>
                <th><input type="button" value="修改" onclick="location='update.jsp?id=${u.id}'">
                <input type="button" value="删除" onclick="del(${u.id})"></th>
            </tr>
        </c:forEach>
        <tr>
            <th colspan="21">
                <button onclick="gopage(1)">首页</button>
                <button onclick="gopage(${pu.prevPage})">上页</button>
                <button onclick="gopage(${pu.nextPage})">下页</button>
                <button onclick="gopage(${pu.totalPage})">末页</button>
                ${pu.cpage}/${pu.totalPage}页
            </th>
        </tr>
    </table>
  </body>
</html>
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">

    <title>My JSP 'update.jsp' starting page</title>

    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!-- <link rel="stylesheet" type="text/css" href="styles.css"> -->

  <script type="text/javascript" src="js/jquery-1.8.2.js"></script>
  <script type="text/javascript"> var id = "${param.id}"; $.post( "u_getUsers", {"user.id":id}, function (obj){ $("[name='user.id']").val(obj.id); $("[name='user.name']").val(obj.name); $("[name='user.sex'][value='"+obj.sex+"']").attr("checked",true); $("[name='user.age']").val(obj.age); },"json" ); function sub(){ $.post( "u_update", $("form").serialize(), function (obj){ if(obj==1){ alert("成功"); location="u_list"; }else if(obj==0){ alert("失败"); } },"json" ); } </script>
  </head>

  <body>
    <form>
        <input name="user.id" type="hidden"><br>
        name:<input name="user.name"><br>
        sex:<input name="user.sex" type="radio" value="男"><input name="user.sex" type="radio" value="女"><br>
        age:<input name="user.age"><br>
    </form>
        <input type="button" onclick="sub()" value="提交"/>
  </body>
</html>

浅浅的知识比无知更使人栗六不安,深深的知识使人安定,我们无非是落在这样的一片浅浅深深之中。
——木心 《鱼丽之宴》