Day58 Java Web Framework phase - SSM framework exercise (user data background management, login interceptor)

Keywords: Spring xml JSP JDBC

SSM practice

Today's source code and materials:
Links: https://pan.baidu.com/s/19XDTuRre1A3JFlKhm2Aqbw
Extraction code: ls63

Demand:

  • 1. Role list display and add / delete operation
  • 2. User list display and add / delete operation
  • 3. Delete user and role operations
  • 4. User login operation
  • 5. Configure the login interceptor (you cannot view and change user information without login, which is off by default, please open it in spring-mvc.xml)

Effect display

01 spring exercise - Analysis of environment building steps (understanding)

Construction steps of case environment:

① Create project & module

② Import static page (see data jsp page)

③ Import requires coordinates (see pom.xml in the data)

④ Create package structure (controller, service, dao, domain, utils)

⑤ Import database script (see data test.sql)

⑥ Create POJO classes (see User.java and Role.java)

Create configuration file (applicationContext.xml,spring-mvc.xml,jdbc.properties,log4j.properties)

02 spring exercise environment building implementation 1 (application)

Create project, import jsp, add project dependency

Create package structure, import database script, import POJO

03 spring exercise environment building implementation 2 (application)

Create Spring's core configuration file applicationContext.xml

Create spring MVC core configuration file spring-mvc.xml

Create database configuration file jdbc.properties

Copy log configuration file log4j.properties

Configure web.xml as follows:

<!--Global initialization parameters-->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
    </context-param>
    <!--Spring Listener-->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <!--SpringMVC Front end controller for-->
    <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>

04 spring exercise environment building implementation 3 (application)

Configure springm-mvc.xml: annotation driven, view parser, static resource opening

The configuration is as follows:

<!--1,mvc Annotation driven-->
    <mvc:annotation-driven/>

    <!--2,Configure view resolver-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/pages/"/>
        <property name="suffix" value=".jsp"/>
    </bean>

    <!--3,Static resource permission opening-->
    <mvc:default-servlet-handler/>

05 spring exercise environment building implementation 4 (application)

Configure applicationContext.xml: load propertiest, configure data source object, and configure JdbcTemplate object

The configuration is as follows:

<?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: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 http://www.springframework.org/schema/context/spring-context.xsd
">
<!--1,Load jdbc.properties-->
    <context:property-placeholder location="classpath:jdbc.properties"/>

    <!--2,Configure data source objects-->
    <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>

    <!--3,To configure JdbcTemplate object-->
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dataSource"></property>
    </bean>
</beans>

06 spring exercise - Analysis of user table and role table (understanding)

Analyze the table relationship between users and roles in database design: many to many relationship, as shown in the figure:

07 spring exercise - role list display analysis (understanding)

Requirements: the role list is displayed, and the requirements are as shown in the figure:

The ideas and steps to complete the function are as follows:

① Click the role management menu to send the request to the server (modify the url address of the role management menu)

② Create RoleController and list() methods

③ Create RoleService and list() methods

④ Create RoleDao and findAll() methods

⑤ Using JdbcTemplate to complete the query operation

⑥ Store query data in modelAndView

⑦ Forward to role-list.jsp page for display

08 spring exercise - role list display - controller layer implementation (application)

1: Modify left menu link address

<ul class="treeview-menu">

					<li><a
						href="${pageContext.request.contextPath}/user/list"> <i
							class="fa fa-circle-o"></i> user management
					</a></li>
					<li><a
						href="${pageContext.request.contextPath}/role/list"> <i
							class="fa fa-circle-o"></i> Role management
					</a></li>
					<li><a
						href="${pageContext.request.contextPath}/pages/syslog-list.jsp"> <i
							class="fa fa-circle-o"></i> Access log
					</a></li>
				</ul>

Controller layer code:

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

    @Autowired
    private RoleService roleService;
    
    @RequestMapping("/list")
    public ModelAndView list(){
        ModelAndView modelAndView = new ModelAndView();
        List<Role> roleList = roleService.list();
        //Set up model
        modelAndView.addObject("roleList",roleList);
        //Set view
        modelAndView.setViewName("role-list");
        System.out.println(roleList);
        return modelAndView;
    }

}

09 spring exercise - role list presentation - service and dao layer implementation (application)

service layer code:

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

dao layer code:

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

10 spring exercise role list display configuration implementation (application)

Configure spring-mvc.xml

<!--4,Component scan Controller-->
    <context:component-scan base-package="com.itheima.controller"/>

Configure applicationContext.xml

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

11 spring exercise role list display page display (application)

Take out and display the data in role-list.jsp. The core code is as follows:

<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">delete</a>
	</td>
</tr>
</c:forEach>

12 spring exercise - adding roles (application)

Requirements: add roles, as shown in the following figure:

The operation steps are as follows:

① Click the new button on the list page to jump to the role adding page

② Input the role information, click the Save button, and submit the form data to the server

③ Write the save() method of RoleController

④ Write RoleService's save() method

⑤ Write RoleDao's save() method

⑥ Save Role data to sys Role using JdbcTemplate

⑦ Jump back to the role list page

The controller code is as follows:

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

The service code is as follows:

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

dao code is as follows:

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

