以前也在网上找了一些关于spring、springmvc、mybatis的项目框架,现在自己写了一个简单的员工管理
一、主要步骤
1.用idea创建一个maven工程
2.准备相关的jar包,不需要手动导入,maven自动创建
3.创建相关的包
4.创建相关的DAO层,Service层,Controller层
5.配置database.properties、Configuration.xml、applicationContext.xml等文件
6.配置web.xml文件
7.编写视图(jsp)
注:数据库自己建立即可
二、详细代码如下
pom.xml
<dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>4.3.2.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</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-tx</artifactId> <version>4.3.2.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</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-jms</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-webmvc</artifactId> <version>4.3.2.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc-portlet</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-instrument</artifactId> <version>4.3.2.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-instrument-tomcat</artifactId> <version>4.3.2.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>4.3.2.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</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-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.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.4.1</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.3.0</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.40</version> </dependency> <dependency> <groupId>commons-lang</groupId> <artifactId>commons-lang</artifactId> <version>2.3</version> </dependency> <dependency> <groupId>commons-dbcp</groupId> <artifactId>commons-dbcp</artifactId> <version>1.3</version> </dependency> <dependency> <groupId>commons-logging</groupId> <artifactId>commons-logging</artifactId> <version>1.1.1</version> </dependency> <dependency> <groupId>commons-pool</groupId> <artifactId>commons-pool</artifactId> <version>1.1</version> </dependency> <dependency> <groupId>commons-collections</groupId> <artifactId>commons-collections</artifactId> <version>3.1</version> </dependency> <dependency> <groupId>commons-beanutils</groupId> <artifactId>commons-beanutils</artifactId> <version>1.7.0</version> </dependency> <dependency> <groupId>net.sf.json-lib</groupId> <artifactId>json-lib</artifactId> <version>2.1</version> </dependency> <dependency> <groupId>net.sf.ezmorph</groupId> <artifactId>ezmorph</artifactId> <version>1.0.3</version> </dependency> </dependencies>
1.database.properties文件
jdbc.driverClassName=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/emp?characterEncoding=utf-8 jdbc.username=root jdbc.password=123
2.配置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:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd" default-autowire="byName" default-lazy-init="false"> <context:property-placeholder location="classpath:/spring/database.properties"/> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close" p:driverClassName="com.mysql.jdbc.Driver" p:url="jdbc:mysql://localhost:3306/emp" p:username="root" p:password="123" p:maxActive="10" p:maxIdle="10"> </bean> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"/> </bean> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <!--DataSource属性指定要用到的连接池--> <property name="dataSource" ref="dataSource"/> <property name="configLocation" value="classpath:/spring/Configuration.xml"/> <property name="mapperLocations" value="classpath*:/mapper/Employee.xml"/> </bean> <!--DAO,这里由于没有写DAO,采用的inter--> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.iflytek.inter"/> </bean> <!--测试配置--> <bean id="EmpMapper" class="org.mybatis.spring.mapper.MapperFactoryBean"> <property name="sqlSessionFactory" ref="sqlSessionFactory"/> <property name="mapperInterface" value="com.iflytek.inter.EmpOperation"/> </bean> </beans>
3.配置Configuration.xml
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"><configuration><typeAliases>
<!--通过package, 可以直接指定package的名字, mybatis会自动扫描你指定包下面的javabean, 并且默认设置一个别名,默认的名字为: javabean 的首字母小写的非限定类名来作为它的别名。 也可在javabean 加上注解@Alias 来自定义别名, 例如: @Alias(user) --><typeAlias type="com.iflytek.entity.Employee" alias="Employee"/></typeAliases></configuration>
4.Employee.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.iflytek.inter.EmpOperation">
<!--在mybatis中,映射文件中的namespace是用于绑定Dao接口的,即面向接口编程。
当你的namespace绑定接口后,你可以不用写接口实现类,mybatis会通过该绑定自动 帮你找到对应要执行的SQL语句--><!---sql代码 1.根据员工ID查看员工信息-->
<select id="selectEmpById" parameterType="int" resultType="Employee">
select * FROM employee WHERE empId = #{empId}
</select>
<!--查询数据,返回list-->
<resultMap id="resultEmployeeList" type="Employee">
<id column="empId" property="empId"/>
<result column="empName" property="empName"/>
<result column="empAge" property="empAge"/>
<result column="empTelD" property="empTel"/>
<result column="empAddress" property="empAddress"/>
</resultMap>
<select id="selectEmp" resultMap="resultEmployeeList">
SELECT * FROM employee ;
</select>
<insert id="addEmp" parameterType="Employee" useGeneratedKeys="true" keyProperty="empId"> INSERT INTO employee(empName,empAge,empTel,empAddress)
VALUES (#{empName},#{empAge},#{empTel},#{empAddress})
</insert>
<update id="updateEmp" parameterType="Employee">
UPDATE employee SET empName = #{empName},empAge = #{empAge},empTel = #{empTel},empAddress = #{empAddress} WHERE empId = #{empId}
</update>
<delete id="deleteEmp" parameterType="int">
DELETE FROM employee WHERE empId = #{empId}
</delete>
</mapper>
5.web.xml
<?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"> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <filter> <filter-name>encoding</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> <init-param> <param-name>forceEncoding</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>encoding</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath*:spring/applicationContext.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <listener> <listener-class>org.springframework.web.context.ContextCleanupListener</listener-class> </listener> <servlet> <servlet-name>dispatcher</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>dispatcher</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app>
6.dispatcher-servlet.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 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 http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd"> <context:component-scan base-package="com.iflytek.controller"/> <mvc:annotation-driven/> <!-- <mvc:resources mapping="/static/**" location="/WEB-INF/static/"/> --> <mvc:default-servlet-handler/> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> </bean> </beans>
7. model(entity)文件
package com.iflytek.entity;
import java.io.Serializable;
public class Employee implements Serializable {private int empId; //员工IDprivate String empName;//员工姓名private String empAge;//员工年龄private String empTel;//员工电话号码private String empAddress;//员工地址public Employee() { }public Employee(int empId, String empName, String empAge, String empTel, String empAddress) {empId = empId;this.empName = empName;this.empAge = empAge;this.empTel = empTel;this.empAddress = empAddress; }public String getEmpTel() {
return empTel; }public void setEmpTel(String empTel) {
this.empTel = empTel; }public int getEmpId() {
return empId;}public void setEmpId(int empId) {this.empId = empId;}public String getEmpName() {
return empName; }public void setEmpName(String empName) {
this.empName = empName; }public String getEmpAge() {
return empAge; }public void setEmpAge(String empAge) {
this.empAge = empAge; }public String getEmpAddress() {
return empAddress; }public void setEmpAddress(String empAddress) {
this.empAddress = empAddress; }@Override
public String toString() {return "Employee{" +"empId=" + empId +", empName='" + empName + '\'' +", empAge='" + empAge + '\'' + ", empTel='" + empTel + '\'' + ", empAddress='" + empAddress + '\'' + '}'; }}
8.inter代码如下
package com.iflytek.inter;
import com.iflytek.entity.Employee;
import java.util.List;
public interface EmpOperation {
public Employee selectEmpById(int empId);//根据ID查看信息public List<Employee> selectEmp();//查看员工信息public void addEmp(Employee employee);//新增员工信息public void updateEmp(Employee employee);//修改员工信息public void deleteEmp(int empId);//删除员工信息}9.controller代码如下package com.iflytek.controller; import com.iflytek.entity.Employee; import com.iflytek.inter.EmpOperation; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.multipart.support.AbstractMultipartHttpServletRequest; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; import java.util.List; @Controller public class EmpController { @Autowired EmpOperation empOperation; @RequestMapping(value="login") public ModelAndView listAllEmp(HttpServletRequest request, HttpServletResponse response) throws IOException { ModelAndView mv = null; response.setCharacterEncoding("utf-8"); response.setContentType("text/html;charset=utf-8"); String accout = request.getParameter("account"); String password = request.getParameter("password"); if(accout.equals("admin") && password.equals("123")){ request.getSession().setAttribute("account",accout); List<Employee> emp = empOperation.selectEmp(); for (Employee e:emp){ System.out.println(e.toString()); } mv = new ModelAndView("list.jsp"); mv.addObject("emp",emp); }else{ PrintWriter pw = response.getWriter(); pw.println("<script type='text/javascript'>"); pw.println("alert('用户或密码不正确');"); pw.println("window.location.href='index.jsp';"); pw.println("</script>"); } return mv; } }10.test代码 这里没有使用junit测试,只用了main方法package com.iflytek.test; import com.iflytek.entity.Employee; import com.iflytek.inter.EmpOperation; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import java.util.List; public class Test { private static ApplicationContext ctx; static{ ctx = new ClassPathXmlApplicationContext("/spring/applicationContext.xml"); } public static void main(String[] args) { EmpOperation mapper = (EmpOperation)ctx.getBean("EmpMapper"); List<Employee> emp = mapper.selectEmp(); for(Employee emps:emp){ System.out.println(emps.toString()); } System.out.println("成功"); } }11.index.jsp如下<body> <center> <font color="red">员工入口</font><hr/> <form action="login" method="post"> <table> <tr> <td>用户账号:</td> <td><input type="text" name="account" value=""/></td> </tr> <tr> <td>用户密码:</td> <td><input type="password" name="password" value=""/></td> </tr> <tr> <td colspan="2"> <input type="submit" value="登录" οnclick="return check(this.form)";/> <input type="reset" value="重置"/> </td> </tr> </table> </form> </center> </body>12.list.jsp代码如下<body> <center> <h3>欢迎进入员工管理系统</h3> <table border="1" bgcolor="#E5E5E5" bordercolor="#f0f0f0" width="480" height="20px" > <tr> <td width="80">员工ID</td> <td >员工姓名</td> <td width="100">员工年龄</td> <td width="100">联系方式</td> <td width="100">地址</td> </tr> </table > <table style="border-collapse: collapse"; border="1" bordercolor="black" width="480" height="40"> <c:forEach items="${emp}" var="e"> <tr> <td width="80">${e.empId}</td> <td width="100">${e.empName}</td> <td width="100">${e.empAge}</td> <td width="100">${e.empTel}</td> <td width="100">${e.empAddress}</td> </tr> </c:forEach> </table> </center> </body>13.项目的整体结构如下
附项目运行页面