1.ssm整合
1.1.创建表
CREATE TABLE `account` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(20) DEFAULT NULL,
`money` double DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
1.2.创建工程
1.3.pom.xml
<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/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0modelVersion>
<groupId>com.wtgroupId>
<artifactId>ssmartifactId>
<version>1.0-SNAPSHOTversion>
<packaging>warpackaging>
<properties>
<spring.version>5.1.8.RELEASEspring.version>
<slf4j.version>1.6.6slf4j.version>
<log4j.version>1.2.12log4j.version>
<mysql.version>5.1.47mysql.version>
<mybatis.version>3.4.5mybatis.version>
<druid.version>1.1.0druid.version>
properties>
<dependencies>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-contextartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-aspectsartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-txartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-jdbcartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-webartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-webmvcartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatisartifactId>
<version>${mybatis.version}version>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatis-springartifactId>
<version>1.3.0version>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>${mysql.version}version>
dependency>
<dependency>
<groupId>com.alibabagroupId>
<artifactId>druidartifactId>
<version>1.1.0version>
dependency>
<dependency>
<groupId>javax.servletgroupId>
<artifactId>servlet-apiartifactId>
<version>2.5version>
<scope>providedscope>
dependency>
<dependency>
<groupId>javax.servlet.jspgroupId>
<artifactId>jsp-apiartifactId>
<version>2.0version>
<scope>providedscope>
dependency>
<dependency>
<groupId>jstlgroupId>
<artifactId>jstlartifactId>
<version>1.2version>
dependency>
<dependency>
<groupId>org.slf4jgroupId>
<artifactId>slf4j-log4j12artifactId>
<version>${slf4j.version}version>
dependency>
dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.tomcat.mavengroupId>
<artifactId>tomcat7-maven-pluginartifactId>
<version>2.2version>
<configuration>
<port>8080port>
<path>/path>
<uriEncoding>UTF-8uriEncoding>
configuration>
plugin>
<plugin>
<groupId>org.apache.maven.pluginsgroupId>
<artifactId>maven-compiler-pluginartifactId>
<version>3.2version>
<configuration>
<source>1.8source>
<target>1.8target>
<encoding>UTF-8encoding>
configuration>
plugin>
plugins>
<resources>
<resource>
<directory>src/main/javadirectory>
<includes>
<include>**/*.xmlinclude>
includes>
resource>
resources>
build>
project>
1.4.log4j.properties
log4j.rootLogger=DEBUG,A1
log4j.appender.A1=org.apache.log4j.ConsoleAppender
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
log4j.appender.A1.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} - %c%l%m%n
1.5.db.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ssm?characterEncoding=utf-8
jdbc.username=root
jdbc.password=1111
1.6.applicationContext-dao.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
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/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd">
<context:property-placeholder location="classpath:db.properties" />
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" destroy-method="close">
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
<property name="driverClassName" value="${jdbc.driver}" />
<property name="maxActive" value="10" />
<property name="minIdle" value="5" />
bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="typeAliasesPackage" value="com.wt.pojo">property>
bean>
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.wt.mapper">property>
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory">property>
bean>
beans>
1.7.applicationContext-tx.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
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/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd">
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
bean>
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="insert*" propagation="REQUIRED"/>
<tx:method name="delete*" propagation="REQUIRED"/>
<tx:method name="update*" propagation="REQUIRED"/>
<tx:method name="select*" propagation="SUPPORTS" read-only="true"/>
<tx:method name="get*" propagation="SUPPORTS" read-only="true"/>
tx:attributes>
tx:advice>
<aop:config>
<aop:advisor advice-ref="txAdvice" pointcut="execution(* com.wt.service.*.*(..))" />
aop:config>
beans>
1.8.applicationContext-service.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
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/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd">
<context:component-scan base-package="com.wt.service">context:component-scan>
beans>
1.9.springmvc.xml
<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.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="com.wt.controller">context:component-scan>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/pages/">property>
<property name="suffix" value=".jsp">property>
bean>
<mvc:annotation-driven conversion-service="cs">mvc:annotation-driven>
<bean id="cs" class="org.springframework.context.support.ConversionServiceFactoryBean">
<property name="converters">
<set>
<bean class="com.wantong.converter.DateConverter">bean>
set>
property>
bean>
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="52428800" />
<property name="defaultEncoding" value="UTF-8" />
bean>
<mvc:resources mapping="/head/**" location="/head/"/>
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/**">mvc:mapping>
<mvc:exclude-mapping path="/user/login"/>
<mvc:exclude-mapping path="/user/addUser"/>
<mvc:exclude-mapping path="/user/register"/>
<bean class="com.wantong.interceptor.LoginHandlerInterceptor">bean>
mvc:interceptor>
mvc:interceptors>
beans>
1.10.web.xml
<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_4_0.xsd"
version="4.0">
<context-param>
<param-name>contextConfigLocationparam-name>
<param-value>classpath:applicationContext-*.xmlparam-value>
context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>
listener>
<filter>
<filter-name>CharacterEncodingFilterfilter-name>
<filter-class>
org.springframework.web.filter.CharacterEncodingFilter
filter-class>
<init-param>
<param-name>encodingparam-name>
<param-value>UTF-8param-value>
init-param>
filter>
<filter-mapping>
<filter-name>CharacterEncodingFilterfilter-name>
<url-pattern>/*url-pattern>
filter-mapping>
<servlet>
<servlet-name>springmvcservlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
<init-param>
<param-name>contextConfigLocationparam-name>
<param-value>classpath:springmvc.xmlparam-value>
init-param>
<load-on-startup>1load-on-startup>
servlet>
<servlet-mapping>
<servlet-name>springmvcservlet-name>
<url-pattern>/url-pattern>
servlet-mapping>
web-app>
1.11.pojo
1.11.1 Account:
public class Account {
private Integer id;
private String name;
private Double money;
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 Double getMoney() {
return money;
}
public void setMoney(Double money) {
this.money = money;
}
@Override
public String toString() {
return "Account{" +
"id=" + id +
", name='" + name + '\'' +
", money=" + money +
'}';
}
}
1.11.2 User:
package com.wantong.pojo;
public class User {
private Integer id;
private String username;
private String password;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
1.12.mapper
1.12.1 Account:
public interface AccountMapper {
List<Account> selectAccount();
void addAccount(Account account);
Account getAccountById(Integer id);
void updateAccountById(Account account);
void deleteAccountById(Integer id);
}
DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.wt.mapper.AccountMapper">
<select id="selectAccount" resultType="Account">
select * from account
select>
<insert id="addAccount" parameterType="Account">
INSERT INTO account(name, money, date, head) VALUES(#{name}, #{money}, #{date}, #{head})
insert>
<select id="getAccountById" parameterType="java.lang.Integer" resultType="Account">
select * from account where id = #{id}
select>
<update id="updateAccountById" parameterType="Account">
UPDATE account
<set>
<if test="name!=null and name!=''">
name=#{name},
if>
<if test="money!=null">
money=#{money},
if>
<if test="date!=null">
date=#{date},
if>
<if test="head!=null and head!=''">
head=#{head},
if>
set>
WHERE id=#{id}
update>
<delete id="deleteAccountById" parameterType="int">
delete from account where id = #{id}
delete>
mapper>
1.12.2 User
package com.wantong.mapper;
import com.wantong.pojo.User;
public interface UserMapper {
void register(User user);
User login(User user);
}
DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.wantong.mapper.UserMapper">
<insert id="register" parameterType="User">
INSERT INTO user(username, password) VALUES(#{username}, #{password})
insert>
<select id="login" parameterType="User" resultType="User">
select * from user where username = #{username} and password = #{password}
select>
mapper>
1.13.service
1.13.1 Account
@Service
@Transactional
public class AccountServiceImpl implements AccountService {
@Autowired
private AccountMapper accountMapper;
@Override
public List<Account> selectAccount() {
return accountMapper.selectAccount();
}
@Override
public void addAccount(Account account) {
accountMapper.addAccount(account);
}
@Override
public Account getAccountById(Integer id) {
return accountMapper.getAccountById(id);
}
@Override
public void updateAccountById(Account account) {
accountMapper.updateAccountById(account);
}
@Override
public void deleteAccountById(Integer id) {
accountMapper.deleteAccountById(id);
}
}
1.13.2 User
@Service
@Transactional
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
@Override
public void register(User user) {
userMapper.register(user);
}
@Override
public User login(User user) {
return userMapper.login(user);
}
}
1.14.controller
1.14.1 Account
@Controller
@RequestMapping("/account")
public class AccountController {
@Autowired
private AccountService accountService;
@RequestMapping("/selectAccount")
public String selectAccount(Model model){
List<Account> list = accountService.selectAccount();
model.addAttribute("list",list);
return "select_account";
}
@RequestMapping("/toAddAccount")
public String toAddAccount(){
return "add_account";
}
@RequestMapping("/addAccount")
public String addAccount(Account account, MultipartFile img, HttpServletRequest request) throws IOException {
String realPath = request.getSession().getServletContext().getRealPath("/head/");
File file = new File(realPath);
if(!file.exists()){
file.mkdirs();
}
String filename = img.getOriginalFilename();
img.transferTo(new File(realPath, filename));
account.setHead(filename);
accountService.addAccount(account);
return "redirect:/account/selectAccount";
}
@RequestMapping("/toUpdateAccount")
public String toUpdateAccount(Integer id ,Model model){
Account account = accountService.getAccountById(id);
model.addAttribute("account",account);
return "update_account";
}
@RequestMapping("/updateAccount")
public String updateAccount(MultipartFile img ,Account account ,HttpServletRequest request) throws IOException {
if(!img.isEmpty()) {
String realPath = request.getSession().getServletContext().getRealPath("/head/");
String filename = img.getOriginalFilename();
img.transferTo(new File(realPath, filename));
account.setHead(filename);
}
accountService.updateAccountById(account);
return "redirect:/account/selectAccount";
}
@RequestMapping("/toDeleteAccount")
public String toDeleteAccount(Integer id){
accountService.deleteAccountById(id);
return "redirect:/account/selectAccount";
}
}
1.14.2 User
@Controller
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
@RequestMapping("/register")
public String selectAccount(){
return "register";
}
@RequestMapping("/addUser")
public String addUser(User user){
userService.register(user);
return "redirect:/index.jsp";
}
@RequestMapping("/login")
public String login(User user , HttpSession session){
User loginUser = userService.login(user);
if (loginUser != null){
session.setAttribute("loginUser",loginUser);
return "redirect:/account/selectAccount";
}
return "redirect:/index.jsp";
}
}
1.15.converter
public class DateConverter implements Converter<String, Date> {
@Override
public Date convert(String source) {
try {
DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
return format.parse(source);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
1.16.interceptor
public class LoginHandlerInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
User user = (User) request.getSession().getAttribute("loginUser");
if (user != null){
return true;
}
response.sendRedirect("/");
return false;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
}
}
1.17.jsp
1.17.1 select_account.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<html>
<head>
<title>Titletitle>
head>
<body>
<h2>查询所有账户h2>
欢迎${sessionScope.loginUser.username}
<a href="/account/toAddAccount">新增a>
<table width="50%" border="1" cellspacing="0" cellpadding="0">
<tr>
<th>idth>
<th>nameth>
<th>moneyth>
<th>dateth>
<th>headth>
<th>操作th>
tr>
<c:forEach var="list" items="${list}">
<tr>
<td>${list.id}td>
<td>${list.name}td>
<td>${list.money}td>
<td><fmt:formatDate value="${list.date}" pattern="yyyy-MM-dd">fmt:formatDate>td>
<td><img src="/head/${list.head}" height="40px" width="50px">td>
<td>
<a href="/account/toUpdateAccount?id=${list.id}">修改a>
<a href="/account/toDeleteAccount?id=${list.id}">删除a>
td>
tr>
c:forEach>
table>
body>
html>
1.17.2 add_account.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Titletitle>
head>
<body>
<h2>新增账户h2>
<%-- enctype="multipart/form-data"--%>
<form action="/account/addAccount" method="post" enctype="multipart/form-data">
账号:<input type="text" name="name"><br>
金额:<input type="text" name="money"><br>
日期:<input type="text" name="date"><br>
头像:<input type="file" name="img"><br>
<input type="submit" value=" 保 存 ">
form>
body>
html>
1.17.3 update_account.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<html>
<head>
<title>Titletitle>
head>
<body>
<h2>修改账户h2>
<%-- enctype="multipart/form-data"--%>
<form action="/account/updateAccount" method="post" enctype="multipart/form-data">
<input type="hidden" name="id" value="${account.id}">
账号:<input type="text" name="name" value="${account.name}"><br>
金额:<input type="text" name="money" value="${account.money}"><br>
日期:<input type="text" name="date" value=""><br>
头像:<input type="file" name="img"><br>
<img src="/head/${account.head}" width="80px" height="50px"><br>
<input type="submit" value=" 修 改 ">
form>
body>
html>
1.17.4 register.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Titletitle>
head>
<body>
<h2>注册h2>
<form action="/user/addUser" method="post">
账户:<input type="text" name="username"><br>
密码:<input type="text" name="password"><br>
<input type="submit" value="注 册">
form>
body>
html>
1.17.5 index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>$Title$title>
head>
<body>
<h2>登录h2>
<form action="/user/login" method="post">
账户:<input type="text" name="username"><br>
密码:<input type="text" name="password"><br>
没有账号?点击<a href="/user/register">这里a>注册账号!
<input type="submit" value="登 录">
form>
body>
html>
1.18.测试
1.18.1 增删改查
1.18.2 登录注册