In order to solve the problem of post submitting Chinese scrambling, we need to configure the global scrambling filter in web.xml

<!--Filter to solve the mess-->    
<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>

Test to complete the function.

13 spring exercise - user list display 1 (application)

Demand: query the user list. The demand chart is as follows:

To complete this function:

① Click the user management menu to send the request to the server (modify the url address of the user management menu)

② Create UserController and list() methods

③ Create UserService and list() methods

④ Create UserDao and findAll() methods

⑤ Using JdbcTemplate to complete the query operation

⑥ Store query data in modelAndView

⑦ Forward to user-list.jsp page for display

Just like the role list, query the user list, create the structure of UserController,UserService,UserDao,User entity, etc., write the code of each layer and configure

The user list Controller,service,dao layer codes are as follows:

controller

@RequestMapping("/list")
    public ModelAndView list(){
        List<User> userList = userService.list();
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("userList",userList);
        modelAndView.setViewName("user-list");
        return modelAndView;
    }

service:

public List<User> list() {
        List<User> userList = userDao.findAll();
        //Encapsulate the roles data of each User in the userList
        return userList;
    }

dao:

public List<User> findAll() {
        List<User> userList = jdbcTemplate.query("select * from sys_user", new BeanPropertyRowMapper<User>(User.class));
        return userList;
    }

14 spring exercise - user list display 2 (application)

When querying a user, all the role information of the user can be queried by association. The service layer code of the user needs to be improved

1. Add a method in the role's dao to query the role list according to the user id

//Querying the role information of user according to user id in role dao
 
public List<Role> findRoleByUserId(Long id) {
        List<Role> roles = 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);
        return roles;
    }

The perfect userservcie layer code is as follows:

//Associate query user's role in query user's service
public List<User> list() {
        List<User> userList = userDao.findAll();
        //Encapsulate the roles data of each User in the userList
        for (User user : userList) {
            //Get user's id
            Long id = user.getId();
            //Query the Role collection data corresponding to the current userId with id as a parameter
            List<Role> roles = roleDao.findRoleByUserId(id);
            user.setRoles(roles);
        }
        return userList;
    }

When querying a user, all the role information that the user has is associated and queried. The core code of the front-end jsp page

<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);" onclick="delUser('${user.id}')" class="btn bg-olive btn-xs">delete</a>
	</td>
</tr>
</c:forEach>

15 spring exercise user add action add page presentation (application)

Requirements: add users, and the requirements diagram is as follows:

When creating a new user, click the new button to go to the user-add.jsp page to add the user. You need to display the optional role information in the add user page, so you need to query all the role information and display it when you come to the add page

When going to the user-add.jsp page, first query the controller code of all role information

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

Because the code of the service layer and dao layer for querying all role information has been written in the previous role list display function, you only need to call,

Display the core code of all role information in the user-add.jsp page

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

16 spring exercise user add operation add data to database (application)

There are two parts of data in the add user page. One part of the basic user data needs to be inserted into the user table user, and the other part of the role data needs to be inserted into the intermediate table sys user role

The user-add.jsp page submits the data to the controller to complete the data adding operation. The codes of the controller layer and the service layer are as follows:

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

//service layer code
public void save(User user, Long[] roleIds) {
        //The first step is to store data in the sys user table
        Long userId = userDao.save(user);
        //Step 2 store multiple pieces of data into the sys user role relationship table
        userDao.saveUserRoleRel(userId,roleIds);
    }

Because the code of dao layer needs to be rebuilt, it needs to be rewritten after learning the next chapter, because there is a problem left here. How to obtain the self increasing primary key id value after the operation of dao layer?

17 spring exercise - user add operation - add data to database 2 (application)

When adding a user, the role information assigned by the user should be stored in the intermediate table sys ﹣ user ﹣ role table. The user id and role id are required, and the role id is selected by the foreground page. The user id should be automatically generated by the mysql primary key during the save operation. How to obtain the value of the mysql self increasing primary key?

Get the self increasing primary key value of mysql when using JdbcTemplate to perform the insert operation:

The dao layer code of the add operation is as follows:

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

18 spring exercise - delete user action (application)

The requirements for deleting user functions are shown in the figure:

The operation steps are as follows:

① Click the delete button in the user list to send the request to the server

② Write del() method of UserController

③ Write del() method of UserService

⑤ Write the delUserRoleRel() method of UserDao

⑥ Jump back to the current user list page

To delete a user, you need to delete not only the user table data, but also the associated table data of the user and role

controller code

@RequestMapping("/del/{userId}")
    public String del(@PathVariable("userId") Long userId){
        userService.del(userId);
        return "redirect:/user/list";
    }

service code

public void del(Long userId) {
        //1. Delete the sys user role relationship table
        userDao.delUserRoleRel(userId);
        //2. Delete sys user table
        userDao.del(userId);
    }

dao Code: not only to delete the user table data, but also to delete the associated table data of users and roles

public void delUserRoleRel(Long userId) {
        jdbcTemplate.update("delete from sys_user_role where userId=?",userId);
    }

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

([Click to open my homepage system to learn java])

Published 78 original articles, won praise 6, visited 3279
Private letter follow

Posted by chombone on Thu, 27 Feb 2020 01:37:52 -0800