当前位置:   article > 正文

SSH框架实现增删查改_ssh框架写按id查询数据库

ssh框架写按id查询数据库

TDemoUser.hbm.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC     
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"    
    "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">  
<hibernate-mapping>
   <class name="com.demo.database.data.TDemoUser" table="t_demo_users">     
       <id name="userId" column="user_id" type="java.lang.Integer">
           <!-- ID生成策略,即自动生成ID -->
           <generator class="native"></generator> <!-- 使用本地数据库的自动增长  uuid.hex-->
       </id>
       <property name="userName" column="user_name" type="java.lang.String"></property>
       <property name="userPassword" column="user_password" type="java.lang.String"></property>
       <property name="userGender" column="user_gender" type="java.lang.String"></property>
       <property name="userBirthday" column="user_birthday" type="java.sql.Date"></property>      
   </class>
</hibernate-mapping>


TDemoUser

package com.demo.database.data;


import java.io.Serializable;
import java.sql.Date;


/**
 * 用户持久化类
 * 
 * @author Teacher
 * @createTime 2018年3月23日 下午3:33:30
 * @updateTime 2018年3月23日 下午3:33:30
 * @version 1.0.0
 */
public class TDemoUser implements Serializable {


private Integer userId;
private String userName;
private String userPassword;
private String userGender;
private Date userBirthday;


public Integer getUserId() {
return userId;
}


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


public String getUserName() {
return userName;
}


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


public String getUserPassword() {
return userPassword;
}


public void setUserPassword(String userPassword) {
this.userPassword = userPassword;
}


public String getUserGender() {
return userGender;
}


public void setUserGender(String userGender) {
this.userGender = userGender;
}


public Date getUserBirthday() {
return userBirthday;
}


public void setUserBirthday(Date userBirthday) {
this.userBirthday = userBirthday;
}


}


UserAction

package com.demo.actions;


import java.util.List;
import com.demo.database.data.TDemoUser;
import com.demo.services.IUserService;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;


/**
 * 用户管理的业务控制器
 * @author Teacher
 * @createTime 2018年3月23日 下午4:32:12
 * @updateTime 2018年3月23日 下午4:32:12
 * @version 1.0.0
 */
public class UserAction extends ActionSupport {


private static final long serialVersionUID = 1L;
private IUserService iuserService; //定义用户管理业务接口
private TDemoUser user;  //定义用户对象变量
private String ids;
private Integer userId;


public String getIds() {
return ids;
}


public void setIds(String ids) {
this.ids = ids;
}


public Integer getUserId() {
return userId;
}


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


public IUserService getIuserService() {
return iuserService;
}


public void setIuserService(IUserService iuserService) {
this.iuserService = iuserService;
}

public TDemoUser getUser() {
return user;
}


public void setUser(TDemoUser user) {
this.user = user;
}


public String list() {
try {
//访问业务接口,查询数据
List<TDemoUser> list = iuserService.list();
//转发数据
ActionContext.getContext().put("list", list);
return "list";
} catch (Exception e) {
e.printStackTrace();
return "error";
}
}

public String add() {
try {
//访问业务接口,添加数据
iuserService.add(user);
return list();
} catch (Exception e) {
e.printStackTrace();
return "error";
}
}


public String delete() {
try {
String[] id = ids.split(",");
int[] userids = new int[id.length];
for(int i = 0;i < id.length;i++){
userids[i] = Integer.valueOf(id[i]).intValue();
}
//访问业务接口,删除数据
iuserService.delete(userids);
return list();
} catch (Exception e) {
e.printStackTrace();
return "error";
}
}


public String update() {
try {
//访问业务接口,修改数据
iuserService.update(this.getUser());
return list();
} catch (Exception e) {
e.printStackTrace();
return "error";
}
}

public String show(){
try {
user = iuserService.getbyId(userId);
//转发数据
return "show";
} catch (Exception e) {
e.printStackTrace();
return "error";
}
}

}


