标签:xmlns eal spec 框架 image inno view lib 定向
最近通过学习别人博客发表的SSM搭建Demo,尝试去搭建一个简单的SSMDemo---实现的功能是对用户增删改查的操作
参考博客链接
工程结构
src目录结构
工程所需jar包(jar包是网上下载的)
package com.ssm.ljn.user.model;
import java.io.Serializable;
/**
*
* <p>
* <b>用户实体类</b></>
*
* @author Luojiening
*/
public class User implements Serializable {
private int id;
private String username;
private int age;
private String sex;
public User() {
super();
}
public User(int id, String username, int age, String sex) {
super();
this.id = id;
this.username = username;
this.age = age;
this.sex = sex;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
}
package com.ssm.ljn.user.dao;
import java.util.List;
import org.springframework.stereotype.Repository;
import com.ssm.ljn.user.model.User;
@Repository
public interface IUserDao {
void saveUser(User user);
boolean updateUser(User user);
boolean deleteUser(int id);
User queryUserById(int id);
List<User> queryAllUser();
}
<?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">
<!--
namespace:必须与对应的接口全类名一致 UserMapper.java
id :必须与对应接口的某个对应的方法名一致即必须要和UserMapper.java接口中的方法同名。
-->
<mapper namespace="com.ssm.ljn.user.dao.IUserDao">
<!-- 新增用户-->
<insert id="saveUser" parameterType="com.ssm.ljn.user.model.User">
insert into User(user_id,user_name,user_age,user_sex) value(#{id},#{username},#{age},#{sex})
</insert>
<!-- 修改用户 -->
<update id="updateUser" parameterType="com.ssm.ljn.user.model.User">
update User set user_name=#{username},user_age=#{age},user_sex=#{sex} where user_id=#{id}
</update>
<!-- 删除用户 -->
<delete id="deleteUser" parameterType="com.ssm.ljn.user.model.User">
delete from User where user_id = #{id}
</delete>
<!-- 根据id查找用户 -->
<select id="queryUserById" parameterType="int" resultType="com.ssm.ljn.user.model.User">
select user_id id,user_name username,user_age age,user_sex sex from User where user_id=#{id}
</select>
<!-- 查询所有用户 -->
<select id="queryAllUser" resultType="com.ssm.ljn.user.model.User">
select user_id id,user_name userName,user_age age,user_sex sex from User order by id
</select>
</mapper>
<?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:aop="http://www.springframework.org/schema/aop"
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/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<!-- 注解扫描包 -->
<context:component-scan base-package="com.ssm.ljn.user" />
<!-- 配置整合mybatis过程 -->
<!-- 1.配置数据库相关参数properties的属性:${url} -->
<context:property-placeholder location="classpath:cfg/jdbc.properties" />
<!-- 2.数据库连接池 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<!-- 配置连接池属性 -->
<property name="driverClass" value="${jdbc.driver}"></property>
<property name="jdbcUrl" value="${jdbc.url}"></property>
<property name="user" value="${jdbc.username}"></property>
<property name="password" value="${jdbc.password}"></property>
<!-- c3p0连接池的私有属性 -->
<property name="maxPoolSize" value="30"></property>
<property name="minPoolSize" value="5"></property>
<!-- 关闭连接后不自动commit -->
<property name="autoCommitOnClose" value="false"></property>
<!-- 获取连接超时时间 -->
<property name="checkoutTimeout" value="10000"></property>
<!-- 当获取连接失败重试次数 -->
<property name="acquireRetryAttempts" value="2"></property>
</bean>
<!-- 3.配置SqlSessionFactory对象 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<!-- 指定Mybatis全局配置文件的位置 -->
<property name="configLocation" value="classpath:cfg/mybatis.xml"></property>
<property name="mapperLocations" value="classpath:com/ssm/ljn/user/model/mybatis/User.xml"></property>
</bean>
<!-- 配置mybatis的代理接口开发 * 接口类名和映射文件必须同名 * 接口类和映射文件必须在同一个目录下 * 接口的映射文件的namespace名称必须是接口的全限定名
* 接口的方法名必须和映射的statement的id一致 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- 扫描所有dao接口的实现,加入到ioc容器中 -->
<property name="basePackage" value="com.ssm.ljn.user.dao"></property>
<property name="SqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
</bean>
<!--事物 -->
<bean id="txManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 配置拦截service -->
<aop:config>
<aop:pointcut expression="execution(* com.ssm.ljn.user.service.impl.*.*(..))" id="txPoint"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="txPoint"/>
</aop:config>
<!-- 配置事物增强,事物如何切入-->
<tx:advice id="txAdvice" transaction-manager="txManager">
<tx:attributes>
<!-- 所有方法都是事物方法 -->
<tx:method name="*"/>
<!-- 以get开始的所有方法 -->
<tx:method name="get*" read-only="true"/>
</tx:attributes>
</tx:advice>
</beans>
<?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 name="com.ssm.ljn.*.model"/>
</typeAliases>
<!-- mybatis分页插件 -->
<plugins>
<plugin interceptor="com.github.pagehelper.PageHelper"></plugin>
</plugins>
</configuration>
<?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:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.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/context/spring-tx.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
">
<!-- 扫描注解包 -->
<context:component-scan base-package="com.ssm.ljn.user.action"></context:component-scan>
<!-- 配置sprigmvc视图解析器:解析逻辑试图
后台返回逻辑试图:index
视图解析器解析出真正物理视图:前缀+逻辑试图+后缀====/WEB-INF/page/index.jsp-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
<!--1: mvc:annotation-driven默认创建了 RequestMappingHandlerMapping和 RequestMappingHandlerAdapter对象
提供对JSon数据格式的支持-->
<mvc:annotation-driven />
<!-- 2.配置静态资源访问 -->
<mvc:default-servlet-handler/>
<!-- 使用CGLib动态代理技术 -->
<aop:aspectj-autoproxy proxy-target-class="true" />
</beans>
#jdbc.properties
jdbc.driver = com.mysql.jdbc.Driver
jdbc.url = jdbc:mysql://127.0.0.1:3306/ssm?useUnicode=true&characterEncoding=utf8&useSSL=false
jdbc.username = root
jdbc.password = 123456
### set log levels ###
log4j.rootLogger = INFO , console , debug , error
### console ###
log4j.appender.console = org.apache.log4j.ConsoleAppender
log4j.appender.console.Target = System.out
log4j.appender.console.layout = org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern = %-d{yyyy-MM-dd HH\:mm\:ss} [%p]-[%c] %m%n
### log file ###
log4j.appender.debug = org.apache.log4j.DailyRollingFileAppender
log4j.appender.debug.File = ../logs/springmvc-demo.log
log4j.appender.debug.Append = true
log4j.appender.debug.Threshold = INFO
log4j.appender.debug.layout = org.apache.log4j.PatternLayout
log4j.appender.debug.layout.ConversionPattern = %-d{yyyy-MM-dd HH\:mm\:ss} [%p]-[%c] %m%n
### exception ###
log4j.appender.error = org.apache.log4j.DailyRollingFileAppender
log4j.appender.error.File = ../logs/springmvc-demo_error.log
log4j.appender.error.Append = true
log4j.appender.error.Threshold = ERROR
log4j.appender.error.layout = org.apache.log4j.PatternLayout
log4j.appender.error.layout.ConversionPattern = %-d{yyyy-MM-dd HH\:mm\:ss} [%p]-[%c] %m%n
###log4j.error.key not found
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ISO8601} %l %c%n%p: %m%n
### druid sql ###
log4j.logger.druid.sql=warn,stdout
log4j.logger.druid.sql.DataSource=warn,stdout
log4j.logger.druid.sql.Connection=warn,stdout
log4j.logger.druid.sql.Statement=warn,stdout
log4j.logger.druid.sql.ResultSet=warn,stdout
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:web="http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>SSMDemo</display-name>
<!-- 加载Spring容器配置 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:cfg/spring-mybatis.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 配置SpringMVC核心控制器 -->
<servlet>
<servlet-name>dispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:cfg/springmvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<!-- 拦截所有请求 -->
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!-- 字符编码过滤器 -->
<filter>
<filter-name>CharacterEncodingFilter</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>
</filter>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
package com.ssm.ljn.user.service;
import java.util.List;
import org.springframework.stereotype.Service;
import com.ssm.ljn.user.model.User;
public interface IUserService {
void saveUser(User user);
boolean updateUser(User user);
boolean deleteUser(int id);
User queryUserById(int id);
List<User> queryAllUser();
}
package com.ssm.ljn.user.service.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.ssm.ljn.user.dao.IUserDao;
import com.ssm.ljn.user.model.User;
import com.ssm.ljn.user.service.IUserService;
@Service("userService")
@Transactional
public class UserService implements IUserService{
@Autowired
private IUserDao iUserDao;
@Override
public void saveUser(User user) {
iUserDao.saveUser(user);
}
@Override
public boolean updateUser(User user) {
return iUserDao.updateUser(user);
}
@Override
public boolean deleteUser(int id) {
return iUserDao.deleteUser(id);
}
@Override
public User queryUserById(int id) {
return iUserDao.queryUserById(id);
}
@Override
public List<User> queryAllUser() {
return iUserDao.queryAllUser();
}
}
package com.ssm.ljn.user.action;
import java.util.List;
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.RequestParam;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ssm.ljn.user.model.User;
import com.ssm.ljn.user.service.IUserService;;
@Controller
@RequestMapping("/user")
public class UserAction {
@Autowired
private IUserService iUserService;
/**
*跳转到添加用户界面
*/
@RequestMapping("toAddUser")
public String toAddUser(){
return "addUser";
}
/**
* 添加用户并重定向
* @param model
* @param user
* @return
*/
@RequestMapping("addUser")
public String addUser(Model model,User user){
if(user != null){
iUserService.saveUser(user);
}
return "redirect:/user/userInfo";
}
/**
* 修改用户
* @param model
* @param request
* @param user
* @return
*/
@RequestMapping("updateUser")
public String UpdateUser(Model model,User user){
if(iUserService.updateUser(user)){
user = iUserService.queryUserById(user.getId());
model.addAttribute("user", user);
return "redirect:/user/userInfo";
}
return "/error";
}
/**
* 查询所有用户
* @param request
* @param model
* @return
*/
@RequestMapping("getAllUser")
public String getAllUser(Model model){
List<User> user = iUserService.queryAllUser();
model.addAttribute("userList",user);
return "allUser";
}
/**
* 查询单个用户
* @param id
* @param request
* @param model
* @return
*/
@RequestMapping("/getUser")
public String getUser(int id,Model model){
model.addAttribute("user", iUserService.queryUserById(id));
return "editUser";
}
/**
* 根据id删除用户
* @param id
* @param request
* @param response
*/
@RequestMapping("/delUser")
public String deleteUser(int id,Model model){
model.addAttribute("user", iUserService.deleteUser(id));
return "redirect:/user/userInfo";
}
@RequestMapping("userInfo")
public String getUsers(@RequestParam(value="pn",defaultValue="1")Integer pn,Model model){
//从第一条开始 每页查询五条数据
PageHelper.startPage(pn, 5);
List<User> users = iUserService.queryAllUser();
//将用户信息放入PageInfo对象里
PageInfo page = new PageInfo(users,5);
model.addAttribute("pageInfo", page);
return "allUser";
}
}
WebContent目录结构
index界面
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
pageContext.setAttribute("path", request.getContextPath());
%>
<!DOCTYPE htm >
<html>
<head>
<title>首页</title>
<style type="text/css">
a {
text-decoration: none;
color: #fff;
font-size: 14px;
}
h3 {
width: 180px;
height: 38px;
margin: 100px auto;
text-align: center;
line-height: 38px;
background: #5BC0DE;
border-radius: 4px;
}
</style>
</head>
<body>
<h3>
<a href="${path }/user/userInfo">进入用户管理页</a>
</h3>
</body>
</html>
jsp页面主要有显示所有用户、新增用户以及修改用户三部分组成
allUser.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%
pageContext.setAttribute("path", request.getContextPath());
%>
<!DOCTYPE HTML>
<html>
<head>
<title>用户列表</title>
<link
href="${path}/resource/css/bootstrap.min.css"
rel="stylesheet">
<script type="text/javascript"
src="${path}/resource/js/jquery-1.9.1.min.js"></script>
<script type="text/javascript"
src="${path}/resource/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<!-- 标题 -->
<div class="row">
<div class="col-md-12">
<h1>用户管理</h1>
</div>
</div>
<!-- 按钮 -->
<div class="row">
<div class="col-md-4 col-md-offset-8">
<a class="btn btn-primary" href="${path}/user/toAddUser">新增</a>
</div>
</div>
<!-- 表格 -->
<div class="row">
<div class="col-md-12">
<table class="table table-hover">
<tr>
<th>id</th>
<th>用户名</th>
<th>年龄</th>
<th>性别</th>
<th>操作</th>
</tr>
<c:forEach items="${pageInfo.list }" var="user">
<tr>
<td>${user.id}</td>
<td>${user.username }</td>
<td>${user.age }</td>
<td>${user.sex }</td>
<!-- <td><a class="edit">编辑</a> <a
class="delete">删除</a></td> -->
<td>
<a type="button" href="${path}/user/getUser?id=${user.id}" class="btn btn-info btn-sm">
<span class="glyphicon glyphicon-pencil" aria-hidden="true"></span>
编辑</a>
<a type="button" href="${path}/user/delUser?id=${user.id}" class="btn btn-danger btn-sm">
<span class="glyphicon glyphicon-trash" aria-hidden="true" ></span>
删除</a>
</td>
</tr>
</c:forEach>
</table>
</div>
</div>
<hr style="height:1px;border:none;border-top:1px solid #ccc;" />
<!-- 分页导航栏 -->
<!-- 分页信息 -->
<div class="row">
<!-- 分页文字信息,其中分页信息都封装在pageInfo中 -->
<div class="col-md-6">
当前第:${pageInfo.pageNum}页,总共:${pageInfo.pages}页,总共:${pageInfo.total}条记录
</div>
<!-- 分页条 -->
<div class="col-md-6">
<nav aria-label="Page navigation">
<ul class="pagination">
<li><a href="${path}/user/userInfo?pn=1">首页</a></li>
<c:if test="${pageInfo.hasPreviousPage }">
<li>
<a href="${path}/user/userInfo?pn=${pageInfo.pageNum-1}" aria-label="Previous">
<span aria-hidden="true">«</span>
</a>
</li>
</c:if>
<c:forEach items="${pageInfo.navigatepageNums }" var="page_Num">
<c:if test="${page_Num == pageInfo.pageNum }">
<li class="active"><a href="#">${ page_Num}</a></li>
</c:if>
<c:if test="${page_Num != pageInfo.pageNum }">
<li><a href="${path}/user/userInfo?pn=${ page_Num}">${ page_Num}</a></li>
</c:if>
</c:forEach>
<c:if test="${pageInfo.hasNextPage }">
<li>
<a href="${path}/user/userInfo?pn=${pageInfo.pageNum+1}" aria-label="Next">
<span aria-hidden="true">»</span>
</a>
</li>
</c:if>
<li><a href="${path}/user/userInfo?pn=${pageInfo.pages}">末页</a></li>
</ul>
</nav>
</div>
</div>
</div>
</body>
</html>
editUser.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://"
+ request.getServerName() + ":" + request.getServerPort()
+ path + "/";
%>
<!DOCTYPE html>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<html>
<head>
<title>编辑用户</title>
<script type="text/javascript">
function updateUser() {
var form = document.forms[0];
form.action = "<%=basePath %>user/updateUser";
form.method = "post";
form.submit();
}
</script>
</head>
<body>
<h1>添加用户</h1>
<form action="" name="userForm">
<input type="hidden" name="id" value="${user.id }" /> 姓名:<input
type="text" name="username" value="${user.username }" /> 年龄:<input
type="text" name="age" value="${user.age }" />
性别:<input type="text" name="sex" value="${user.sex }" />
<input type="button" value="编辑" onclick="updateUser()" />
</form>
</body>
</html>
addUser.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://"
+ request.getServerName() + ":" + request.getServerPort()
+ path + "/";
%>
<html>
<title>添加用户</title>
</head>
<body>
<h1>添加用户</h1>
<form action="" name="userForm">
id:<input type="text" name="id"><br>
姓名:<input type="text" name="username"><br>
年龄:<input type="text" name="age"><br>
性别:<input type="text" name="sex"><br>
<input type="button" value="添加"
onclick="addUser()">
</form>
<script type="text/javascript">
function addUser() {
var form = document.forms[0];
form.action = "<%=basePath %>user/addUser";
form.method = "post";
form.submit();
}
</script>
</body>
</html>
数据库建表语句,相对较为简单,也没有任何的约束条件
CREATE TABLE `user` (
`user_id` int(50) NOT NULL,
`user_name` varchar(20) DEFAULT NULL,
`user_age` int(10) DEFAULT NULL,
`user_sex` varchar(2) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
在参考实现过程中遇到很多的问题,有的是jar的缺失引起的,有的是路径错误引起的,主要通过百度相关异常从而找到相应的解决方法。
最后,用户增删改查的界面调试成功
SSM(Spring +SpringMVC + Mybatis)框架搭建
标签:xmlns eal spec 框架 image inno view lib 定向
原文地址:https://www.cnblogs.com/Luojiening/p/8807216.html