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" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd "> <bean id="config" class="org.springframework.beans.factory.config.PreferencesPlaceholderConfigurer"> <property name="locations" value="classpath*:*.properties"/> bean> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"> <property name="driverClassName" value="${driver}">property> <property name="url" value="${url}">property> <property name="username" value="${username}">property> <property name="password" value="${password}">property> <property name="initialSize" value="${initialSize}">property> <property name="maxActive" value="${maxActive}">property> <property name="maxIdle" value="${maxIdle}">property> <property name="minIdle" value="${minIdle}">property> bean> <bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean"> <property name="dataSource" ref="dataSource">property> <property name="mappingLocations" value="classpath:k/bean/*.hbm.xml">property> <property name="configLocation" value="classpath:hibernate.cfg.xml">property> bean> <bean id="txManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory"/> bean> <context:annotation-config/> <bean name="/login" class="k.action.LoginAction" scope="prototype"/> <bean name="/employee" class="k.action.EmployeeAction" scope="prototype"/> <bean name="testService" class="k.service.TestService"/> <bean name="employeeService" class="k.service.impl.EmployeeServiceImpl"/> <bean name="departmentService" class="k.service.impl.DepartmentServiceImpl"/> beans>
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="employeeForm" type="k.form.EmployeeForm"> <form-property name="id" type="java.lang.Integer">form-property> <form-property name="name" type="java.lang.String">form-property> <form-property name="password" type="java.lang.String">form-property> form-bean> form-beans> <global-forwards> <forward name="ok" path="/WEB-INF/jsp/ok.jsp">forward> <forward name="err" path="/WEB-INF/jsp/err.jsp">forward> global-forwards> <action-mappings> <action name="employeeForm" path="/login" parameter="action" type="k.action.LoginAction" scope="request" attribute="employeeForm" input="index.jsp" validate="false"> <forward name="main" path="/WEB-INF/jsp/main.jsp">forward> <forward name="loginJsp" path="/WEB-INF/jsp/login.jsp">forward> action> <action name="employeeForm" path="/employee" parameter="action" type="k.action.EmployeeAction" scope="request" attribute="employeeForm" input="index.jsp" validate="false"> <forward name="addEmployeeUI" path="/WEB-INF/jsp/addEmployeeUI.jsp">forward> <forward name="loginJsp" path="/WEB-INF/jsp/login.jsp">forward> action> action-mappings> <controller> <set-property property="processorClass" value="org.springframework.web.struts.DelegatingRequestProcessor">set-property> controller> struts-config>
hibernate.cfg.xml
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="hibernate.dialect">org.hibernate.dialect.MySQL5Dialectproperty> <property name="hibernate.hbm2ddl.auto">updateproperty> <property name="hibernate.show_sql">trueproperty> <property name="hibernate.format_sql">trueproperty> <property name="cache.use_second_level_cache">trueproperty> <property name="ache.provider_class">org.hibernate.cache.internal.DefaultCacheKeysFactoryproperty> <property name="generate_statistics">trueproperty> session-factory> hibernate-configuration>
web.xml
xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1"> <context-param> <param-name>contextConfigLocationparam-name> <param-value>classpath:applicationContext.xmlparam-value> context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class> <listener-class>k.listener.StartSystemListenerlistener-class> listener> <servlet> <servlet-name>actionservlet-name> <servlet-class>org.apache.struts.action.ActionServletservlet-class> <init-param> <param-name>configparam-name> <param-value>/WEB-INF/struts-config.xmlparam-value> init-param> <load-on-startup>2load-on-startup> servlet> <servlet-mapping> <servlet-name>actionservlet-name> <url-pattern>*.dourl-pattern> servlet-mapping> <filter> <filter-name>springUtf8Encodingfilter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class> <init-param> <param-name>encodingparam-name> <param-value>UTF-8param-value> init-param> <init-param> <param-name>forceEncodingparam-name> <param-value>trueparam-value> init-param> filter> <filter-mapping> <filter-name>springUtf8Encodingfilter-name> <url-pattern>/*url-pattern> filter-mapping> <filter> <filter-name>OpenSessionInViewFilterfilter-name> <filter-class>org.springframework.orm.hibernate5.support.OpenSessionInViewFilterfilter-class> filter> <filter-mapping> <filter-name>OpenSessionInViewFilterfilter-name> <url-pattern>/*url-pattern> filter-mapping> <context-param> <param-name>log4jConfigLocationparam-name> <param-value>classpath:log4j.propertiesparam-value> context-param> <context-param> <param-name>log4jRefreshIntervalparam-name> <param-value>60000param-value> context-param> <listener> <listener-class> org.springframework.web.util.Log4jConfigListener listener-class> listener> web-app>
db.properties
driver=com.mysql.jdbc.Driver url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8 username=root password=xxxx initialSize=20 maxActive=500 maxIdle=2 minIdle=1
log4j.properties
log4j.rootLogger=ERROR, console
log4j.appender.console=org.apache.log4j.ConsoleAppender
log4j.appender.console.layout=org.apache.log4j.PatternLayout
log4j.appender.console.layout.conversionPattern=%5p [%t] (%F:%L) - %m%n
EmployeeAction
package k.action; import k.domain.Department; import k.domain.Employee; import k.form.EmployeeForm; import k.service.DepartmentService; import k.service.EmployeeService; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.apache.struts.actions.DispatchAction; import org.springframework.web.context.WebApplicationContext; import org.springframework.web.context.support.WebApplicationContextUtils; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.Date; public class EmployeeAction extends DispatchAction { @Resource private EmployeeService employeeService; @Resource private DepartmentService departmentService; public ActionForward addEmployeeUI(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { return mapping.findForward("addEmployeeUI"); } public ActionForward addEmployee(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { EmployeeForm employeeForm = (EmployeeForm) form; Employee employee = new Employee(); employee.setName(employeeForm.getName()); employee.setEmail(employeeForm.getEmail()); employee.setSalary(employeeForm.getSalary()); employee.setPassword(employeeForm.getPassword()); employee.setGrade(employeeForm.getGrade()); employee.setHireDate(new Date()); Department department = departmentService.getDepartmentbyEmployee(Integer.parseInt(employeeForm.getDepartment_id())); employee.setDepartment(department); try { employeeService.addEmployee(employee); } catch (Exception e) { e.printStackTrace(); return mapping.findForward("err"); } return mapping.findForward("ok"); } }
LoginAction
package k.action; import k.domain.Employee; import k.form.EmployeeForm; import k.service.EmployeeService; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.apache.struts.actions.DispatchAction; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class LoginAction extends DispatchAction { @Resource private EmployeeService employeeService; public ActionForward login(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { return mapping.findForward("loginJsp"); } public ActionForward doLogin(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { EmployeeForm employeeOld = (EmployeeForm) form; Employee employee = new Employee(Integer.parseInt(employeeOld.getId()), employeeOld.getPassword()); employee = employeeService.checkEmployee(employee); if (employee != null) { request.getSession().setAttribute("employee", employee); return mapping.findForward("main"); } return mapping.findForward("err"); } public ActionForward loginOut(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { return super.execute(mapping, form, request, response); } }
Department.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="k.domain.Department" table="t_department"> <id name="id" column="id" type="java.lang.Integer"> <generator class="native">generator> id> <property name="name" column="name" type="java.lang.String" length="64">property> <set name="employees" inverse="true" cascade="save-update,delete"> <key column="department_id">key> <one-to-many class="k.domain.Employee">one-to-many> set> class> hibernate-mapping>
Employee.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="k.domain.Employee" table="t_employee"> <id name="id" column="id" type="java.lang.Integer"> <generator class="native">generator> id> <property name="name" column="name" type="java.lang.String" length="64">property> <property name="email" column="email" type="java.lang.String" length="64">property> <property name="hireDate" column="hireDate" type="java.util.Date">property> <property name="salary" column="salary" type="java.lang.Float">property> <property name="password" column="password" type="java.lang.String" length="64">property> <property name="grade" column="grade" type="java.lang.Integer" length="3">property> <many-to-one name="department" class="k.domain.Department" column="department_id">many-to-one> class> hibernate-mapping>
Department
package k.domain; import java.util.Set; public class Department { private Integer id; private String name; private Setemployees; public Department() { } public Department(String name) { this.name = name; } 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 Set getEmployees() { return employees; } public void setEmployees(Set employees) { this.employees = employees; } }
Employee
package k.domain; import java.util.Date; public class Employee { private Integer id; private String name; private String email; private Date hireDate; private Float salary; private String password; private Integer grade; private Department department; private String department_id; public Employee(Integer id, String name) { this.id = id; this.name = name; } public Employee() { } public Employee(String name, String password, String email, Date hireDate, Float salary, Integer grade) { this.name = name; this.email = email; this.hireDate = hireDate; this.salary = salary; this.password = password; this.grade = grade; } public String getDepartment_id() { return department_id; } public void setDepartment_id(String department_id) { this.department_id = department_id; } 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 getEmail() { return email; } public void setEmail(String email) { this.email = email; } public Date getHireDate() { return hireDate; } public void setHireDate(Date hireDate) { this.hireDate = hireDate; } public Float getSalary() { return salary; } public void setSalary(Float salary) { this.salary = salary; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public Integer getGrade() { return grade; } public void setGrade(Integer grade) { this.grade = grade; } public Department getDepartment() { return department; } public void setDepartment(Department department) { this.department = department; } }
EmployeeForm
package k.form; import org.apache.struts.action.ActionForm; import java.util.Date; public class EmployeeForm extends ActionForm { private String id; private String name; private String email; private Date hireDate; private Float salary; private String password; private Integer grade; private String department_id; public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public Date getHireDate() { return hireDate; } public void setHireDate(Date hireDate) { this.hireDate = hireDate; } public Float getSalary() { return salary; } public void setSalary(Float salary) { this.salary = salary; } public Integer getGrade() { return grade; } public void setGrade(Integer grade) { this.grade = grade; } public String getDepartment_id() { return department_id; } public void setDepartment_id(String department_id) { this.department_id = department_id; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
EncodingFilter
package k.listener; import javax.servlet.*; import javax.servlet.http.HttpServlet; import java.io.IOException; public class EncodingFilter extends HttpServlet implements Filter { @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { servletRequest.setCharacterEncoding("utf-8"); servletResponse.setCharacterEncoding("utf-8"); // System.out.println("========== set utf-8 ok =========="); filterChain.doFilter(servletRequest, servletResponse); } @Override public void init(FilterConfig filterConfig) throws ServletException { } }
StartSystemListener
package k.listener; import k.util.WebHelper; import javax.servlet.ServletContext; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; public class StartSystemListener implements ServletContextListener { @Override public void contextInitialized(ServletContextEvent sce) { //1.将项目上下文路径(request.getContextPath())放置到application域中. ServletContext application = sce.getServletContext(); String app_path = application.getContextPath(); application.setAttribute("APP_PATH", app_path); System.out.println("========== APP_PATH = " + app_path); WebHelper.setApp_Path(app_path); } @Override public void contextDestroyed(ServletContextEvent sce) { } }
DepartmentServiceImpl
package k.service.impl; import k.domain.Department; import k.domain.Employee; import k.service.DepartmentService; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.springframework.transaction.annotation.Transactional; import javax.annotation.Resource; import java.io.Serializable; @Transactional public class DepartmentServiceImpl implements DepartmentService { @Resource private SessionFactory sessionFactory; @Override public void addDepartment(Department department) { Session session = sessionFactory.openSession(); // Transaction transaction = session.beginTransaction(); Serializable res = session.save(department); // transaction.commit(); } @Override public Department getDepartmentbyEmployee(Serializable id) { Session session = sessionFactory.openSession(); Department department = session.get(Department.class, id); return department; } }
EmployeeServiceImpl
package k.service.impl; import k.domain.Department; import k.domain.Employee; import k.service.EmployeeService; import org.hibernate.*; import org.springframework.transaction.annotation.Transactional; import javax.annotation.Resource; import java.io.Serializable; import java.util.List; @Transactional public class EmployeeServiceImpl implements EmployeeService { @Resource private SessionFactory sessionFactory; @Override public int addEmployee(Employee e) { Session session = sessionFactory.openSession(); Transaction transaction = session.beginTransaction(); Serializable res = session.save(e); transaction.commit(); return (Integer) res; } @Override public ListgetList() { return null; } @Override public int updateEmployee() { return 0; } @Override public int delEmployee(Serializable id) { return 0; } @Override public Employee checkEmployee(Employee e) { Session session = sessionFactory.openSession(); Query sqlQuery = session.createQuery("from k.domain.Employee c where c.id=? "); // SQLQuery sqlQuery = session.createSQLQuery("select * from t_employee where id=?"); sqlQuery.setParameter(0, e.getId()); // Hibernate.initialize(Department.class); //显示初始化懒加载 List list = sqlQuery.list(); if (list.size() == 1) { // Department department = list.get(0).getDepartment(); // String s1 = department.getId() + "===3" + department.getName(); // System.out.println(department.getId() + "===3" + department.getName()); return list.get(0); } return null; } }
DepartmentService
package k.service; import k.domain.Department; import java.io.Serializable; public interface DepartmentService { void addDepartment(Department department); Department getDepartmentbyEmployee(Serializable id); }
EmployeeService
package k.service; import k.domain.Employee; import java.io.Serializable; import java.util.List; public interface EmployeeService { int addEmployee(Employee e); ListgetList(); int updateEmployee(); int delEmployee(Serializable id); Employee checkEmployee(Employee e); }
WebHelper
package k.util; import java.util.UUID; public class WebHelper { public static String getApp_Path() { return APP_PATH; } public static void setApp_Path(String appPath) { APP_PATH = appPath; } private static String APP_PATH = ""; public static String getNewFileName(String fileName) { int beginIndex = fileName.lastIndexOf("."); return UUID.randomUUID().toString() + fileName.substring(beginIndex, fileName.length()); } }
addEmployeeUI.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>添加雇员title> head> <body> <h1>添加雇员h1> <form action="${APP_PATH}/employee.do?action=addEmployee" method="post"> <table> <tr> <td>name:td> <td><input type="text" name="name" value="张三4">td> tr> <tr> <td>email:td> <td><input type="text" name="email" value="[email protected]">td> tr> <tr> <td>salary:td> <td><input type="text" name="salary" value="5000">td> tr> <tr> <td>password:td> <td><input type="password" name="password" value="1">td> tr> <tr> <td>grade:td> <td><input type="text" name="grade" value="1">td> tr> <tr> <td>department_id:td> <td><select name="department_id"> <option value="1" selected>部门1option> select>td> tr> <tr> <td><input type="submit" name="sub1" value="添加">td> <td><input type="reset" name="reset" value="重置">td> tr> table> form> body> html>
login.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>管理员登录title> head> <body> <h1>管理员登录h1> <form action="${APP_PATH}/login.do?action=doLogin" method="post"> <table> <tr> <td>id:td> <td><input type="text" name="id" value="1">td> tr> <tr> <td>name:td> <td><input type="text" name="name" value="1哈哈">td> tr> <tr> <td>pwd:td> <td><input type="password" name="password" value="1">td> tr> <tr> <td><input type="submit" name="sub1" value="登录">td> <td><input type="reset" name="reset" value="重置">td> tr> table> form> body> html>
main.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>登录成功title> head> <body> <h1>登录成功h1> <a href="${APP_PATH}/login.do?action=login">返回登录a> <h2>欢迎 【${employee.name}】 您所在的部门是 【${employee.getDepartment().getName()} 】请选择您要进行的操作h2> <a href="${APP_PATH}/employee.do?action=addEmployeeUI">添加雇员a> <br/> <a href="#">显示雇员a> <br/> <a href="#">查询雇员a> <br/> <a href="#">退出系统a> <br/> body> html>
ok.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>成功title> head> <body> <h1>成功h1> <a href="#">返回继续添加a> <a href="#">返回主界面a> <a href="${APP_PATH}/login.do?action=login">返回登录a> body> html>
err.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>操作失败title> head> <body> <h1>操作失败h1> <a href="#">操作失败,返回主界面a> <a href="${APP_PATH}/login.do?action=login">返回登录a> body> html>
index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>$Title$title> head> <body> <jsp:forward page="WEB-INF/jsp/login.jsp">jsp:forward> body> html>