ssm目录
流程:
前端发送请求由浏览器发送到tomcat,交给dispatcherServlet;dispatcherServlet调用controller,controller调用service,service调用dao,dao与数据交互。
案例:使用ssm框架实现登录功能(前后端完全分离)
Ⅰ、配置配置文件
👆一、web.xml
放在src\main\resources下面
<?xml version="1.0" encoding="UTF-8"?>
<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">
<!--前端发送请求由浏览器发送到tomcat,交给dispatcherServlet;dispatcherServlet调用controller,controller调用service,service调用dao。不过现在这些实例都没有,所以需要初始化-->
<!--想要在加载tomcat初始化dispatcherServlet时就实例上述对象,如何完成???-->
<!--使用tomcat提供地监听器ServletContextListener(这个监听器监听servletContext,而启动tomcat就自动创建一个servletContext(内置对象,随着tomcat的启动而创建,关闭而销毁))-->
<!--初始化核心处理器dispatcherServlet-->
<servlet>
<servlet-name>ssm1109</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springMVC.xml</param-value>
</init-param>
<!--默认是第一次访问tomcat时创建。但是当值大于0时,启动tomcat时创建-->
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>ssm1109</servlet-name>
<!--不要拦截所有,jsp交给jspservlet处理-->
<url-pattern>/</url-pattern>
</servlet-mapping>
<!--初始化上下文-->
<listener>
<!--ContextLoaderListener extends ContextLoader implements ServletContextListener(Tomcat提供的)-->
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<!--实际完成实例的,肯定是spring的配置文件或者使用注解啦-->
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<!--过滤器,统一编码编码-->
<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>
</web-app>
👆二、spring配置文件applicationContext.xml
放在src\main\resources下面
<?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:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
https://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">
<!--扫描指定包的注解-->
<context:component-scan base-package="com.hbw">
<!--com.hbw包下面除了controller注解-->
<!--为什么要除了controller注解???因为配置springMVC时也会扫描该注解。springMVC的容器,是spring容器的子容器-->
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
<!--spring整合mybatis-->
<!--引入属性配置文件(db.properties)-->
<context:property-placeholder location="classpath:db.properties"></context:property-placeholder>
<bean id="dataSources" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="${db.driver}"></property>
<property name="url" value="${db.url}"></property>
<property name="username" value="${db.username}"></property>
<property name="password" value="${db.password}"></property>
</bean>
<!--sqlsessionFactory与数据库交互-->
<bean id="sqlSessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSources"></property>
<property name="configLocation" value="classpath:mybatisConfig.xml"></property>
<property name="mapperLocations" value="classpath:mapper/*.xml"></property>
<property name="typeAliasesPackage" value="com.hbw.bean"></property>
</bean>
<!--基于接口代理对象实现交互-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!--引入上面的sqlSessionFactoryBean为何使用的value?因为提醒的就是String啊。通过名字找到的-->
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactoryBean"></property>
<property name="basePackage" value="com.hbw.dao"></property>
</bean>
<!--事务-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!--事务肯定需要链接connection了-->
<property name="dataSource" ref="dataSources"></property>
</bean>
<!--事务生效-->
<tx:annotation-driven transaction-manager="transactionManager"></tx:annotation-driven>
</beans>
附件——db.propertis
db.driver=com.mysql.cj.jdbc.Driver
db.url=jdbc:mysql://localhost:3306/student?characterEncoding=utf-8&serverTimezone=UTC&useSSL=false
db.username=root
db.password=123456
👆三、springMVC.xml
放在src\main\resources下面
<?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:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
https://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">
<!--扫描controller注解-->
<context:component-scan base-package="com.hbw.controller">
<!--将排除的注解,加回来-->
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
<!--初始化handlerMapping、handlerAdapter。json自动转换、controller请求转发-->
<!--viewReslover视图解析(前后端分离,使用ajax跳转页面,这里就不初始化了)-->
<mvc:annotation-driven></mvc:annotation-driven>
<!--开启静态资源加载-->
<mvc:default-servlet-handler></mvc:default-servlet-handler>
</beans>
👆四、mybatis主配置文件mybatisConfig.xml
放在src\main\resources下面
<?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>
</configuration>
👆五、mybatis映射配置文件Usersmapper.xml
Usersmapper.xml放在src\main\resources\mapper文件夹下面(上面配置文件夹是这么配置的,不然找不到(因为mapper一般比较多,所以放到文件夹中))
使用逆向工程自动生成 实体类bean、dao层接口mapper、映射配置文件mapper.xml
👉点击——https://blog.csdn.net/Today_He/article/details/109391392
自动生成的考虑比较全面,有点长
<?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.hbw.dao.UsersMapper">
<resultMap id="BaseResultMap" type="com.hbw.bean.Users">
<id column="uid" jdbcType="INTEGER" property="uid" />
<result column="uname" jdbcType="VARCHAR" property="uname" />
<result column="upwd" jdbcType="VARCHAR" property="upwd" />
</resultMap>
<sql id="Example_Where_Clause">
<where>
<foreach collection="oredCriteria" item="criteria" separator="or">
<if test="criteria.valid">
<trim prefix="(" prefixOverrides="and" suffix=")">
<foreach collection="criteria.criteria" item="criterion">
<choose>
<when test="criterion.noValue">
and ${criterion.condition}
</when>
<when test="criterion.singleValue">
and ${criterion.condition} #{criterion.value}
</when>
<when test="criterion.betweenValue">
and ${criterion.condition} #{criterion.value} and #{criterion.secondValue}
</when>
<when test="criterion.listValue">
and ${criterion.condition}
<foreach close=")" collection="criterion.value" item="listItem" open="(" separator=",">
#{listItem}
</foreach>
</when>
</choose>
</foreach>
</trim>
</if>
</foreach>
</where>
</sql>
<sql id="Update_By_Example_Where_Clause">
<where>
<foreach collection="example.oredCriteria" item="criteria" separator="or">
<if test="criteria.valid">
<trim prefix="(" prefixOverrides="and" suffix=")">
<foreach collection="criteria.criteria" item="criterion">
<choose>
<when test="criterion.noValue">
and ${criterion.condition}
</when>
<when test="criterion.singleValue">
and ${criterion.condition} #{criterion.value}
</when>
<when test="criterion.betweenValue">
and ${criterion.condition} #{criterion.value} and #{criterion.secondValue}
</when>
<when test="criterion.listValue">
and ${criterion.condition}
<foreach close=")" collection="criterion.value" item="listItem" open="(" separator=",">
#{listItem}
</foreach>
</when>
</choose>
</foreach>
</trim>
</if>
</foreach>
</where>
</sql>
<sql id="Base_Column_List">
uid, uname, upwd
</sql>
<select id="selectByExample" parameterType="com.hbw.bean.UsersExample" resultMap="BaseResultMap">
select
<if test="distinct">
distinct
</if>
<include refid="Base_Column_List" />
from users
<if test="_parameter != null">
<include refid="Example_Where_Clause" />
</if>
<if test="orderByClause != null">
order by ${orderByClause}
</if>
</select>
<select id="selectByPrimaryKey" parameterType="java.lang.Integer" resultMap="BaseResultMap">
select
<include refid="Base_Column_List" />
from users
where uid = #{uid,jdbcType=INTEGER}
</select>
<delete id="deleteByPrimaryKey" parameterType="java.lang.Integer">
delete from users
where uid = #{uid,jdbcType=INTEGER}
</delete>
<delete id="deleteByExample" parameterType="com.hbw.bean.UsersExample">
delete from users
<if test="_parameter != null">
<include refid="Example_Where_Clause" />
</if>
</delete>
<insert id="insert" parameterType="com.hbw.bean.Users">
insert into users (uid, uname, upwd
)
values (#{uid,jdbcType=INTEGER}, #{uname,jdbcType=VARCHAR}, #{upwd,jdbcType=VARCHAR}
)
</insert>
<insert id="insertSelective" parameterType="com.hbw.bean.Users">
insert into users
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="uid != null">
uid,
</if>
<if test="uname != null">
uname,
</if>
<if test="upwd != null">
upwd,
</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="uid != null">
#{uid,jdbcType=INTEGER},
</if>
<if test="uname != null">
#{uname,jdbcType=VARCHAR},
</if>
<if test="upwd != null">
#{upwd,jdbcType=VARCHAR},
</if>
</trim>
</insert>
<select id="countByExample" parameterType="com.hbw.bean.UsersExample" resultType="java.lang.Long">
select count(*) from users
<if test="_parameter != null">
<include refid="Example_Where_Clause" />
</if>
</select>
<update id="updateByExampleSelective" parameterType="map">
update users
<set>
<if test="record.uid != null">
uid = #{record.uid,jdbcType=INTEGER},
</if>
<if test="record.uname != null">
uname = #{record.uname,jdbcType=VARCHAR},
</if>
<if test="record.upwd != null">
upwd = #{record.upwd,jdbcType=VARCHAR},
</if>
</set>
<if test="_parameter != null">
<include refid="Update_By_Example_Where_Clause" />
</if>
</update>
<update id="updateByExample" parameterType="map">
update users
set uid = #{record.uid,jdbcType=INTEGER},
uname = #{record.uname,jdbcType=VARCHAR},
upwd = #{record.upwd,jdbcType=VARCHAR}
<if test="_parameter != null">
<include refid="Update_By_Example_Where_Clause" />
</if>
</update>
<update id="updateByPrimaryKeySelective" parameterType="com.hbw.bean.Users">
update users
<set>
<if test="uname != null">
uname = #{uname,jdbcType=VARCHAR},
</if>
<if test="upwd != null">
upwd = #{upwd,jdbcType=VARCHAR},
</if>
</set>
where uid = #{uid,jdbcType=INTEGER}
</update>
<update id="updateByPrimaryKey" parameterType="com.hbw.bean.Users">
update users
set uname = #{uname,jdbcType=VARCHAR},
upwd = #{upwd,jdbcType=VARCHAR}
where uid = #{uid,jdbcType=INTEGER}
</update>
</mapper>
Ⅱ、后端业务开发
👆一、结果集主工具类
用于接口实现是否有异常的判断
BaseResult .java
package com.hbw.util;
public class BaseResult {
/*用于判断接口实现是否有误*/
private boolean result;
private String message;
public boolean isResult() {
return result;
}
public void setResult(boolean result) {
this.result = result;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
@Override
public String toString() {
return "BaseResult{" +
"result=" + result +
", message='" + message + '\'' +
'}';
}
}
👆二、登录结果集辅工具类
用于登录成功与否的判断
UsersResult.java
package com.hbw.util;
import com.hbw.bean.Users;
public class UsersResult extends BaseResult {
private boolean usersResult;
private Users users;
public boolean isUsersResult() {
return usersResult;
}
public void setUsersResult(boolean usersResult) {
this.usersResult = usersResult;
}
public Users getUsers() {
return users;
}
public void setUsers(Users users) {
this.users = users;
}
@Override
public String toString() {
return "UsersResult{" +
"usersResult=" + usersResult +
", users=" + users +
'}';
}
}
👆三、service层实现类
UsersServiceImpl .java
package com.hbw.service;
import com.hbw.bean.Users;
import com.hbw.bean.UsersExample;
import com.hbw.dao.UsersMapper;
import com.hbw.util.UsersResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class UsersServiceImpl implements UsersService {
@Autowired
private UsersMapper usersMapper;
@Override
public UsersResult login(String uname, String upwd) {
UsersResult usersResult = new UsersResult();
try {
UsersExample usersExample = new UsersExample();
UsersExample.Criteria criteria = usersExample.createCriteria();
criteria.andUnameEqualTo(uname);
criteria.andUpwdEqualTo(upwd);
List<Users> list = usersMapper.selectByExample(usersExample);
if(list!=null && list.size()>0){//查到了对应用户信息。登录成功
usersResult.setUsersResult(true);
usersResult.setMessage("登录成功");
}else {
usersResult.setUsersResult(false);
usersResult.setMessage("账户或者密码错误,请重新登录");
}
usersResult.setResult(true);
}catch (Exception e){
e.printStackTrace();
usersResult.setResult(false);
usersResult.setMessage("登录失败,请稍后再试");
}
return usersResult;
}
}
👆四、controller层
StudentsController.java
package com.hbw.controller;
import com.hbw.service.UsersService;
import com.hbw.util.UsersResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
@RequestMapping("users")
public class StudentsController {
@Autowired
private UsersService usersService;
@RequestMapping("login")
@ResponseBody
public UsersResult login(String uname, String upwd){
return usersService.login(uname,upwd);
}
}
Ⅲ、前端代码
👉👆一、登录页面
需要的js、css去里面下载即可(下载的压缩包解压里面就包含js和所需的css了。copy到项目的webapp文件夹下面即可)——https://www.jeasyui.cn/
index.jsp
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>登录页面</title>
<link rel="stylesheet" type="text/css" href="/css/themes/default/easyui.css">
<link rel="stylesheet" type="text/css" href="/css/themes/icon.css">
<link rel="stylesheet" type="text/css" href="/css/demo/demo.css">
<script type="text/javascript" src="/js/jquery.min.js"></script>
<script type="text/javascript" src="/js/jquery.easyui.min.js"></script>
</head>
<body>
<div style="margin:20px 0;"></div>
<div class="easyui-panel" title="登录页面" style="width:400px">
<div style="padding:10px 60px 20px 60px">
<form id="ff" method="post">
<table cellpadding="5">
<tr>
<td>用户名:</td>
<td><input class="easyui-textbox" type="text" name="uname" data-options="required:true"></input></td>
</tr>
<tr>
<td>密码:</td>
<td><input class="easyui-textbox" type="password" name="upwd" data-options="required:true"></input></td>
</tr>
</table>
</form>
<div style="text-align:center;padding:5px">
<a href="javascript:void(0)" class="easyui-linkbutton" onclick="submitForm()">登录</a>
<a href="javascript:void(0)" class="easyui-linkbutton" onclick="clearForm()">取消</a>
</div>
</div>
</div>
<script>
function submitForm(){
$('#ff').form('submit', {
url:"/users/login",
success:function(data){
var obj = eval('('+data+')');
alert(obj.message);
if(obj.result){
if(obj.usersResult){
window.location.href="/success.html";
}else{
window.location.href ="/index.html";
}
}else{
window.location.href = "/index.html";
}
}
});
}
function clearForm(){
$('#ff').form('clear');
}
</script>
</body>
</html>
👆二、成功页面
success.jsp
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
登录成功
</body>
</html>