Spring练习

环境搭建

在这里插入图片描述

web.xml

<?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">
  
  <!--全局的初始化参数-->
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:applicationContext.xml</param-value>
  </context-param>
  
  <!--Spring的监听器-->
  <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:spring-mvc.xml</param-value>
    </init-param>
    <load-on-startup>2</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>DispatcherServlet</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
  
</web-app>

spring-mvc.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       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
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">


    <!--注解驱动-->
    <mvc:annotation-driven/>

    <!--配置视图解析器-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/pages/"/>
        <property name="suffix" value=".jsp"/>
    </bean>

    <!--静态资源访问开放-->
    <mvc:default-servlet-handler/>
</beans>

applicationContext.xml:

<?xml version="1.0" encoding="UTF-8"?>
<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"
       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
">

    <!--加载jdbc配置文件-->
    <context:property-placeholder location="classpath:jdbc.properties"/>
    <!--配置数据源-->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="${jdbc.driver}"/>
        <property name="jdbcUrl" value="${jdbc.url}"/>
        <property name="user" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
    </bean>
    
    <!--配置jdbcTemplate对象-->
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dataSource"/>
    </bean>
    
</beans>

角色列表的展示

在这里插入图片描述

dao层

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 sys_role", new BeanPropertyRowMapper<Role>(Role.class));
        return roleList;
    }
}

service层

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;
    }
}

controller层

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("/list")
    public ModelAndView list()
    {
        ModelAndView modelAndView=new ModelAndView();
        List<Role> roleList=roleService.list();
        modelAndView.addObject("roleList",roleList);
        modelAndView.setViewName("role-list");
        return modelAndView;
    }
}


开启组件扫描:

<!--组件扫描-->
    <context:component-scan base-package="com.itheima.controller"/>

配置bean

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

页面展示

引jstl标签

<%@ 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="#" class="btn bg-olive btn-xs">删除</a>
											</td>
										</tr>
									</c:forEach>
								</tbody>

角色添加

在这里插入图片描述

乱码过滤器

<!--乱码过滤器-->
  <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>

dao

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

    }

service

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

controller

 @RequestMapping("/save")
    public String save(Role role)
    {
        roleService.save(role);

        return "redirect:/role/list";
    }

用户列表展示

和角色列表展示步骤基本相同,唯一的不同之处在于该查询涉及到多表查询。

service

package com.itheima.service.impl;

import com.itheima.dao.RoleDao;
import com.itheima.dao.UserDao;
import com.itheima.domain.Role;
import com.itheima.domain.User;
import com.itheima.service.UserService;

import java.util.List;

public class UserServiceImpl implements UserService {

    private UserDao userDao;
    private RoleDao roleDao;

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

    public UserDao getUserDao() {
        return userDao;
    }

    public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
    }

    public List<User> list() {
        List<User> userList=userDao.findAll();
        //封装user中的roles
        for (User user : userList) {
            Long id = user.getId();
            //将id作为参数查询当前user的roles
            List<Role> roles=roleDao.findRolesByUserId(id);
            user.setRoles(roles);
        }
        return userList;
    }
}

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

    }

表格展示

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

用户添加

动态展示角色

<div class="col-md-2 title">用户角色</div>
						<div class="col-md-10 data">
							<c:forEach items="${roleList}" var="role">
								<input class="" type="checkbox" name="roleIds" value="${role.id}">${role.roleName}
							</c:forEach>
						</div>

返回数据库自动生成的主键

controller

@RequestMapping("/saveUI")
    public ModelAndView saveUI()
    {
        ModelAndView modelAndView=new ModelAndView();
        List<Role> roles = roleService.list();
        modelAndView.addObject("roleList",roles);
        modelAndView.setViewName("user-add");

        return modelAndView;
    }

    @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) {
        Long userId = userDao.save(user);
        userDao.saveUserRole(userId,roleIds);
    }

dao

 public Long save(final User user) {

        //创建prepareStatementCreator对象
        PreparedStatementCreator preparedStatementCreator=new PreparedStatementCreator() {
            public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
                PreparedStatement preparedStatement = connection.prepareStatement(
                        "insert into sys_user values(?,?,?,?,?)", PreparedStatement.RETURN_GENERATED_KEYS);
                preparedStatement.setObject(1,null);
                preparedStatement.setObject(2,user.getUsername());
                preparedStatement.setObject(3,user.getEmail());
                preparedStatement.setObject(4,user.getPassword());
                preparedStatement.setObject(5,user.getPhoneNum());

                return preparedStatement;
            }
        };
        //创建keyHolder
        GeneratedKeyHolder keyHolder=new GeneratedKeyHolder();

        jdbcTemplate.update(preparedStatementCreator,keyHolder);
        //获得生成的主键
        long userId = keyHolder.getKey().longValue();


        return userId;
    }

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

    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值