SSM学习笔记6 Spring练习

 

controller是web层 domain是实体层 utils 是工具包

配置文件applicationcontext.xml配置Bean,加载jdbc.properties,配置数据源对象,配置JdbcTemplate、spring-mvc.xml配置注解驱动,内部资源视图解析器、配置静态资源访问、jdbc.properties抽取jdbc数据库连接信息的、log4j.properties配置日志文件、web.xml配置解决乱码的过滤器,全局的初始化参数,Spring监听器,SpringMVC前端控制器

SpringMVC流程

1、 用户发送请求至前端控制器DispatcherServlet;

2、DispatcherServlet收到请求调用HandlerMapping处理器映射器;

3、处理器映射器根据请求url找到具体的处理器,生成处理器对象及处理器拦截器(如果有则生成)一并返回给DispatcherServlet;

4、DispatcherServlet通过HandlerAdapter处理器适配器调用处理器,执行处理器(Controller,也叫后端控制器);

5、Controller执行完成返回ModelAndView,并返回给HandlerAdapter,HandlerAdapter将结果返回给DispatcherServlet;

6、DispatcherServlet将ModelAndView传给ViewReslover视图解析器,ViewReslover解析后返回具体View给DispatcherServlet;

 7、DispatcherServlet对View进行渲染视图(即将模型数据填充至视图中)后返回给给客户
 

 

点击角色管理菜单发送请求到服务器端(修改角色管理菜单的ur地址)

在aside.jsp中

<li><a
	<%--点击角色管理会跳转到role/list--%>
    <%--下一步创建 RoleController和 showList()方法--%>
	href="${pageContext.request.contextPath}/role/list"> <i
	class="fa fa-circle-o"></i> 角色管理
</a></li>

创建 RoleController和 showList()方法

package com.itheima.controller;

import com.itheima.domain.Role;
import com.itheima.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

@RequestMapping("/role")//总领
@Controller
public class RoleController {

    @Autowired
    private RoleService roleService;

    @RequestMapping("/save")
    public String save(Role role){
        roleService.save(role);
        return "redirect:/role/list";
    }

    @RequestMapping("/list")
    public ModelAndView list(){
        ModelAndView modelAndView = new ModelAndView();
        List<Role> roleList = roleService.list();
        //设置模型
        modelAndView.addObject("roleList",roleList);
        //设置视图
        modelAndView.setViewName("role-list");
        //下一步创建Roleservice和 showiest()方法
        System.out.println(roleList);
        return modelAndView;
    }

}


创建 RoleService和 showList()方法(代码解耦合:分为接口和RoleService)

package com.itheima.service;

import com.itheima.domain.Role;

import java.util.List;

public interface RoleService {
    public List<Role> list() ;

    void save(Role role);
}
package com.itheima.service.impl;

import com.itheima.dao.RoleDao;
import com.itheima.domain.Role;
import com.itheima.service.RoleService;

import java.util.List;

public class RoleServiceImpl implements RoleService {

    private RoleDao roleDao;
    public void setRoleDao(RoleDao roleDao) {
        this.roleDao = roleDao;
    }

    public List<Role> list() {
        List<Role> roleList = roleDao.findAll();
        return roleList;
    }

    public void save(Role role) {
        roleDao.save(role);
    }
}


创建 RoleDao和 findAll()方法(代码解耦合:分为接口和RoleDao)

使用 JdbcTemplate完成查询操作

将查询数据存储到 Modell中

package com.itheima.dao;

import com.itheima.domain.Role;

import java.util.List;

public interface RoleDao {
    List<Role> findAll();

    void save(Role role);

    List<Role> findRoleByUserId(Long id);
}
package com.itheima.dao.impl;

import com.itheima.dao.RoleDao;
import com.itheima.domain.Role;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.List;

public class RoleDaoImpl implements RoleDao {

    private JdbcTemplate jdbcTemplate;
    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    public List<Role> findAll() {
        List<Role> roleList = jdbcTemplate.query("select * from test.sys_role", new BeanPropertyRowMapper<Role>(Role.class));
        return roleList;
    }

    public void save(Role role) {
        jdbcTemplate.update("insert into test.sys_role values(?,?,?)",null,role.getRoleName(),role.getRoleDesc());
    }

    public List<Role> findRoleByUserId(Long id) {
        List<Role> roles = jdbcTemplate.query("select * from test.sys_user_role ur,test.sys_role r where ur.roleId=r.id and ur.userId=?", new BeanPropertyRowMapper<Role>(Role.class), id);
        return roles;
    }
}

