JAVA中SSM框架的搭建实现CRUD的方法

最近在开发公司的一个系统,系统的框架是用ssm的框架搭建的,当然和这次写博客的不一样,它拥有很多的配置文件,企业级的开发所需要的配置文件是非常繁琐的,今天记录一下一个简单的SSM框架的搭建和实现一个CRUD的操作。

使用的是Maven插件来配置我们需要的jar包,由于操作不多,所以并没有配置很多,要注意自己使用的jdk的版本,选择不同版本号的jdk

<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>

<!-- 用来设置版本号 -->

<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>

<!-- 用到的jar包 -->

<dependencies>

<!-- 单元测试 -->

<dependency>

<groupId>junit</groupId>

<artifactId>junit</artifactId>

<version>4.11</version>

<!-- 表示开发的时候引入,发布的时候不会加载此包 -->

<scope>test</scope>

</dependency>

<!-- java ee包 -->

<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框架包 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-webmvc</artifactId>

<version>${srping.version}</version>

</dependency>

<dependency>

<groupId>org.springframework</groupId>

<artifactId>spring-aspects</artifactId>

<version>${srping.version}</version>

</dependency>

<!-- spring框架包 end -->

<!-- mybatis框架包 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框架包 end -->

<!-- 数据库驱动 -->

<dependency>

<groupId>mysql</groupId>

<artifactId>mysql-connector-java</artifactId>

<version>5.1.35</version>

</dependency>

<!-- 导入dbcp的jar包,用来在applicationContext.xml中配置数据库 -->

<dependency>

<groupId>commons-dbcp</groupId>

<artifactId>commons-dbcp</artifactId>

<version>1.4</version>

</dependency>

<!-- jstl标签类 -->

<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 -->

<!-- 格式化对象,方便输出日志 -->

<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>

<!-- 上传组件包 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>

<!-- 上传组件包 end -->

<!-- AL相关添加 -->

<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相关添加 -->

</dependencies>

<build>

<finalName>Maven_Project</finalName>

<plugins>

<plugin>

<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>

然后配置数据库的连接,改成自己的数据库就行了

driver=com.mysql.jdbc.Driver

url=jdbc\:mysql\://locahost\:3306/db

username=root

password=root

maxActive=20

maxIdle=20

minIdle=1

maxWait=60000

配置文件spring-dao.xml,Spring会自动查找其下的类

<?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/context"

xmlns:mvc="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">

<!-- DAO接口所在包名,Spring会自动查找其下的类 -->

<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">

<!--basePackage指定要扫描的包,在此包之下的映射器都会被搜索到。

可指定多个包,包与包之间用逗号或分号分隔-->

<property name="basePackage" value="com.lr.dao" />

<property name="sqlSessionFactory" ref="sqlSessionFactory"></property>

</bean>

</beans>

配置文件Spring和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/context"

xmlns:mvc="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">

<!-- 引入配置文件 -->

<context:property-placeholder location="classpath:/jdbc.properties" />

<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" 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" />

<!-- 初始化连接大小 -->

<property name="initialSize" value="3" />

<!-- 连接池最大数量 -->

<property name="maxActive" value="20" />

<!-- 连接池最大空闲 -->

<property name="maxIdle" value="20" />

<!-- 连接池最小空闲 -->

<property name="minIdle" value="1" />

<!-- 获取连接最大等待时间 -->

<property name="maxWait" value="60000" />

</bean>

<!-- spring和MyBatis完美整合,不需要mybatis的配置映射文件 -->

<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">

<property name="dataSource" ref="dataSource" />

<!-- 自动扫描mapping.xml文件 -->

<property name="mapperLocations" value="classpath:com/lr/mapper/*.xml"></property>

</bean>

</beans>

配置事物的文件

<?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/context"

xmlns:aop="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/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/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 manager, use JtaTransactionManager for global tx -->

<bean id="transactionManager"

class="org.springframework.jdbc.datasource.DataSourceTransactionManager">

<property name="dataSource" ref="dataSource" />

</bean>

<!-- 配置参与事务的类 -->

<aop:config>

<aop:pointcut id="allServiceMethod" expression="execution(* com.lr.service.*.*(..))"/>

<aop:advisor pointcut-ref="allServiceMethod" advice-ref="txAdvice" />

</aop:config>

<!-- 使用声明方式配置事务 -->

<tx:advice id="txAdvice" transaction-manager="transactionManager">

<tx:attributes>

<tx:method name="*" propagation="REQUIRED" rollback-for="java.lang.Exception"/>

</tx:attributes>

</tx:advice>

</beans>

配置Springmvc.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:p="http://www.springframework.org/schema/p"

xmlns:context="http://www.springframework.org/schema/context"

xmlns:mvc="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">

<!-- 自动扫描 -->

<context:component-scan base-package="com.lr.controller" />

<mvc:annotation-driven />

<mvc:default-servlet-handler/>

<!-- 定义跳转的文件的前后缀 ,视图模式配置-->

<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">

<property name="prefix" value="/WEB-INF/jsp/" />