IDaoService

package com.demo.database.idao;


import java.util.List;


import com.demo.database.data.TDemoUser;


public interface IDaoService {


public List<? extends Object> list(String hql) throws Exception;

public void save(Object obj) throws Exception;

public void update(Object obj) throws Exception;

public void delete(int...ids) throws Exception;

public TDemoUser getbyId(Integer userId) throws Exception;

}

DaoServiceImpl

package com.demo.database.idao.impl;


import java.util.List;


import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.query.Query;


import com.demo.database.data.TDemoUser;
import com.demo.database.idao.IDaoService;


public class DaoServiceImpl implements IDaoService {


private SessionFactory sessionFactory; // 会话工厂


public SessionFactory getSessionFactory() {
return sessionFactory;
}


public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}


/**
* 打开并返回会话Session

* @return
*/
public Session getSession() {
return sessionFactory.openSession();
}


/**
* 查询
*/
@Override
public List<? extends Object> list(String hql) throws Exception {
// 获得Session对象
Session session = getSession();
// 获得查询数据的对象
Query query = session.createQuery(hql);
// 查询获得数据
List<Object> list = query.list();
// 关闭Session
session.close();
return list;
}


/**
* 添加
*/
@Override
public void save(Object obj) throws Exception {
Session session = getSession();
Transaction tx = session.beginTransaction();
session.save(obj);
tx.commit();
session.close();
}


/**
* 修改
*/
@Override
public void update(Object obj) throws Exception {
Session session = getSession();
Transaction tx = session.beginTransaction();
session.update(obj);
tx.commit();
session.close();
}


/**
* 批量删除
*/
@Override
public void delete(int...ids) throws Exception {
Session session = getSession();
Transaction tx = session.beginTransaction();
for (int id : ids) {
TDemoUser user = new TDemoUser();
user.setUserId(id);
session.delete(user);
}
tx.commit();
session.close();
}


@Override
public TDemoUser getbyId(Integer userId) throws Exception {
Session session = getSession();
return session.get(TDemoUser.class, userId);
}

}


IUserService

package com.demo.services;


import java.util.List;


import com.demo.database.data.TDemoUser;


/**
 * 用户管理的业务接口
 * @author Teacher
 * @createTime 2018年3月23日 下午5:01:07
 * @updateTime 2018年3月23日 下午5:01:07
 * @version 1.0.0
 */
public interface IUserService {


public List<TDemoUser> list() throws Exception;

public void add(TDemoUser user) throws Exception;

public void delete(int...ids) throws Exception;

public void update(TDemoUser user) throws Exception;

public TDemoUser getbyId(Integer userId) throws Exception;

}


IUserServiceImpl

package com.demo.services.impl;


import java.util.List;


import com.demo.database.data.TDemoUser;
import com.demo.database.idao.IDaoService;
import com.demo.services.IUserService;


/**
 * 用户管理业务具体实现类
 * @author Teacher
 * @createTime 2018年3月23日 下午5:03:44
 * @updateTime 2018年3月23日 下午5:03:44
 * @version 1.0.0
 */
public class IUserServiceImpl implements IUserService {


private IDaoService idaoService; //定义数据访问接口

public IDaoService getIdaoService() {
return idaoService;
}


public void setIdaoService(IDaoService idaoService) {
this.idaoService = idaoService;
}


@Override
public List<TDemoUser> list() throws Exception {
List<TDemoUser> list = (List<TDemoUser>) idaoService.list("from TDemoUser");
return list;
}


@Override
public void add(TDemoUser user) throws Exception {
idaoService.save(user);
}


@Override
public void update(TDemoUser user) throws Exception {
idaoService.update(user);
}


@Override
public void delete(int...ids) throws Exception {
idaoService.delete(ids);
}


@Override
public TDemoUser getbyId(Integer userId) throws Exception {
return this.idaoService.getbyId(userId);  
}

}


applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop  
        http://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">


<!-- 定义数据源Bean -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="com.mysql.jdbc.Driver"></property>
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/demo"></property>
<property name="user" value="root"></property>
<property name="password" value="123456"></property>
</bean>
<!-- 定义会话工厂Bean -->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<!-- 注入数据Bean -->
<property name="dataSource" ref="dataSource"></property>
<!-- Hibernate常用配置 -->
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
<!-- 映射文件位置 -->
<property name="mappingLocations">
<list>
<value>classpath:com/demo/database/xml/*.hbm.xml</value>
</list>
</property>
</bean>


<!-- 定义数据访问的公共Bean -->
<bean id="idaoService" class="com.demo.database.idao.impl.DaoServiceImpl">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>


<!-- 定义业务Bean -->
<bean id="iuserService" class="com.demo.services.impl.IUserServiceImpl">
<property name="idaoService" ref="idaoService"></property>
</bean>


<!-- 定义业务控制器Bean -->
<bean id="userAction" class="com.demo.actions.UserAction">
<property name="iuserService" ref="iuserService"></property>
</bean>

</beans>


struts.xml

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


<struts>


<package name="default" namespace="/" extends="struts-default">


<global-results>
<result name="error">/error.jsp</result>
</global-results>


<global-allowed-methods>regex:.*</global-allowed-methods>


<action name="simple" class="simpleAction">
<result>/index.jsp</result>
</action>


<action name="user*" class="userAction" method="{1}">
<result name="list">/userlist.jsp</result>
<result name="delete">/userlist.jsp</result>
<result name="show">/userview.jsp</result>
</action>

</package>


</struts>


web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
id="WebApp_ID" version="3.1">


<display-name>Archetype Created Web Application</display-name>
<context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext*.xml</param-value>
    </context-param>
    
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    
    <filter>
        <filter-name>struts2</filter-name>
        <filter-class>org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>struts2</filter-name>
        <url-pattern>*.action</url-pattern>
    </filter-mapping>
    <filter-mapping>
        <filter-name>struts2</filter-name>
        <url-pattern>*.jsp</url-pattern>
    </filter-mapping>


</web-app>


<ul>
       <li><a href="userlist.action">用户管理</a></li>

    </ul>


useradd.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<%
String base = request.getScheme() + "://" + request.getServerName() + ":" 
     + request.getServerPort() + request.getContextPath() + "/";
%>
<base href="<%=base%>">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
    <h2>添加用户信息</h2>
    <hr/>
    <form method="post" action="useradd.action">
        <p>用户名: <input type="text" name="user.userName" required autofocus></p>
        <p>密码: <input type="password" name="user.userPassword" required></p>
        <p>性别: <input type="radio" name="user.userGender" value="男" checked>男 
              <input type="radio" name="user.userGender" value="女">女
        </p>
        <p>出生年月: <input type="date" name="user.userBirthday" required></p>
        <p><input type="submit" value="确 定"> <input type="reset" value="重 置"></p>
    </form>
</body>

</html>


userlist

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" import="java.lang.*"%>
<%@ taglib uri="/struts-tags" prefix="s"%>
<!DOCTYPE html>
<html>
<head>
<%
String base = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
+ request.getContextPath() + "/";
%>
<base href="<%=base%>">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script src="js/jquery-1.7.1.min.js"></script>
<script>
function deleting() {
var userId = document.getElementsByName("ids");
var ids = new Array();
for (var i = 0; i < userId.length; i++) {
if (userId[i].checked){
ids.push(userId[i].value);
}
}
location.href="userdelete.action?ids="+ids;
}
</script>
</head>
<body>
<h2>用户信息列表</h2>
<form id="form1" name="form1" method="post" action="">
<table width="1000" cellpadding="5" cellspacing="0" border="1"
align="center">
<tr align="center">
<th></th>
<th>序号</th>
<th>编号</th>
<th>姓名</th>
<th>性别</th>
<th>出生年月</th>
<th>操作</th>
</tr>
<s:iterator var="user" value="#request.list" status="st">
<tr align="center">
<td><input type="checkbox"
value="<s:property value="#user.userId" />" name="ids"></td>
<td><s:property value="#st.count" /></td>
<td><s:property value="#user.userId" /></td>
<td><s:property value="#user.userName" /></td>
<td><s:property value="#user.userGender" /></td>
<td><s:date name="#user.userbirthday" format="yyyy年MM月dd日" /></td>
<td><a
href="usershow.action?userId=<s:property value="#user.userId" />">修
改</a></td>
</tr>
</s:iterator>
</table>
</form>
<p align="center">
<input type="button" value="添 加" οnclick="location.href='useradd.jsp'" />
<input type="button" value="删 除" οnclick="deleting()" />
</p>
</body>

</html>


userview

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<%
String base = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
+ request.getContextPath() + "/";
%>
<base href="<%=base%>">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<h2>添加用户信息</h2>
<hr />
<form method="post" action="userupdate.action">
<p>
用户名: <input type="text" name="user.userName" value="${user.userName }" required autofocus>
</p>
<p>
密码: <input type="password" name="user.userPassword" value="${user.userPassword }" required>
</p>
<p>
性别: <input type="text" name="user.userGender" value="${user.userGender }" >
</p>
<p>
出生年月: <input type="date" name="user.userBirthday" value="${user.userBirthday }" required>
</p>
<p>
<input type="submit" value="确 定"> <input type="reset"
value="重 置">
</p>
</form>
</body>

</html>


pom.xml

<dependencies>
<dependency>
<groupId>org.apache.struts</groupId>
<artifactId>struts2-core</artifactId>
<version>2.5.14</version>
</dependency>
<dependency>
<groupId>org.apache.struts</groupId>
<artifactId>struts2-convention-plugin</artifactId>
<version>2.5.14</version>
</dependency>
<dependency>
<groupId>org.apache.struts</groupId>
<artifactId>struts2-spring-plugin</artifactId>
<version>2.5.14</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>5.0.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>5.0.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>5.0.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.0.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>5.0.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.0.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>5.0.4.RELEASE</version>
</dependency>
<dependency>
<groupId>aopalliance</groupId>
<artifactId>aopalliance</artifactId>
<version>1.0</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.13</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>5.0.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-expression</artifactId>
<version>5.0.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.2.14.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-c3p0</artifactId>
<version>5.2.14.Final</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.46</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>5.0.4.RELEASE</version>
</dependency>

</dependencies>


<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.2</version>
<configuration>
<url>http://localhost:8080/manager/text</url>
<server>Tomcat8</server>
<username>admin</username>
<password>admin</password>
<!-- <path>/yiibaiWebApp</path> -->
</configuration>
</plugin>
</plugins>


package test;




import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;


public class test {


public static void main(String[] args) {


Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日  HH:mm:ss");
System.out.println(sdf.format(date));
}


public void read(String url,String dx){
try {
//创建文件字节输入流
FileInputStream fis=new FileInputStream(url);

String s = url.substring(url.lastIndexOf("/"));
File file=new File(dx);//判断复制到的目录是否存在
if(!file.exists()){
file.mkdirs();//创建目录
}

File file1 = new File(dx + File.separator + s); 
//字节输出流
OutputStream os = new FileOutputStream(file1);
BufferedOutputStream bos = new BufferedOutputStream(os);

byte[] bytes=new byte[1024];
int i=0;
//循环写入
while((i=fis.read(bytes))!=-1){
bos.write(bytes,0,i);
}
fis.close();
bos.close();
System.out.println("复制成功");
} catch (FileNotFoundException e) {

e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家小花儿/article/detail/185246
推荐阅读
相关标签
  

闽ICP备14008679号