引言
所用版本:jdk1.8 tomcat7.88
所用数据库:mysql
所用技术:maven-spring4.3.2-struts2-mybatis-ajax 基于注解版
//主要实现 两张表 增删改查 包含图片上传 ajax发送异步请求 主要对 select标签 有详细案例
本案例中用到的常用注解总结如下:
1.实体类上:
@Component此注解表示 创建简单对象 默认构建的简单对象名称(ID值)为类名首字母小写
2.service 实现类上:
加到类上
@Service 自动创建service实现类对象
@Transactional 进行事务控制 书写在类上表示本类中所有的方法都加事务( 增删改 默认)
加到方法上表示:方法上的事务覆盖类上的
@Transactional(propagation = Propagation.SUPPORTS,readOnly = true)
表示查询 时将事务级别设置为 readOnly = true 只读属性
(propagation = Propagation.SUPPORTS 外部没有事务不开启事务
作用:提高查询效率
3.action类上:
@Controller 作用 生成Action对象 默认为类名首字母小写
@Scope("prototype") 作用 控制对象创建的次数 表示多例 (struts2中表示多列)
4.@Autowired 表示自动注入 由spring框架提供 所创建的接口实现类对象 (取代get和set方法)
5.@Resource 表示自动注入 由java默认提供
1环境搭建 导入依赖 pom.xml文件
<name>SSMAnotation Maven Webapp</name>
<!-- FIXME change it to the project's website -->
<url>http://www.example.com</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<!-- 引入javaEE规范 -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>
<!-- 引入spring相关的jar -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.3.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.3.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>4.3.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>4.3.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>4.3.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>4.3.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>4.3.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>4.3.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-expression</artifactId>
<version>4.3.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>4.3.2.RELEASE</version>
</dependency>
<!-- 引入mybatis相关jar -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.2.8</version>
</dependency>
<!-- 引入mybatis 与 spring 整合jar -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.2</version>
</dependency>
<!-- 引入struts2 -->
<dependency>
<groupId>org.apache.struts</groupId>
<artifactId>struts2-core</artifactId>
<version>2.3.16</version>
</dependency>
<!-- 引入struts2 与spring的整合jar -->
<dependency>
<groupId>org.apache.struts</groupId>
<artifactId>struts2-spring-plugin</artifactId>
<version>2.3.16</version>
</dependency>
<!-- 引入mysql -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.38</version>
</dependency>
<!-- 引入dbcp -->
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.4</version>
</dependency>
<!-- 引入fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.47</version>
</dependency>
<!-- 引入log4j -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.15</version>
</dependency>
<!--引入jstl标签-->
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.2</version>
</dependency>
</dependencies>
<build>
<finalName>SSMAnotation</finalName>
<pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
<plugins>
<plugin>
<artifactId>maven-clean-plugin</artifactId>
<version>3.1.0</version>
</plugin>
<!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<version>3.0.2</version>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.1</version>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>3.2.2</version>
</plugin>
<plugin>
<artifactId>maven-install-plugin</artifactId>
<version>2.5.2</version>
</plugin>
<plugin>
<artifactId>maven-deploy-plugin</artifactId>
<version>2.8.2</version>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>
2.小配置文件 jdbc.properties
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/ems_spring1
name=root
password=root
3.spring 配置文件 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:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<!--开启注解扫描 告知Spring在哪一个包下使用了注解-->
<context:component-scan base-package="com.baizhi.*"></context:component-scan>
<!--读取小配置文件-->
<context:property-placeholder location="classpath:jdbc.properties"></context:property-placeholder>
<!--配置数据源-->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName">
<value>${driver}</value>
</property>
<property name="url">
<value>${url}</value>
</property>
<property name="username">
<value>${name}</value>
</property>
<property name="password">
<value>${password}</value>
</property>
</bean>
<!--创建SqlSessionFactory-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<!--起别名-->
<property name="typeAliasesPackage">
<value>com.baizhi.entity</value>
</property>
<!--Mapper文件注册-->
<property name="mapperLocations">
<list>
<value>classpath:com/baizhi/dao/*Mapper.xml</value>
</list>
</property>
</bean>
<!--创建DAO实现类对象-->
<bean id="scannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage">
<value>com.baizhi.dao</value>
</property>
</bean>
<!--激活@Transactional-->
<!--引入控制事务的相关代码-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!--激活-->
<tx:annotation-driven transaction-manager="transactionManager"></tx:annotation-driven>
4. web.xml
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<!--读取spring(applicationContext.xml)配置文件-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<!--配置Struts的核心过滤器-->
<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>
<!--配置Spring的监听工厂-->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
</web-app>
5.log4j.properties
log4j.rootLogger = ERROR,bb
log4j.appender.bb = org.apache.log4j.ConsoleAppender
log4j.appender.bb.layout = org.apache.log4j.PatternLayout
log4j.appender.bb.layout.conversionPattern = %d{yyyy-MM-dd} %t %c [%p] %m%n
log4j.logger.com.baizhi.dao = DEBUG
log4j.logger.com.baizhi.service = DEBUG
log4j.logger.org.springframework.jdbc = DEBUG
6 写实体 (建表省略)
//运用注解开发
//第一张表 部门表
package com.baizhi.entity;
import org.springframework.stereotype.Component;
import java.io.Serializable;
/**
* 部门表的实体类
* @Component此注解表示 创建简单对象 默认构建的简单对象名称(ID值)为类名首字母小写
* */
@Component
public class Department implements Serializable {
private Integer id;
//部门编号
private String identifier;
private String name;
//此处 get/set,有参无参,toString 省略
}
//第二种表 员工表
package com.baizhi.entity;
import org.springframework.stereotype.Component;
import java.io.Serializable;
/**
* 库表 emp 对应的实体类
* @Component此注解表示 创建简单对象 默认构建的简单对象名称(ID值)为类名首字母小写
* */
@Component
public class Emp implements Serializable {
private Integer id;
private String code;
private String name;
private double salary;
private Integer age;
//关系属性 部门id
private Integer department_id;
//封装部门对象 做表连接查询结果展示
private Department department;
//此处 get/set,有参无参,toString 省略
}
7写Dao接口
7.1 部门表 对应接口
package com.baizhi.dao;
import com.baizhi.entity.Department;
import java.util.List;
public interface DepartmentDao {
//插入一条数据
public void saveDepartment(Department department);
//展示所有部门信息
public List<Department> selectDepartmentAll();
//根据id查询一个对象
public Department selectByIdDepartment(Department department);
//根据id修改一条数据
public void uadataByIdDepartment(Department department);
}
7.2员工表 对应接口
package com.baizhi.dao;
import com.baizhi.entity.Emp;
import org.apache.ibatis.annotations.Param;
import java.util.List;
public interface EmpDao {
//根据部门id展示所有员工信息
public List<Emp> selectEmpAll(@Param ("department_id") Integer department_id,@Param ("did") Integer did);
//插入一条数据
public void savaEmp(Emp emp);
//根据id删除一条员工信息
public void deleteByIdEmp(Emp emp);
//根据 id查询一条员工信息
public Emp selectByIdEmp(Emp emp);
//根据id修改一条员工信息
public void updateByIdEmp(Emp emp);
}
8 写 Mapper.xml (实现Dao接口)
8.1 部门表 接口 对应的实现
文件名为:DepartmentDaoMapper.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.baizhi.dao.DepartmentDao">
<!-- 插入一条数据-->
<insert id="saveDepartment" parameterType="Department">
insert into department (identifier,name) values(#{identifier},#{name})
</insert>
<!--展示所有信息-->
<select id="selectDepartmentAll" resultType="Department">
select * from department
</select>
<!--根据id查询一个对象-->
<select id="selectByIdDepartment" resultType="Department">
select * from department where id = #{id}
</select>
<!--根据id修改一条数据-->
<update id="uadataByIdDepartment" parameterType="Department">
update department set identifier =#{identifier},name=#{name} where id = #{id}
</update>
</mapper>
8.2 员工表 接口 对应的实现
文件名为:EmpDaoMapper.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.baizhi.dao.EmpDao">
<!-- 插入一条数据-->
<insert id="savaEmp" parameterType="Emp">
insert into emp (code,name,salary,age,department_id)
values(#{code},#{name},#{salary},#{age},#{department_id})
</insert>
<resultMap id="map" type="Emp">
<id property="id" column="eid"></id>
<result property="code" column="code"></result>
<result property="name" column="name"></result>
<result property="salary" column="salary"></result>
<result property="age" column="age"></result>
<result property="department_id" column="department_id"></result>
<!--对 属性 是 对象 类型 的处理-->
<association property="department" javaType="Department">
<id property="id" column="did"></id>
<result property="identifier" column="identifier"></result>
<result property="name" column="dname"></result>
</association>
</resultMap>
<!--根据部门id展示所有信息-->
<select id="selectEmpAll" resultMap="map">
select * from
(select
e.id eid,e.code,e.name,e.salary,e.age,e.department_id,
d.name dname,d.id did,d.identifier
from emp e inner join department d on e.department_id = d.id) em
<where>
<if test=" department_id!=0">
em.department_id=#{department_id}
</if>
<if test="did!=0">
and em.did=#{did}
</if>
</where>
</select>
<!--根据id查询一个对象-->
<select id="selectByIdEmp" resultMap="map">
select
e.id eid,e.code,e.name,e.salary,e.age,e.department_id,
d.name dname,d.id did,d.identifier
from emp e inner join department d on e.department_id = d.id
where e.id=#{id}
</select>
<!--根据id修改一条数据-->
<update id="updateByIdEmp" parameterType="Emp">
update emp
<set>
<if test="code != null">
code=#{code},
</if>
<if test="name!=null">
name=#{name},
</if>
<if test="age!=null">
age=#{age},
</if>
<if test="department_id!=null">
department_id=#{department_id}
</if>
</set>
where id=#{id}
</update>
<!--根据id删除一条数据-->
<delete id="deleteByIdEmp" parameterType="Emp">
delete from emp where id=#{id}
</delete>
</mapper>
9.写 Service接口
9.1部门表对应的service接口
package com.baizhi.service;
import com.baizhi.entity.Department;
import java.util.List;
public interface DepartmentService {
//插入一条数据
public void motifysaveDepartment(Department department);
//展示所有部门信息
public List<Department> selectDepartmentAll();
//根据id查询一个对象
public Department selectByIdDepartment(Department department);
//根据id修改一条数据
public void motifyuadataByIdDepartment(Department department);
}
9.2员工表对应的service接口
package com.baizhi.service;
import com.baizhi.entity.Emp;
import java.util.List;
public interface EmpService {
//根据部门id展示所有员工信息
public List<Emp> selectEmpAll(Integer department_id,Integer did);
//添加员工
public void motifySavaEmp(Emp emp);
//根据id删除一条员工
public void motifyDeleteByIdEmp(Emp emp);
//根据 id查询一条员工信息
public Emp selectByIdEmp(Emp emp);
//根据id修改一条员工信息
public void motifyUpdateByIdEmp(Emp emp);
}
10.写serviceImpl接口的实现类
10.1部门表service接口对应实现类
package com.baizhi.service;
import com.baizhi.dao.EmpDao;
import com.baizhi.entity.Emp;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
/**
* @Service 自动创建service实现类对象
* @Transactional 进行事务控制 书写在类上表示本类中所有的方法都加事务(增删改默认)
* */
@Service
@Transactional
public class EmpServiceImpl implements EmpService {
@Autowired
private EmpDao empDao;
//根据部门id展示所有员工信息
@Override
@Transactional(propagation = Propagation.SUPPORTS,readOnly = true)
public List<Emp> selectEmpAll(Integer department_id,Integer did) {
List<Emp> emps = empDao.selectEmpAll (department_id,did);
return emps;
}
//插入一条数据
@Override
public void motifySavaEmp(Emp emp) {
empDao.savaEmp (emp);
}
//根据id删除一条员工信息
@Override
public void motifyDeleteByIdEmp(Emp emp) {
empDao.deleteByIdEmp (emp);
}
//根据 id 查询一条员工 信息
@Override
@Transactional(propagation = Propagation.SUPPORTS,readOnly = true)
public Emp selectByIdEmp(Emp emp) {
return empDao.selectByIdEmp (emp);
}
//根据id修改一条员工信息
@Override
public void motifyUpdateByIdEmp(Emp emp) {
empDao.updateByIdEmp (emp);
}
}
10.2 部门表service接口对应实现类
package com.baizhi.service;
import com.baizhi.dao.DepartmentDao;
import com.baizhi.entity.Department;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
/**
* @Service 自动创建service实现类对象
* @Transactional 进行事务控制 书写在类上表示本类中所有的方法都加事务(增删改默认)
* */
@Service
@Transactional
public class DepartmentServiceImpl implements DepartmentService {
//调用dao 创建dao接口类对象 利用spring 内置的注解 自动注入
@Autowired
private DepartmentDao departmentDao;
// @Transactional 给原始方法添加对应的事务 需要在spring 配置文件中激活该事务
//插入一条数据
@Override
public void motifysaveDepartment(Department department) {
departmentDao.saveDepartment (department);
}
//展示所有
/**
* @Transactional(propagation = Propagation.SUPPORTS,readOnly = true)
* 表示查询 时将事务级别设置为 readOnly = true 只读属性
* (propagation = Propagation.SUPPORTS 外部没有事务不开启事务
* 提高查询效率
* */
@Override
@Transactional(propagation = Propagation.SUPPORTS,readOnly = true)
public List<Department> selectDepartmentAll() {
List<Department> departments = departmentDao.selectDepartmentAll ();
return departments;
}
//根据id查询
@Override
@Transactional(propagation = Propagation.SUPPORTS,readOnly = true)
public Department selectByIdDepartment(Department department) {
Department department1 = departmentDao.selectByIdDepartment (department);
return department1;
}
//根据id修改
@Override
public void motifyuadataByIdDepartment(Department department) {
departmentDao.uadataByIdDepartment (department);
}
}
11.写action
9.1 部门表对应的action
package com.baizhi.action;
import com.baizhi.entity.Department;
import com.baizhi.service.DepartmentService;
import com.opensymphony.xwork2.ActionSupport;
import org.apache.struts2.ServletActionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
/**
* @Controller 作用 生成Action对象
* @Scope("prototype") 作用 控制对象创建的次数 此处表示多例
* */
@Controller
@Scope("prototype")
public class DepartmentAction extends ActionSupport {
//调用service层方法 利用自动注入
@Autowired
private DepartmentService departmentService;
//成员变量接收参数
private Department department;
public Department getDepartment() {
return department;
}
public void setDepartment(Department department) {
this.department = department;
}
//插入一条数据
public String addDepartmentAction(){
departmentService.motifysaveDepartment (department);
return "addDepartmentActionOK";
}
//展示所有部门信息
public String showAllDepartment(){
List<Department> departments = departmentService.selectDepartmentAll ();
//利用工具类获取request作用域存储数据 用于展示
HttpServletRequest request = ServletActionContext.getRequest ();
request.setAttribute ("departments",departments);
return "showAllDepartmentOK";
}
//根据id查询 回显
public String showOneDepartment(){
Department dep = departmentService.selectByIdDepartment (department);
//利用工具类获取request作用域存储数据 用于展示
HttpServletRequest request = ServletActionContext.getRequest ();
request.setAttribute ("department",dep);
return "showOneDepartmentOK";
}
//根据id修改
public String updateDepartment(){
departmentService.motifyuadataByIdDepartment (department);
return "updateDepartmentOK";
}
}
9.1员工表对应的action
package com.baizhi.action;
import com.alibaba.fastjson.JSON;
import com.baizhi.entity.Department;
import com.baizhi.entity.Emp;
import com.baizhi.service.DepartmentService;
import com.baizhi.service.EmpService;
import com.opensymphony.xwork2.ActionSupport;
import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
/**
* @Controller 作用 生成Action对象
* @Scope("prototype") 作用 控制对象创建的次数 此处表示多例
* */
@Controller
@Scope("prototype")
public class EmpAction extends ActionSupport {
//调用 员工service 自动注入
@Autowired
private EmpService empService;
//调用 部门service 自动注入
@Autowired
private DepartmentService departmentService;
//接收前台传过来的参数
private Emp emp;
private Department department;
public Emp getEmp() {
return emp;
}
public void setEmp(Emp emp) {
this.emp = emp;
}
public Department getDepartment() {
return department;
}
public void setDepartment(Department department) {
this.department = department;
}
//根据部门id展示所有员工信息
public String showAllEmp() {
//获取作用域传值
HttpServletRequest request = ServletActionContext.getRequest ();
//用户添加时所选的部门id
//System.out.println ("===="+emp);
//System.out.println ("++++"+department);
if (emp!=null||department!=null) {
if (emp!=null){
List<Emp> emps = empService.selectEmpAll (emp.getDepartment_id (), 0);
request.setAttribute ("emps", emps);
}else if (department!=null){
List<Emp> emps = empService.selectEmpAll (0, department.getId ());
request.setAttribute ("emps", emps);
}
}
return "showAllEmpOK";
}
//根据id删除一条员工信息
public String deteleByIdEmpAction(){
Integer department_id = emp.getDepartment_id ();
//获取作用域传值
empService.motifyDeleteByIdEmp (emp);
return "deteleByIdEmpActionOK";
}
//ajax 异步请求 查询所有的部门信息
public String showAllDapartmentName1(){
//获取作用域传值
HttpServletRequest request = ServletActionContext.getRequest ();
HttpServletResponse response = ServletActionContext.getResponse ();
List<Department> departments = departmentService.selectDepartmentAll ();
//将list集合转换为json
String jsonString = JSON.toJSONString (departments);
//设置响应编码格式
response.setCharacterEncoding ("UTF-8");
//获得响应流 将结果用流打回页面
try {
PrintWriter out = response.getWriter ();
out.println (jsonString);
} catch (IOException e) {
e.printStackTrace ();
}
return null;
}
//添加员工 包含上传头像
//处理上传头像
//定义成员变量接收参数
private File upload;
//动态获取文件名
private String uploadFileName;
public File getUpload() {
return upload;
}
public void setUpload(File upload) {
this.upload = upload;
}
public String getUploadFileName() {
return uploadFileName;
}
public void setUploadFileName(String uploadFileName) {
this.uploadFileName = uploadFileName;
}
//添加员工 包含上传头像
public String addEmpAction(){
//处理上传的图片
String realPath = ServletActionContext.getServletContext ().getRealPath ("/uplodeImg/" + "/" + uploadFileName);
System.out.println("相对路径="+realPath);
try {
FileUtils.copyFile (upload,new File (realPath));
} catch (IOException e) {
e.printStackTrace ();
}
emp.setCode (uploadFileName);
empService.motifySavaEmp (emp);
return "addEmpActionOK";
}
//为修改 做铺垫 回显
public String showOneEmp(){
Emp emp = empService.selectByIdEmp (this.emp);
//获取作用域存值
HttpServletRequest request = ServletActionContext.getRequest ();
request.setAttribute ("emp",emp);
return "showOneEmpOK";
}
//根据 id修改
public String updateOneEmp(){
if (uploadFileName!=null) {
//处理上传的图片
String realPath = ServletActionContext.getServletContext ().getRealPath ("/uplodeImg/" + "/" + uploadFileName);
System.out.println ("根据 id修改 0000相对路径=" + realPath);
try {
FileUtils.copyFile (upload, new File (realPath));
} catch (IOException e) {
e.printStackTrace ();
}
Integer id = department.getId ();
emp.setDepartment_id (id);
emp.setCode (uploadFileName);
}
System.out.println ("转入的参数="+emp);
empService.motifyUpdateByIdEmp (emp);
return "updateOneEmpOK";
}
}
12. struts2.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
"http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
<!--对部门表进行处理-->
<package name="department" extends="struts-default" namespace="/department">
<!--展示所有部门信息-->
<action name="showAllDepartment" class="departmentAction" method="showAllDepartment">
<result name="showAllDepartmentOK">/Jsp/departments.jsp</result>
</action>
<!--插入一条信息-->
<action name="addDepartmentAction" class="departmentAction" method="addDepartmentAction" >
<result name="addDepartmentActionOK" type="redirect">showAllDepartment</result>
</action>
<!--回显-->
<action name="showOneDepartment" class="departmentAction" method="showOneDepartment">
<result name="showOneDepartmentOK">/Jsp/updateDepartment.jsp</result>
</action>
<!--更新 修改-->
<action name="updateDepartment" class="departmentAction" method="updateDepartment">
<result name="updateDepartmentOK" type="redirect">showAllDepartment</result>
</action>
</package>
<!--对员工表处理-->
<package name="emp" extends="struts-default" namespace="/emp">
<!--展示所有员工信息-->
<action name="showAllEmp" class="empAction" method="showAllEmp">
<result name="showAllEmpOK">/Jsp/emplist.jsp</result>
</action>
<!--根据id删除-->
<action name="deteleByIdEmpAction" class="empAction" method="deteleByIdEmpAction">
<result name="deteleByIdEmpActionOK" type="chain">showAllEmp</result>
</action>
<!--展示所有部门信息-->
<action name="showAllDapartmentName1" class="empAction" method="showAllDapartmentName1">
</action>
<!--添加一条员工信息-->
<action name="addEmpAction" class="empAction" method="addEmpAction">
<!--挎包调转 展示所有部门-->
<result name="addEmpActionOK" type="redirectAction">
<param name="namespace">/department</param>
<param name="actionName">showAllDepartment</param>
</result>
</action>
<!--回显 为修改做铺垫-->
<action name="showOneEmp" class="empAction" method="showOneEmp">
<result name="showOneEmpOK" >/Jsp/updateEmp.jsp</result>
</action>
<!--修改-->
<action name="updateOneEmp" class="empAction" method="updateOneEmp">
<result name="updateOneEmpOK" type="chain">showAllEmp</result>
</action>
</package>
</struts>
13.页面处理
1 添加员工 对文件上传处理
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>n
<html >
<html >
<head>
<title>add Emp</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" type="text/css"
href="../css/style.css" />
<!--引入juery插件-->
<script type="application/javascript" src="${pageContext.request.contextPath}/js/jquery-1.8.3.js"></script>
<script type="text/javascript">
$(function(){
//ajax发送异步请求
$.ajax({
url:"${pageContext.request.contextPath}/emp/showAllDapartmentName1",
type:"post",
dataType:"json",
success:function (dapartments) {
for(var i=0;i<dapartments.length;i++){
//创建option标签 将遍历的值放到option标签中
var option = $("<option value="+dapartments [i].id+">"+dapartments [i].name+"</option>");
//获取select标签 将 option 标签放到 select标签中
$("#sel").append(option);
}
}
});
});
</script>
</head>
<body>
<div id="wrap">
<div id="top_content">
<div id="header">
<div id="rightheader">
<p>
2009/11/20
<br />
</p>
</div>
<div id="topheader">
<h1 id="title">
<a href="#">Main</a>
</h1>
</div>
<div id="navigation">
</div>
</div>
<div id="content">
<p id="whereami">
</p>
<h1>
add Emp info:
</h1>
<form action="${pageContext.request.contextPath}/emp/addEmpAction" enctype="multipart/form-data" method="post">
<table cellpadding="0" cellspacing="0" border="0"
class="form_table">
<tr>
<td valign="middle" align="right">
头像:
</td>
<td valign="middle" align="left">
<input type="file" name="upload" />
</td>
</tr>
<tr>
<td valign="middle" align="right">
姓名:
</td>
<td valign="middle" align="left">
<input type="text" class="inputgri" name="emp.name" />
</td>
</tr>
<tr>
<td valign="middle" align="right">
工资:
</td>
<td valign="middle" align="left">
<input type="text" class="inputgri" name="emp.salary" />
</td>
</tr>
<tr>
<td valign="middle" align="right">
年龄:
</td>
<td valign="middle" align="left">
<input type="text" class="inputgri" name="emp.age" />
</td>
</tr>
<tr>
<td valign="middle" align="right">
部门:
</td>
<td valign="middle" align="left">
<!--此处用ajax异步请求 展示所有部门的名称-->
<select id="sel" name="emp.department_id">
</select>
</td>
</tr>
</table>
<p>
<input type="submit" class="button" value="提交" />
</p>
</form>
</div>
</div>
<div id="footer">
<div id="footer_bg">
ABC@126.com
</div>
</div>
</div>
</body>
</html>
2修改员工信息 包含上传头像
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
<html>
<head>
<title>update Emp</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" type="text/css"
href="../css/style.css" />
<!--引入jquery框架-->
<script type="application/javascript" src="${pageContext.request.contextPath}/js/jquery-1.8.3.js"></script>
<script type="text/javascript">
$(function(){
//ajax发送异步请求
$.ajax({
url:"${pageContext.request.contextPath}/emp/showAllDapartmentName1",
type:"post",
dataType:"json",
success:function (dapartments) {
//获取回显的 部门 id
var optValue = $("#opt").val()
for(var i=0;i<dapartments.length;i++) {
//去重 遍历时不在展示 已回显的部门信息
if (optValue != dapartments [i].id) {
//创建option标签 将遍历的值放到option标签中
var option = $("<option value=" + dapartments [i].id + ">" + dapartments [i].name + "</option>");
$("#sel").append(option);
}
}
}
});
});
</script>
</head>
<body>
<div id="wrap">
<div id="top_content">
<div id="header">
<div id="rightheader">
<p>
2009/11/20
<br />
</p>
</div>
<div id="topheader">
<h1 id="title">
<a href="#">Main</a>
</h1>
</div>
<div id="navigation">
</div>
</div>
<div id="content">
<p id="whereami">
</p>
<h1>
update Emp info:
</h1>
<form action="${pageContext.request.contextPath}/emp/updateOneEmp" enctype="multipart/form-data" method="post">
<table cellpadding="0" cellspacing="0" border="0"
class="form_table">
<tr>
<td valign="middle" align="right">
id:
</td>
<td valign="middle" align="left">
<input type="hidden" class="inputgri" name="emp.id" value="${emp.id}"/>
</td>
</tr>
<tr>
<td valign="middle" align="right">
头像:
</td>
<td valign="middle" align="left">
<img width="40px" height="40px" src="${pageContext.request.contextPath}/uplodeImg/${emp.code}" />
<input type="file" name="upload" />
</td>
</tr>
<tr>
<td valign="middle" align="right">
用户名:
</td>
<td valign="middle" align="left">
<input type="text" class="inputgri" name="emp.name" value="${emp.name}"/>
</td>
</tr>
<tr>
<td valign="middle" align="right">
工资:
</td>
<td valign="middle" align="left">
<input type="text" class="inputgri" name="emp.salary" value="${emp.salary}"/>
</td>
</tr>
<tr>
<td valign="middle" align="right">
年龄:
</td>
<td valign="middle" align="left">
<input type="text" class="inputgri" name="emp.age" value="${emp.age}"/>
</td>
</tr>
<tr>
<td valign="middle" align="right">
部门:
</td>
<td valign="middle" align="left">
<!--第一次回显 第二次是ajax查询到所有的部门进行遍历展示 最后进行比较去重-->
<select id="sel" name="emp.department_id">
<option id="opt" value="${emp.department_id}" selected="selected" >${requestScope.emp.department.name}</option>
</select>
</td>
</tr>
</table>
<p>
<input type="submit" class="button" value="修改" />
</p>
</form>
</div>
</div>
<div id="footer">
<div id="footer_bg">
ABC@126.com
</div>
</div>
</div>
</body>
</html>
总结
基于maven 连接 mysql数据 用 spring-struts2-mybatis 环境搭建, 集成开发 案例 。 运用注解开发无需在applicationContext.xml中配置 service和action ,直接采用自动注入。