<property name="suffix" value=".jsp" />

</bean>

好了!!!需要配置的文件已经配置完成了,足够我们进行一波操作了

接下来是后台的一些代码,这里主要是实体类,dao层,service层,controller层,我把后台的文件一起上传了,mapper.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.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>

<!-- 增加用户 -->

<insert id="addUser" parameterType="com.lr.dto.User">

insert into user(name,password,age) values(#{name},#{password},#{age})

</insert>

<!-- 查询用户-->

<select id="queryByPrimaryKey" resultMap="BaseResultMap"

parameterType="java.lang.Integer">

select

<include refid="Base_Column_List" />

from user

where id = #{id}

</select>

<!-- 删除用户 -->

<delete id="deleteByPrimaryKey" parameterType="java.lang.Integer">

delete from user

where id = #{id}

</delete>

<!-- 更新用户 -->

<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 {

//查询用户

public User queryByPrimaryKey(int id);

//删除用户

public int deleteByPrimaryKey(int id);

//更新用户

public int updateByPrimaryKey(User user);

//添加用户

public int addUser(User user);

//查询所有用户

public List<User> findallUser();

}

package com.lr.service;

import java.util.List;

import com.lr.dto.User;

public interface IUserService {

//查询用户

public User getUserById(int userId);

//删除

public void deleteUser(int id);

//更新用户

public void updateUser(User user);

//添加用户

public void addUser(User user);

//查看所有用户

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;

}

//查询用户

@Override

public User getUserById(int userId) {

return userdao.queryByPrimaryKey(userId);

}

//更新用户

@Override

public void updateUser(User user) {

userdao.updateByPrimaryKey(user);

}

//删除用户

@Override

public void deleteUser(int id) {

userdao.deleteByPrimaryKey(id);

}

//添加用户

@Override

public void addUser(User user) {

userdao.addUser(user);

}

//查询所有用户

@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;

@Controller

public class UserController {

@Autowired

private IUserService userService;

public IUserService getUserService() {

return userService;

}

public void setUserService(IUserService userService) {

this.userService = userService;

}

//主页面

@RequestMapping("/")

public String userMgr() {

return "showUser";

}

//添加用户

@RequestMapping("/addUser")

@ResponseBody

public void userAdd(User user) {

userService.addUser(user);

}

//删除用户

@RequestMapping("/deleteUser")

@ResponseBody

public void deleteUser(int id){

userService.deleteUser(id);

}

//修改用户

@RequestMapping("/updateUser")

@ResponseBody

public void upadteUser(User user){

userService.updateUser(user);

}

//根据id查找用户

@RequestMapping("/showUser")

@ResponseBody

public User showUser(int id,Model model){

return userService.getUserById(id);

}

//查询所有用户

@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">

//添加用户

$(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("添加成功!")

});

}

//删除用户

$(function(){

$("#delete").on("click",deleteUser);

})

function deleteUser(){

var id=$.trim($("#deleteid").val());

$.get("/ssm/deleteUser",{"id":id},function(){

alert("删除成功!")

});

}

//查询所有用户

$(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);

}

});

});

});

//根据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);

}

})

})

})

//根据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("修改成功!")

});

}

</script>

<title>用户管理</title>

</head>

<body>

<div>

<p>姓名:<input type="text" id="txtName"></p>

<p>密码:<input type="password" id="txtPassword"></p>

<p>年龄:<input type="text" id="txtAge"></p>

<p><button id="add">添加</button></p>

</div>

<hr style="height:1px;border:none;border-top:1px dashed #0066CC;" />

<div>

<p>输入用户id:<input type="text" id="deleteid"></p>

<p><button id="delete">删除</button></p>

</div>

<hr style="height:1px;border:none;border-top:1px dashed #0066CC;" />

<div><p><button id="findalluser">查询所有</button></p></div>

<div>

<table width="300" border="1" >

<thead id="findall">

<tr>

<th width="50">id</th>

<th width="50">姓名</th>

<th width="50">密码</th>

<th width="50">年龄</th>

</tr>

</thead>

</table>

</div>

<hr style="height:1px;border:none;border-top:1px dashed #0066CC;" />

<div>

<p>输入用户id:<input type="text" id="findid"></p>

<p><button id="find">查询</button></p>

</div>

<div>

<table width="300" border="1" >

<thead id="finduserbyid">

<tr>

<th width="50">id</th>

<th width="50">姓名</th>

<th width="50">密码</th>

<th width="50">年龄</th>

</tr>

</thead>

</table>

</div>

<hr style="height:1px;border:none;border-top:1px dashed #0066CC;" />

<div>

<p>输入用户id:<input type="text" id="updateid"></p>

<p>输入用户姓名:<input type="text" id="updatename"></p>

<p>输入密码:<input type="password" id="updatepassword"></p>

<p>输入用户年龄:<input type="password" id="updateage"></p>

<p><button id="update">修改</button></p>

</div>

</body>

</html>

以上是 JAVA中SSM框架的搭建实现CRUD的方法 的全部内容, 来源链接: utcz.com/p/215155.html

回到顶部