三层代码写完后,需要将web层(controller) 业务层(service) dao层(dao)都放到Spring容器当中——在spring.mvc中添加组件扫描器——剩下的不需要扫描,直接在applicationContext.xml中配置即可

    <!--4、组件扫描  扫描Controller-->
    <context:component-scan base-package="com.itheima.controller"/>
    <!--配置RoleService-->
    <bean id="roleService" class="com.itheima.service.impl.RoleServiceImpl">
        <property name="roleDao" ref="roleDao"/>
    </bean>

    <!--配置RoleDao-->
    <bean id="roleDao" class="com.itheima.dao.impl.RoleDaoImpl">
        <property name="jdbcTemplate" ref="jdbcTemplate"/>
    </bean>


转发到 role-list. jsp页面进行展示

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>


<tbody>
	<c:forEach items="${roleList}" var="role">
		<tr>
			<td><input name="ids" type="checkbox"></td>
			<td>${role.id}</td>
			<td>${role.roleName}</td>
			<td>${role.roleDesc}</td>
			<td class="text-center">
				<a href="javascript:void(0);" class="btn bg-olive btn-xs">删除</a>
			</td>
	   </tr>
	</c:forEach>
</tbody>

 

用户列表(数据库链表关系展示)

在业务层实现

读取:

    public List<User> list() {
        List<User> userList = userDao.findAll();
        //封装userList中的每一个User的roles数据
        for (User user : userList) {
            //获得user的id
            Long id = user.getId();
            //将id作为参数 查询当前userId对应的Role集合数据
            //使用roleDao,在RoleDao中编写数据库操作函数并调用(代码解耦思想)
            List<Role> roles = roleDao.findRoleByUserId(id);
            user.setRoles(roles);
        }
        return userList;
    }
    public List<Role> findRoleByUserId(Long id) {
        List<Role> roles = jdbcTemplate.query("select * from test.sys_user_role ur,test.sys_role r where ur.roleId=r.id and ur.userId=?", new BeanPropertyRowMapper<Role>(Role.class), id);
        return roles;
    }

新建(一个对象对应多个 id.用数组进行接收)

难点:要自动返回新建的当前保存用户的id,该id是数据库自动生成的

controller

    @RequestMapping("/save")
    public String save(User user,Long[] roleIds){
        userService.save(user,roleIds);
        return "redirect:/user/list";
    }

service

    public void save(User user, Long[] roleIds) {
        //第一步 向sys_user表中存储数据
        Long userId = userDao.save(user);
        //第二步 向sys_user_role 关系表中存储多条数据
        userDao.saveUserRoleRel(userId,roleIds);
    }

dao

    public Long save(final User user) {
        //创建PreparedStatementCreator
        PreparedStatementCreator creator = new PreparedStatementCreator() {
            public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
                //使用原始jdbc完成有个PreparedStatement的组建
                PreparedStatement preparedStatement = connection.prepareStatement("insert into test.sys_user values(?,?,?,?,?)", PreparedStatement.RETURN_GENERATED_KEYS);
                preparedStatement.setObject(1,null);
                preparedStatement.setString(2,user.getUsername());
                preparedStatement.setString(3,user.getEmail());
                preparedStatement.setString(4,user.getPassword());
                preparedStatement.setString(5,user.getPhoneNum());
                return preparedStatement;
            }
        };
        //创建keyHolder
        GeneratedKeyHolder keyHolder = new GeneratedKeyHolder();
        jdbcTemplate.update(creator,keyHolder);
        //获得生成的主键
        long userId = keyHolder.getKey().longValue();
        return userId; //返回当前保存用户的id 该id是数据库自动生成的
    }

    public void saveUserRoleRel(Long userId, Long[] roleIds) {
        for (Long roleId : roleIds) {
            jdbcTemplate.update("insert into test.sys_user_role values(?,?)",userId,roleId);
        }
    }

删除(要把这个用户的id传到后台,要删两张表,先删sys_user_role和后删sys_user,有顺序)

controller

    @RequestMapping("/del/{userId}")
    public String del(@PathVariable("userId") Long userId){
        userService.del(userId);
        return "redirect:/user/list";
    }
    public void del(Long userId) {
        //1、删除sys_user_role关系表
        userDao.delUserRoleRel(userId);
        //2、删除sys_user表
        userDao.del(userId);
    }
    public void delUserRoleRel(Long userId) {
        jdbcTemplate.update("delete from test.sys_user_role where userId=?",userId);
    }

    public void del(Long userId) {
        jdbcTemplate.update("delete from test.sys_user where id=?",userId);
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值