Recently, a system in the development company was built with the ssm framework. Of course, it is different from the blog this time. It has many configuration files. The configuration files required for enterprise-level development are very cumbersome. Today I will record the construction of a simple SSM framework and the operation of implementing a CRUD.
We use the Maven plug-in to configure the jar package we need. Since there are not many operations, we do not configure a lot. We should pay attention to the version of jdk you use and select jdk with different version numbers
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.lr</groupId> <artifactId>ssm</artifactId> <packaging>war</packaging> <version>0.0.1-SNAPSHOT</version> <name>ssm Maven Webapp</name> <url>http://maven.apache.org</url> <!-- Used to set the version number --> <properties> <srping.version>4.0.2.RELEASE</srping.version> <mybatis.version>3.2.8</mybatis.version> <slf4j.version>1.7.12</slf4j.version> <log4j.version>1.2.17</log4j.version> </properties> <!-- Used jar package--> <dependencies> <!-- Unit Test--> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> <!-- means that this package will not be loaded during development --> <scope>test</scope> </dependency> <!-- java ee package--> <dependency> <groupId>javax</groupId> <artifactId>javaee-api</artifactId> <version>7.0</version> </dependency> <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.8.8</version> </dependency> <!-- spring framework package start --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${srping.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${srping.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-oxm</artifactId> <version>${srping.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>${srping.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>${srping.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>${srping.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${srping.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> <version>${srping.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-expression</artifactId> <version>${srping.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> <version>${srping.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${srping.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webvc</artifactId> <version>${srping.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aspects</artifactId> <version>${srping.version}</version> </dependency> <!-- spring framework package end --> <!-- mybatis framework package start --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>${mybatis.version}</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.2.2</version> </dependency> <!-- mybatis framework package end --> <!-- database driver --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.35</version> </dependency> <!-- Import dbcp jar package to configure the database in applicationContext.xml--> <dependency> <groupId>commons-dbcp</groupId> <artifactId>commons-dbcp</artifactId> <version>1.4</version> </dependency> <!-- jstl tag class --> <dependency> <groupId>jstl</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <dependency> <groupId>taglibs</groupId> <artifactId>standard</artifactId> <version>1.1.2</version> </dependency> <!-- log start --> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>${log4j.version}</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>${slf4j.version}</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>${slf4j.version}</version> </dependency> <!-- log END --> <!-- Json --> <!-- Format objects to facilitate log output --> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.6</version> </dependency> <dependency> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-mapper-asl</artifactId> <version>1.9.13</version> </dependency> <!-- Upload component package start --> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.1</version> </dependency> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.4</version> </dependency> <dependency> <groupId>commons-codec</groupId> <artifactId>commons-codec</artifactId> <version>1.10</version> </dependency> <!-- Upload component package end --> <!-- AL related addition --> <dependency> <groupId>net.sourceforge.jexcelapi</groupId> <artifactId>jxl</artifactId> <version>2.6</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>3.8</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>3.9</version> </dependency> <!-- AL related addition--> </dependencies> <build> <finalName>Maven_Project</finalName> <plugins> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>2.3.2</version> <configuration> <source>1.7</source> <target>1.7</target> </configuration> </plugin> </plugins> </build> </project>Then configure the database connection and change it to your own database.
driver=com.mysql.jdbc.Driverurl=jdbc/:mysql/://locahost/:3306/dbusername=rootpassword=rootmaxActive=20maxIdle=20minIdle=1maxWait=60000
The configuration file spring-dao.xml will automatically find the class under it.
<?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:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd"> <!-- The package name where the DAO interface is located, Spring will automatically find the class below it --> <bean> <!--basePackage specifies the package to be scanned, and the mappers under this package will be searched. Multiple packages can be specified, separated by commas or semicolons between packages --> <property name="basePackage" value="com.lr.dao" /> <property name="sqlSessionFactory" ref="sqlSessionFactory"></property> </bean> </beans>
Consolidated files for configuration files Spring and Mybatis
<?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:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd"> <!-- Introducing configuration files --> <context:property-placeholder location="classpath:/jdbc.properties" /> <bean id="dataSource" destroy-method="close"> <property name="driverClassName" value="com.mysql.jdbc.Driver" /> <property name="url" value="jdbc:mysql://localhost:3306/db?useUnicode=true&characterEncoding=utf8" /> <property name="username" value="root" /> <property name="password" value="root" /> <!-- Initialize connection size --> <property name="initialSize" value="3" /> <!-- Maximum number of connection pools --> <property name="maxActive" value="20" /> <!-- Maximum free connection pools --> <property name="maxIdle" value="20" /> <!-- Minimum free connection pools --> <property name="maxIdle" value="20" /> <!-- Minimum free connection pools --> <property name="minIdle" value="1" /> <!-- Get the maximum connection waiting time --> <property name="maxWait" value="60000" /> </bean> <!-- Spring and MyBatis are perfectly integrated, and there is no need for mybatis configuration mapping file --> <bean id="sqlSessionFactory"> <property name="dataSource" ref="dataSource" /> <!-- Automatically scan mapping.xml file --> <property name="mapperLocations" value="classpath:com/lr/mapper/*.xml"></property> </beans>
Configure the file for things
<?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:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd"> <!-- (Transaction Management) transaction manager, use JtaTransactionManager for global tx --> <bean id="transactionManager" > <property name="dataSource" ref="dataSource" /> </bean> <!-- Configure the class participating in the transaction --> <aop:config> <aop:pointcut id="allServiceMethod" expression="execution(* com.lr.service.*.*(..))"/> <aop:advisor pointcut-ref="allServiceMethod" advice-ref="txAdvice" /> </aop:config> <!-- Configure transactions using declaration--> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="*" propagation="REQUIRED" rollback-for="java.lang.Exception"/> </tx:attributes> </tx:advice> </beans>
Configure Springmvc.xml file
<?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:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd"> <!-- Automatic scan --> <context:component-scan base-package="com.lr.controller" /> <mvc:annotation-driven /> <mvc:default-servlet-handler/> <!-- Define the pre-suffix of the jumped file, view mode configuration --> <bean> <property name="prefix" value="/WEB-INF/jsp/" /> <property name="suffix" value=".jsp" /> </bean>
alright! ! ! The file that needs to be configured has been configured, enough for us to perform a wave of operations.
Next is some code in the background, which mainly includes entity classes, dao layer, service layer, and controller layer. I uploaded the background files together. The mapper.xml file is the most critical part of the implementation method.
<?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.lr.dao.IUserDao"> <resultMap id="BaseResultMap" type="com.lr.dto.User"> <result column="id" property="id" jdbcType="INTEGER" /> <result column="name" property="name" jdbcType="VARCHAR" /> <result column="password" property="password" jdbcType="VARCHAR" /> <result column="age" property="age" jdbcType="INTEGER" /> </resultMap> <sql id="Base_Column_List"> id, name, password, age </sql> <!-- Add user--> <insert id="addUser" parameterType="com.lr.dto.User"> insert into user(name,password,age) values(#{name},#{password},#{age}) </insert> <!-- Query user--> <select id="queryByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer"> select <include refid="Base_Column_List" /> from user where id = #{id} </select> <!-- Delete user--> <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer"> delete from user where id = #{id} </delete> <!-- Update user--> <update id="updateByPrimaryKey" parameterType="com.lr.dto.User" > update user set name=#{name},password=#{password},age=#{age} where id=#{id} </update> <select id="findallUser" resultType="com.lr.dto.User"> select * from user </select> </mapper> package com.lr.dao;import java.util.List;import com.lr.dto.User;public interface IUserDao { //Query user public User queryByPrimaryKey(int id); //Delete user public int deleteByPrimaryKey(int id); //Update user public int updateByPrimaryKey(User user); //Add user public int addUser(User user); //Query all users public List<User> findallUser();} package com.lr.service;import java.util.List;import com.lr.dto.User;public interface IUserService { //Query user public User getUserById(int userId); //Delete public void deleteUser(int id); //Update user public void updateUser(User user); //Add user public void addUser(User user); //View all users public List<User> findallUser();} package com.lr.service.Impl;import java.util.List;import javax.annotation.Resource;import org.springframework.stereotype.Service;import com.lr.dao.IUserDao;import com.lr.dto.User;import com.lr.service.IUserService;@Service("userService")public class UserServiceImpl implements IUserService{ @Resource private IUserDao userdao; public IUserDao getUserdao() { return userdao; } public void setUserdao(IUserDao userdao) { this.userdao = userdao; } //Query user @Override public User getUserById(int userId) { return userdao.queryByPrimaryKey(userId); } //Update user @Override public void updateUser(User user) { userdao.updateByPrimaryKey(user); } //Delete user @Override public void deleteUser(int id) { userdao.deleteByPrimaryKey(id); } //Add user @Override public void addUser(User user) { userdao.addUser(user); } //Query all users @Override public List<User> findallUser() { return userdao.findallUser(); }} package com.lr.controller;import java.util.List;import javax.servlet.http.HttpServletRequest;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Controller;import org.springframework.ui.Model;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.ResponseBody;import com.lr.dto.User;import com.lr.service.IUserService;@Controllerpublic class UserController { @Autowired private IUserService userService; public IUserService getUserService() { return userService; } public void setUserService(IUserService userService) { this.userService = userService; } //Main page @RequestMapping("/") public String userMgr() { return "showUser"; } //Add user @RequestMapping("/addUser") @ResponseBody public void userAdd(User user) { userService.addUser(user); } //Delete user @RequestMapping("/deleteUser") @ResponseBody public void deleteUser(int id){ userService.deleteUser(id); } //Modify user @RequestMapping("/updateUser") @ResponseBody public void uploadteUser(User user){ userService.updateUser(user); } //Find user based on id @RequestMapping("/showUser") @ResponseBody public User showUser(int id,Model model){ return userService.getUserById(id); } //Query all users @RequestMapping("/findallUser") @ResponseBody public List<User> findallUser(){ return userService.findallUser(); }} <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><!DOCTYPE HTML><html> <head> <meta charset="utf-8"><script type="text/javascript" src="<%= application.getContextPath() %>/js/jquery-1.12.4.min.js"></script> <script type="text/javascript"> //Add user $(function(){ $("#add").on("click", addNewUser); }) function addNewUser(){ var name = $.trim($("#txtName").val()); var password = $.trim($("#txtPassword").val()); var age = $.trim($("#txtAge").val()); $.post("/ssm/addUser", {"name": name, "password": password, "age": age}, function(){ alert("Add successful!") }); } //Delete user $(function(){ $("#delete").on("click",deleteUser); }) function deleteUser(){ var id=$.trim($("#deleteid").val()); $.get("/ssm/deleteUser",{"id":id},function(){ alert("Delete successful!") }); } //Query all users $(function(){ $("#findalluser").click(function(){ $.ajax({ type:"POST", dataType:"json", url:"/ssm/findallUser", success:function(msg){ var str=""; for(i in msg){ str+="<tr><th>"+msg[i].id+"</th><th>"+msg[i].name+"</th><th>" +msg[i].password+"</th><th>"+msg[i].age+"</th><tr>" } $("#findall").append(str); } }); }); }); //Finding a user based on id $(function(){ $("#find").click(function(){ $.ajax({ type:"POST", data:{id:$("#findid").val()}, dataType:"json", url:"/ssm/showUser", success:function(user){ var str=""; str+="<tr><th>"+user.id+"</th><th>"+user.name+"</th><th>" +user.password+"</th><th>"+user.age+"</th><tr>" $("#finduserbyid").append(str); } }) }) }) //Modify user information based on id $(function(){ $("#update").on("click",updateUser); }) function updateUser(){ alert($.trim($("#updateid").val())) alert($.trim($("#updatename").val())) alert($.trim($("#updatepassword").val())) alert($.trim($("#updateage").val())) var id=$.trim($("#updateid").val()); var name=$.trim($("#updatename").val()); var password=$.trim($("#updatepassword").val()); var age=$.trim($("#updateage").val()); $.post("/ssm/updateUser",{"id":id,"name":name,"password":password,"age":age},function(){ alert("Modified successfully!") }); } </script> <title>User Management</title> </head> <body> <div> <p>Name: <input type="text" id="txtName"></p> <p>Password: <input type="password" id="txtPassword"></p> <p>Age: <input type="text" id="txtAge"></p> <p><button id="add">Add</button></p> </div> <hr style="height:1px;border:none;border-top:1px dashed #0066CC;" /> <div> <p>Enter user id:<input type="text" id="deleteid"></p> <p><button id="delete">Delete</button></p> </div> <hr style="height:1px;border:none;border-top:1px dashed #0066CC;" /> <div><p><button id="findalluser">Query all</button></p></div> <div> <table > <thead id="findall"> <tr> <th>id</th> <th>name</th> <th>password</th> <th>age</th> </tr> </table> </div> <hr style="height:1px;border:none;border-top:1px dashed #0066CC;" /> <div> <p>Enter user id:<input type="text" id="findid"></p> <p><button id="find">Query</button></p> </div> <div> <table > <thead id="finduserbyid"> <tr> <th>id</th> <th>Name</th> <th>Password</th> <th>Age</th> </tr> </table> </div> <hr style="height:1px;border:none;border-top:1px dashed #0066CC;" /> <div> <p>Enter user id:<input type="text" id="updateid"></p> <p>Enter user name:<input type="text" id="updatename"></p> <p>Enter password: <input type="password" id="updatepassword"></p> <p>Enter user age:<input type="password" id="updateage"></p> <p><button id="update">Modify</button></p> </div> </body></html>