大致的把ssm基础知识都过了一遍,那么就来做一个ssm整合的小项目吧,练练手!
因为是练整合的流程,所以业务就是基础的CRUD啦。
一个用户管理系统,管理员可以对用户账号进行增删改查(你没听错,就这么简单!!!!)
打开idea,左上角选择file–>new–>project,选择maven,然后点击next
这里设定自己的项目名和groupid,然后finish即可。
在pom.xml中导入我们需要用的依赖和maven的静态资源过滤:
<dependencies>
<dependency>
<groupId>junitgroupId>
<artifactId>junitartifactId>
<version>4.13.2version>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>8.0.30version>
dependency>
<dependency>
<groupId>com.mchangegroupId>
<artifactId>c3p0artifactId>
<version>0.9.5.5version>
dependency>
<dependency>
<groupId>javax.servletgroupId>
<artifactId>servlet-apiartifactId>
<version>2.5version>
dependency>
<dependency>
<groupId>javax.servlet.jspgroupId>
<artifactId>jsp-apiartifactId>
<version>2.2version>
dependency>
<dependency>
<groupId>javax.servletgroupId>
<artifactId>jstlartifactId>
<version>1.2version>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatisartifactId>
<version>3.5.11version>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatis-springartifactId>
<version>3.0.0version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-webmvcartifactId>
<version>5.1.9.RELEASEversion>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-jdbcartifactId>
<version>5.1.9.RELEASEversion>
dependency>
<dependency>
<groupId>org.projectlombokgroupId>
<artifactId>lombokartifactId>
<version>1.16.10version>
<scope>providedscope>
dependency>
dependencies>
<build>
<resources>
<resource>
<directory>src/main/javadirectory>
<includes>
<include>**/*.propertiesinclude>
<include>**/*.xmlinclude>
includes>
<filtering>falsefiltering>
resource>
<resource>
<directory>src/main/resourcesdirectory>
<includes>
<include>**/*.propertiesinclude>
<include>**/*.xmlinclude>
includes>
<filtering>falsefiltering>
resource>
resources>
build>
导入后,记得更新依赖包
点击项目文件夹,然后右键选择 add framework support,来添加web支持
在idea的右上角的位置:
点击 edit configurations然后配置tomcat
然后会弹出下面这样的界面,点击加号,找到local tomcat
这里我使用的是tomcat9,然后端口号和tomcat名可以自行修改
选择 deployment,添加artfacts
点击左上角 file ,然后选择project structure,弹出窗口后选择artifacts,然后找到自己当前项目的artifacts,在其根目录下新建一个lib文件夹,然后右键选择add of…library files 将项目中的依赖全部放入lib文件夹,然后ok即可
初始数据添加:
新建一个包 com/gothic/sunset/pojo 然后新建User.java实体类
package com.gothic.sunset.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor //有参构造
@NoArgsConstructor //无参构造
public class User {
private int id; //id号
private String userName;//用户名
private String password;//密码
}
这里我使用了lombok,来自动注入,避免手写有参无参构造以及对应的getter和setter…
<dependency>
<groupId>org.projectlombokgroupId>
<artifactId>lombokartifactId>
<version>1.16.10version>
<scope>providedscope>
dependency>
@Data:该注解定义在JavaBean上,给JavaBean产生getter(),setter(),无参构造器,tostring(),hashcode(),equals()
@NoArgsConstructor:产生无参构造器
@Getter:产生getter()
@Setter:产生setter()
@ToString:产生toString()
@RequiredArgsConstructor + @NonNull:可以用来定义有参构造器
@AllArgsConstructor:产生全属性的有参构造
在com/gothic/sunset/dao 下新建UserMapper.java 接口
package com.gothic.sunset.dao;
import com.gothic.sunset.pojo.User;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Repository;
import java.util.List;
public interface UserMapper {
//添加用户
public int addUser(User user);
//删除用户 根据id
public int delUser(@Param("id") int id);
//更新用户信息 根据id
public int updateUser(User user);
//查询单个用户 根据id查
public User findUserById(@Param("id") int id);
//查询所有用户信息
public List<User> selectAllUser();
//根据用户名查询用户
public List<User> findUserByName(@Param("userName") String userName);
}
在resources 目录下,新建 com/gothic/sunset/dao 目录,然后在这个包下新建UserMapper.xml映射文件
DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.gothic.sunset.dao.UserMapper">
<insert id="addUser" parameterType="User">
insert into
(id,userName,password)
values(#{userName},#{password})
insert>
<delete id="delUser" parameterType="int">
delete from user where id = #{id}
delete>
<update id="updateUser" parameterType="User">
update user
set userName = #{userName},
password =#{password}
where id =#{id}
update>
<select id="findUserById" resultType="User">
select id,userName,password from user where id = #{id}
select>
<select id="selectAllUser" resultType="User">
select
id,userName,password
from user
select>
<select id="findUserByName" resultType="User">
select
id,userName,password
from user
where userName = #{userName}
select>
mapper>
在resources目录下,新建mybatis-config.xml文件
DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<settings>
<setting name="mapUnderscoreToCamelCase" value="true"/>
settings>
<typeAliases>
<package name="com.gothic.sunset.pojo"/>
typeAliases>
<mappers>
<package name="com/gothic/sunset/dao/UserMapper.xml"/>
mappers>
configuration>
在resources 目录下,新建jdbc.properties文件,用于存放数据库连接用户名密码验证…
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis?characterEncoding=UTF-8
jdbc.username=root
jdbc.password=root
在resources目录下,新建spring-dao.xml配置文件
<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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">
<context:property-placeholder location="classpath:jdbc.properties"/>
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" >
<property name="jdbcUrl" value="${jdbc.url}"/>
<property name="driverClass" value="${jdbc.driver}"/>
<property name="user" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="configLocation" value="classpath:mybatis-config.xml"/>
bean>
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
<property name="basePackage" value="com.gothic.sunset.dao"/>
bean>
beans>
这里如果sqlSessionFactory注入数据库连接池,中写成了value=“dataSource” 这样的话,就会出现一个异常
org.springframework.beans.ConversionNotSupportedException: Failed to convert property value of type 'java.lang.String' to required type 'javax.sql.DataSource' for property 'dataSource'
.
新建包 com/gothic/sunset/service 在这个包里新建UserService.java接口
package com.gothic.sunset.service;
import com.gothic.sunset.pojo.User;
import java.util.List;
public interface UserService {
//添加用户
public int addUser(User user);
//删除用户 根据id
public int delUser( int id);
//更新用户信息 根据id
public int updateUser(User user);
//查询单个用户 根据id查
public User findUserById(int id);
//查询所有用户信息
public List<User> selectAllUser();
//根据用户名查询用户
public List<User> findUserByName( String userName);
}
与UserService.java接口在同一目录下,新建UserServiceImpl.java接口实现类
package com.gothic.sunset.service;
import com.gothic.sunset.dao.UserMapper;
import com.gothic.sunset.pojo.User;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class UserServiceImpl implements UserService{
private UserMapper userMapper;
public void setUserMapper(UserMapper userMapper) {
this.userMapper = userMapper;
}
@Override
public int addUser(User user) {
return userMapper.addUser(user);
}
@Override
public int delUser(int id) {
return userMapper.delUser(id);
}
@Override
public int updateUser(User user) {
return userMapper.updateUser(user);
}
@Override
public User findUserById(int id) {
return userMapper.findUserById(id);
}
@Override
public List<User> selectAllUser() {
return userMapper.selectAllUser();
}
@Override
public List<User> findUserByName(String userName) {
return userMapper.findUserByName(userName);
}
}
这里需要说明的是,可以使用自动装配bean结合注解@AutuWired的方式去做,我这里(刚回忆整合)就先用手动settter注入的方式。
<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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="com.gothic.sunset.service"/>
<bean id="userServiceImpl" class="com.gothic.sunset.service.UserServiceImpl">
<property name="userMapper" ref="userMapper"/>
bean>
<bean class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
bean>
beans>
然后这里的话,事务横切aop,这个小例子还没使用,so…就没有配置,也没有导入aspectj这个依赖包。
在 com/gothic/sunset/controller包下,新建UserController.java类
package com.gothic.sunset.controller;
import com.gothic.sunset.pojo.User;
import com.gothic.sunset.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.List;
@Controller
@RequestMapping("/user")
public class UserController {
// controller层调用service层,service层调用dao层 mvc架构,我就不多说了
//@Qualifier注解 别名
@Autowired
@Qualifier("userServiceImpl")
private UserService userService;
@RequestMapping("/allUser")
public String selectAllUser(Model model){
//使用业务层调用dao层查询出数据,通过model对象渲染到前台页面
List<User> userList = userService.selectAllUser();
model.addAttribute(userList);
return "allUser";
}
//添加书籍,首先需要跳转到添加用户的表单页面
@RequestMapping("/toAddUser")
public String toAddUser(){
//接收到前端请求后,跳到添加用户表单页面
return "addUser";
}
//接收添加用户表单的数据,进行正式的添加用户,添加完成后,重定向到所有用户页面
@RequestMapping("addUser")
public String addUser(User user){
userService.addUser(user);
System.out.println(user.toString());
return "redirect:/user/allUser";
}
//更新用户,与添加用户流程基本一样
@RequestMapping("toUpdateUser")
public String toUpdateUser(Model model,int id){
User user = userService.findUserById(id);
model.addAttribute("user",user);
//跳转到用户修改页面,同时将要修改的用户的信息传递过去
return "updateUser";
}
//正式更新用户
@RequestMapping("updateUser")
public String updateUser(User user){
System.out.println(user.toString());
userService.updateUser(user);
System.out.println(user.getId());
return "redirect:/user/allUser";
}
//删除就直接删除用户即可
@RequestMapping("delUser")
public String delUser(int id){
userService.delUser(id);
return "redirect:/user/allUser";
}
//查询用户 根据用户名查询
@RequestMapping("/queryUser")
public String queryUser(String userName,Model model){
List<User> userList = userService.findUserByName(userName);
model.addAttribute(userList);
return "allUser";
}
}
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
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/mvc http://www.springframework.org/schema/cache/spring-mvc.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="com.gothic.sunset.controller"/>
<mvc:annotation-driven/>
<mvc:default-servlet-handler/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="internalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
bean>
beans>
将三个spring配置文件,都引入到一个新建的applicationContext.xml(Resources目录下新建)中。
<beans xmlns="http://www.springframework.org/schema/beans"
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.xsd">
<import resource="classpath:spring-dao.xml"/>
<import resource="classpath:spring-service.xml"/>
<import resource="classpath:spring-mvc.xml"/>
beans>
<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">
<servlet>
<servlet-name>DispatcherServletservlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
<init-param>
<param-name>contextConfigLocationparam-name>
<param-value>classpath:applicationContext.xmlparam-value>
init-param>
<load-on-startup>1load-on-startup>
servlet>
<servlet-mapping>
<servlet-name>DispatcherServletservlet-name>
<url-pattern>/url-pattern>
servlet-mapping>
<filter>
<filter-name>encodingFilterfilter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
<init-param>
<param-name>encodingparam-name>
<param-value>utf-8param-value>
init-param>
filter>
<filter-mapping>
<filter-name>encodingFilterfilter-name>
<url-pattern>/*url-pattern>
filter-mapping>
<session-config>
<session-timeout>15session-timeout>
session-config>
web-app>
这里需要注意的是,前端控制器里面,最终绑定的是整合总的配置文件applicationContext.xml,别配错了,否则就会告诉你找不到某些bean,其实配错了也能根据提示来修改。
index.jsp页面
<%--
Created by IntelliJ IDEA.
User: gothi
Date: 2022/12/3
Time: 10:28
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>首页title>
<style type="text/css">
a {
text-decoration: none;
color: black;
font-size: 18px;
}
h3 {
width: 180px;
height: 38px;
margin: 100px auto;
text-align: center;
line-height: 38px;
background: deepskyblue;
border-radius: 4px;
}
style>
head>
<body>
<h3><a href="${pageContext.request.contextPath}/user/allUser">点击进入a>h3>
body>
html>
在/WEB-INF/jsp/目录下新建jsp页面
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%--
Created by IntelliJ IDEA.
User: gothi
Date: 2022/12/3
Time: 15:25
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>查询所有用户title>
<link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
head>
<body>
<div class="container">
<div class="row clearfix">
<div class="col-md-12 column">
<div class="page-header">
<h1>
<small>用户列表 —— 显示所有用户small>
h1>
div>
div>
div>
<div class="row">
<div class="col-md-4 column">
<a class="btn btn-primary" href="${pageContext.request.contextPath}/user/toAddUser">新增a>
div>
<div class="col-md-4 column">
<a class="btn btn-primary" href="${pageContext.request.contextPath}/user/allUser">显示所有用户a>
div>
<div class="col-md-4 column">
<form class="form-inline" action="${pageContext.request.contextPath}/user/queryUser" method="post" style="float: right">
<input type="text" name="userName" class="form-control" placeholder="输入用户名" required>
<input type="submit" value="查询" class="btn btn-primary">
form>
div>
div>
<div class="row clearfix">
<div class="col-md-12 column">
<table class="table table-hover table-striped">
<thead>
<tr>
<th>用户idth>
<th>用户名th>
<th>密码th>
<th>操作th>
tr>
thead>
<tbody>
<c:forEach var="user" items="${requestScope.get('userList')}">
<tr>
<td>${user.id}td>
<td>${user.userName}td>
<td>${user.password}td>
<td>
<a href="${pageContext.request.contextPath}/user/toUpdateUser?id=${user.getId()}">更改a> |
<a href="${pageContext.request.contextPath}/user/delUser/?id=${user.getId()}">删除a>
td>
tr>
c:forEach>
tbody>
table>
div>
div>
div>
body>
html>
addUser.jsp
<%--
Created by IntelliJ IDEA.
User: gothi
Date: 2022/12/3
Time: 19:10
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>用户添加title>
<link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
head>
<body>
<div class="container">
<div class="row clearfix">
<div class="col-md-12 column">
<div class="page-header">
<h1>
<small>用户添加small>
h1>
div>
div>
div>
<form action="${pageContext.request.contextPath}/user/addUser" method="post">
用户名:<input type="text" name="userName"><br><br><br>
密 码:<input type="text" name="password"><br><br><br>
<input type="submit" value="添加">
form>
div>
body>
html>
updateUser.jsp
<%--
Created by IntelliJ IDEA.
User: gothi
Date: 2022/12/3
Time: 19:14
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>用户更新title>
<link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
head>
<body>
<div class="container">
<div class="row clearfix">
<div class="col-md-12 column">
<div class="page-header">
<h1>
<small>修改用户信息small>
h1>
div>
div>
div>
<form action="${pageContext.request.contextPath}/user/updateUser" method="post">
<input type="hidden" name="id" value="${user.id}"/>
用户名:<input type="text" name="userName" value="${user.userName}"/>
密 码:<input type="text" name="password" value="${user.password}"/>
<input type="submit" value="提交"/>
form>
div>
body>
html>
首页:
用户列表页:
添加用户页面:
点击添加后:
这里是因为主键自增的,之前测试了一些数据,所以会显示id号为10.
修改用户页面:
修改测试:
根据用户名查询:
这里相同的用户名,会查出多条用户数据,因为我这里只有一条名为大漠孤烟的用户名的数据,所以只显示一条。
ssm果然配置真繁琐,不过如果一层一层来的话,也不算太复杂,多练习!经过大致10多天的时间,二刷结束,接下来就是做一些ssm的练手项目,熟悉一下流程了。
然后,因为时间匆忙写的略微有点简单,而且前台比较丑,等过段时间,做一个真正的ssm项目,并且做完以后准备学习springboot,和redis…最后再把前台的相关技术也认真学学!!!!