Tags: SSH Integration and Reading project


preface

We’ve already learned how to integrate the SSH framework. It’s time to practice with a small project…. We are now going to design an enterprise personnel management system…

Requirements:

  • ** Requires maintenance of employee information; **
  • Background system login first, can operate staff: add/modify/delete
  • No login, can only view the list, can not operate!

Functional classification:

  • [Administrator Module]
    • Registration/Login
  • [Employee Module]
      1. Add an employee, specifying the department to be added
      1. Modify the specified employee information
      1. Delete select employee
      1. The list shows

Database design

  • Admin table: t_admin
  • Employee table: t_user
  • Department: t_dept

Setting up the Configuration Environment

For details on setting up the configuration environment, please refer to the previous blog post: blog.csdn.net/hon_3y/arti…

Write Javabeans and mapping files #

Javabeans code # #

Admin.java


public class Admin {

    private int id;
    private String username;
    private String password;


    public int getId(a) {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getUsername(a) {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword(a) {
        return password;
    }

    public void setPassword(String password) {
        this.password = password; }}Copy the code

User.java


public class User {

    private int id;
    private String username;
    private Dept dept;


    public int getId(a) {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getUsername(a) {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public Dept getDept(a) {
        return dept;
    }

    public void setDept(Dept dept) {
        this.dept = dept; }}Copy the code

Dept.java


public class Dept {

    private int id;
    private String name;

    public int getId(a) {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName(a) {
        return name;
    }

    public void setName(String name) {
        this.name = name; }}Copy the code

Map file ##

Dept.hbm.xml


<?xml version="1.0" encoding="UTF-8" ? >

      

<hibernate-mapping package="zhongfucheng.entity">

	<class name="Dept" table="t_dept">
		<id name="id" >
			<generator class="native"></generator>
		</id>
		<property name="name" column="name"></property>
	</class>

</hibernate-mapping>


Copy the code

User.hbm.xml


<?xml version="1.0" encoding="UTF-8" ? >

      

<hibernate-mapping package="zhongfucheng.entity">

	<class name="User" table="t_user">
		<id name="id" column="id">
			<generator class="native"></generator>
		</id>
		<property name="username" column="userName"></property>

		<many-to-one name="dept" class="Dept" column="dept_id"/>
	</class>

</hibernate-mapping>


Copy the code

Admin.hbm.xml


<?xml version="1.0" encoding="UTF-8" ? >

      

<hibernate-mapping package="zhongfucheng.entity">

	<class name="Admin" table="t_admin">
		<id name="id" column="id">
			<generator class="native"></generator>
		</id>
		<property name="username" column="userName"></property>
		<property name="password" column="password"></property>
	</class>

</hibernate-mapping>

Copy the code

Write the Dao

Write BaseDao

Why do you write baseDao? Check out this blog post: blog.csdn.net/hon_3y/arti…


package zhongfucheng.dao;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.lang.reflect.ParameterizedType;
import java.util.List;

/** * Created by ozc on 2017/5/16. */
public abstract class BaseDao<T> {

    // The container injects sessionFactory
    @Autowired
    private SessionFactory sessionFactory;

    // Subclass type
    private Class<T> clazz;
    
    // Subclass name
    private String clazzName;
    
    public BaseDao(a){
        clazz = (Class<T>) this.getClass();  // Get the subclass
        ParameterizedType pt = (ParameterizedType) clazz.getGenericSuperclass();

        // Get the real type of the subclass
        clazz = (Class) pt.getActualTypeArguments()[0];
        // Get the name of the subclass.
        clazzName = clazz.getSimpleName();
    }
    public void add(T t){
        sessionFactory.getCurrentSession().save(t);
    }

    public T find(String id){
        return (T) sessionFactory.getCurrentSession().get(clazz, id);
    }

    public void update(T t){
        sessionFactory.getCurrentSession().update(t);
    }

    public void delete(String id){
        T t = (T) sessionFactory.getCurrentSession().get(clazz, id);
        sessionFactory.getCurrentSession().delete(t);
    }

    public List<T> getAll(a) {
        return sessionFactory.getCurrentSession().createQuery("from"+ clazzName).list(); }}Copy the code

Write UserDao

At this point, the UserDao already has all the functionality of baseDao


/** * 1. Add employee -->add() * 2. Modify employee -->find() * 3. Delete employees -->delete() * 4. GetAll employees -->getAll() * 5. Get employee by id -->find() * */
@Repository
public class UserDao extends BaseDao<User>{}Copy the code

Write AdminDao


/** ** 1. Save administrator [register] -->add() * 2. Find administrator [login] -->login() * * * */

@Repository
public class AdminDao extends BaseDao<Admin> {

    @Autowired
    private SessionFactory sessionFactory;

    public Admin login(Admin admin) {
        return (Admin) sessionFactory.
                getCurrentSession().
                createQuery("FROM Admin WHERE username=? AND password=?")
                .setParameter(0, admin.getUsername())
                .setParameter(1, admin.getPassword()) .uniqueResult(); }}Copy the code

Write DeptDao


import org.springframework.stereotype.Repository;
import zhongfucheng.entity.Dept;

/** * 1. Find all departments -->getAll() * 2 Find the department by id -->find() * * */

@Repository
public class DeptDao extends BaseDao<Dept> {}Copy the code

Write the Service

UserService

@Transactional
@Service
public class UserService {

    @Autowired
    private UserDao userDao;


    /** * 1. Add employee -->add() * 2. Modify employee -->find() * 3. Delete employees -->delete() * 4. GetAll employees -->getAll() * 5. Get employee by id -->find() */
    public void addUser(User user) {
        userDao.add(user);
    }

    public void updateUser(User user) {
        userDao.update(user);
    }

    public void deleteUser(String id) {
        userDao.delete(id);
    }

    public List<User> getAllUsers(a) {
        return userDao.getAll();
    }

    public User findUserById(String id) {
        returnuserDao.find(id); }}Copy the code

Write the AdminService


@Transactional
@Service
public class AdminService {


    @Autowired
    private AdminDao adminDao;

    /** * 1. Save admin -->save() * 2. -->login() */
    public void register(Admin admin) {

        adminDao.add(admin);
    }
    public Admin login(Admin admin) {

        returnadminDao.login(admin); }}Copy the code

Write DeptService


@Transactional
@Service
public class DeptService {


    @Autowired
    private DeptDao deptDao;

    /** * 1. Find all departments -->getAll() * 2 Find the department by id -->find() */
    public List<Dept> getAllDept(a) {
        return deptDao.getAll();
    }

    public Dept findDeptById(String id) {
        returndeptDao.find(id); }}Copy the code

Employee module

Now that we’ve written the logic for the background, it’s time to write the Action and the front page data. Let’s start with the employee module.

    1. Add an employee, specifying the department to be added
    1. Modify the specified employee information
    1. Delete select employee
    1. The list shows

The list shows

  • UserAction

package zhongfucheng.action;

import com.opensymphony.xwork2.ActionSupport;
import org.apache.struts2.interceptor.RequestAware;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import zhongfucheng.entity.User;
import zhongfucheng.service.UserService;

import java.util.List;
import java.util.Map;

/** * Created by ozc on 2017/5/15. */

@Controller
@Scope("prototype")

public class UserAction extends ActionSupport implements RequestAware{

    @Autowired
    private UserService userService;

    // Request object is used in many places, so we can implement the interface directly to get request object
    private Map<String, Object> request;
    @Override
    public void setRequest(Map<String, Object> map) {
        this.request = map;
    }

    /* List display */
    public String list(a) {

        List<User> list = userService.getAllUsers();

        System.out.println(list);
        // Encapsulate the data into the Request object
        request.put("list", list);

        return "list"; }}Copy the code

Struts configuration file


        <action name="user_*" class="userAction" method="{1}">

            <! -- List display -->
            <result name="list">/list.jsp</result>
        </action>
Copy the code

List. The JSP page


<% @ page contentType="text/html; charset=UTF-8" language="java"% >
<%@taglib prefix="s" uri="/struts-tags"% >
<html>
<head>
    <title>The list shows</title>
</head>
<body>
<s:if test="#request.list ! = null">
    <table align="center" border="1">
        <tr>
            <td>Employee number</td>
            <td>Employee name</td>
            <td>Staff Department No.</td>
            <td>operation</td>
        </tr>

        <s:iterator var="user" value="#request.list" status="st">
            <tr>
                <td><s:property value="#user.id"/></td>
                <td><s:property value="#user.username"/></td>
                <td><s:property value="#user.dept.id"/> </td>
                <td><s:a href="#">Modify, delete</s:a></td>
            </tr>
        </s:iterator>
    </table>
</s:if>

<s:else>Sorry, there is no employee's information, please input</s:else>
</body>
</html>

Copy the code

Effect:


Add employees

Add an employee, specify the department to be added, go to the page for adding an Employee…


    @Autowired
    private DeptService deptService;

    /* Add staff... Shows the added JSP page */
    public String viewAdd(a) {

        // You need to get all the department information when adding employees
        List<Dept> deptList = deptService.getAllDept();

        // encapsulate to the Request domain object
        request.put("deptList", deptList);

        return "viewAdd";
    }
Copy the code

            <! -- Give the interface for adding employees -->
            <result name="viewAdd">/viewAdd.jsp</result>
Copy the code

The interface for adding employees is displayed:


<% @ page contentType="text/html; charset=UTF-8" language="java"% >
<%@taglib prefix="s" uri="/struts-tags"% >

<html>
<head>
    <title>Adding an employee interface</title>
</head>
<body>

<s:form method="POST" action="user_addUser.action" theme="simple">

    <table align="center" border="1">
        <tr>
            <td>Staff name</td>
            <td><s:textfield name="username" id="username" value=""/></td>
        </tr>

        <tr>
            <td>Department employees</td>
            <! Struts dropdown tag: Name ="deptId" Label name of the drop-down list (by which the server obtains the actual value of the selected item) headerKey Actual value of the default selection headerValue Content to be displayed in the default drop-down list List Collection of data to be displayed in the drop-down list Which property of the listKey collection object is used as the value of an instance of the drop-down list, i.e., value value Which property of the listValue collection object is used as the value of the drop-down list to display value Default Settings for selected items -->
            <td><s:select list="#request.deptList" headerKey="1" headerValue="Please select" listKey="id" listValue="name" name="deptId"/></td>
        </tr>
        <tr>
            <td colspan="2"><s:submit value="Add employees"/></td>
        </tr>
    </table>
</s:form>


</body>
</html>
Copy the code
  • Use model-driven and automatic data encapsulation in the Action to retrieve the data brought in by the JSP page:

    // Model driven
    User user = new User();
    public User getUser(a) {
        return user;
    }
    public void setUser(User user) {
        this.user = user;
    }
    @Override
    public Object getModel(a) {
        return user;
    }

    // Automatically encapsulate deptId
    private int deptId;
    public int getDeptId(a) {
        return deptId;
    }
    public void setDeptId(int deptId) {
        this.deptId = deptId;
    }
Copy the code
  • Find the department to which you want to add employees and set up the employee-department relationship. Add to database:

    /* Add employee */
    public String addUser(a) {
        // Find the department object based on the department ID
        Dept dept = deptService.findDeptById(deptId);
        // Set up the relationship between departments and employees
        user.setDept(dept);

        userService.addUser(user);
        // Return to list display
        return "listPage";
    }
Copy the code
  • Return to the list display page

            <! Return to the list display page -->
            <result name="listPage" type="redirectAction">user_list</result>
Copy the code
  • Effect:


Modify the employee

  • Modify and delete hyperlinks: specify the user ID to be changed.
                <td>
                    <s:a href="user_viewUpdate? id=%{#user.id}">Modify the</s:a>
                    <s:a href="user_delete? id=%{#user.id}">delete</s:a>
                </td>

Copy the code

  • Provide an interface for modifying data

    /* Provides the page for the modification, which is actually the output data */
    public String viewUpdate(a) {

        / / get the user
        User user = userService.findUserById(this.user.getId());
        // Get all the departments
        List<Dept> deptList = deptService.getAllDept();
        request.put("deptList", deptList);

        // Use Struts2 echo technology
        ValueStack valueStack = ActionContext.getContext().getValueStack();
        valueStack.pop();
        valueStack.push(user);
        return "viewUpdate";
    }
Copy the code


            <! -- Provide modification page -->
            <result name="viewUpdate">/viewUpdate.jsp</result>
Copy the code
  • Modify page JSP

<% @ page contentType="text/html; charset=UTF-8" language="java"% >
<%@taglib prefix="s" uri="/struts-tags"% >

<html>
<head>
    <title>Modify the employee interface</title>
</head>
<body>

<s:form method="POST" action="user_updateUser.action" theme="simple">

    <table align="center" border="1">

        <%-- here you want to bring the ID through the hidden field --%>
        <s:hidden name="id" id="id" value="%{id}"/>
        <tr>
            <td>Staff name</td>
            <td><s:textfield name="username" id="username"/></td>
        </tr>

        <tr>
            <td>Department employees</td>
            <td>
                <s:select name="deptId"
                          list="#request.deptList"
                          listKey="id"
                          listValue="name"
                          value="dept.id"/>
            </td>
        </tr>
        <tr>
            <td colspan="2"><s:submit value="Modify employees"/></td>
        </tr>
    </table>
</s:form>

</body>
</html>
Copy the code
  • Because we are model-driven, the Action encapsulates the data brought in by the JSP directly into the User object, which we can use directly

    /* To confirm the modification of the employee, the model-driven encapsulates the data directly into the User object */
    public String updateUser(a) {
        // Get the department
        Dept dept = deptService.findDeptById(deptId);

        // Set up the relationship between employees and departments
        user.setDept(dept);

        userService.updateUser(user);

        // After modification, return to display list
        return "listPage";
    }
Copy the code
  • Effect:


Delete staff


    /* Delete employee */
    public String delete(a) {

        userService.deleteUser(user.getId());

        // After modification, return to display list
        return "listPage";
    }

Copy the code
  • Testing:


Administrator module

  • registered
  • landing

registered

  • Provide hyperlinks to register
<s:a href="register.jsp">registered</s:a>
Copy the code
  • Admin.action

package zhongfucheng.action;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import zhongfucheng.entity.Admin;
import zhongfucheng.service.AdminService;

/** * Created by ozc on 2017/5/15. */

@Controller
@Scope("prototype")

public class AdminAction extends ActionSupport implements ModelDriven<Admin>{


    / * * * * * * * * * * call service * * * * * * * * * * * * * * /
    @Autowired
    private AdminService adminService;


    /************** uses model-driven ******************/
    Admin admin = new Admin();
    public Admin getAdmin(a) {
        return admin;
    }
    public void setAdmin(Admin admin) {
        this.admin = admin;
    }
    @Override
    public Admin getModel(a) {
        returnadmin; }}Copy the code
  • Configuration information

        <! --############ Administrator module #################-->
        <action name="admin_*" class="adminAction" method="{1}">

        </action>
Copy the code
  • The JSP page:

<% @ page contentType="text/html; charset=UTF-8" language="java"% >
<html>
<head>
    <title>The registration screen</title>
</head>
<body>

<s:form action="admin_register" method="POST" theme="simple">
    <table border="1" align="center">
        <tr>
            <td>Administrator account:</td>
            <td><s:textfield name="username"/></td>
        </tr>
        <tr>
            <td>Administrator password:</td>
            <td><s:textfield name="password"/></td>
        </tr>

        <tr>
            <td colspan="2"><s:submit value="Registered"/> </td>
        </tr>
    </table>
</s:form>

</body>
</html>
Copy the code
  • The Action to achieve

    /* Get the data from the JSP page, complete the registration */
    public String register(a) {

        adminService.register(admin);

        return "listPage";
    }

Copy the code
  • Effect:


Log in function

  • Provide a hyperlink to login

<s:a href="login.jsp">landing</s:a>
Copy the code
  • Login JSP page

<% @ taglib prefix="s" uri="/struts-tags"% >
<% @ page contentType="text/html; charset=UTF-8" language="java"% >
<html>
<head>
    <title>Login interface</title>
</head>
<body>

<s:form action="admin_login" method="POST" theme="simple">
    <table border="1" align="center">
        <tr>
            <td>Administrator account:</td>
            <td><s:textfield name="username" value=""/></td>
        </tr>
        <tr>
            <td>Administrator password:</td>
            <td><s:textfield name="password" value=""/></td>
        </tr>

        <tr>
            <td colspan="2"><s:submit value="Login"/> </td>
        </tr>
    </table>
</s:form>

</body>
</html>

Copy the code
  • Action handles login


    /* Complete login */
    public String login(a) {

        adminService.login(admin);
        // Save the user to Sessiion
        ActionContext.getContext().getSession().put("admin", admin);
        return "listPage";
    }


Copy the code
  • Give corresponding prompt in the list page, if logged in, give a welcome display

<s:if test="#session.admin ! =null">Welcome you to:<s:property value="%{#session.admin.username}"/>
</s:if>

Copy the code
  • Effect:


Permission to operate

  • Background system login first, can operate staff: add/modify/delete
  • No login, can only view the list, can not operate!

We write an interceptor that determines whether to call login or list-display methods, and if not, checks to see if the user is logged in. Jump to login screen without login


package zhongfucheng.action;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

/** * Created by ozc on 2017/5/17. */
public class PrivilegeInterceptor extends AbstractInterceptor {

    @Override
    public String intercept(ActionInvocation actionInvocation) throws Exception {

        / / get the ActionContext
        ActionContext context = actionInvocation.getInvocationContext();

        // Get the name of the method calling the Action
        String methodName = actionInvocation.getProxy().getMethod();

        // Get the object of the session administrator
        Object o = context.getSession().get("admin");

        // Determine what method is being called
        if ("login".equals(methodName) || "list".equals(methodName)) {

            // Call both methods without permission
            return actionInvocation.invoke();
        } else {
            // If not, check

            // If there is no login, jump to the login screen
            if (o == null) {
                return "login";
            } else {
                // If you have logged in, you can execute it
                returnactionInvocation.invoke(); }}}}Copy the code
  • Configure the interceptor in the Struts2 configuration file

		<! Interceptor configuration -->
		<interceptors>
			<interceptor name="userInterceptor" class="cn.itcast.action.UserInterceptor"></interceptor>
			<interceptor-stack name="myStack">
				<interceptor-ref name="defaultStack"></interceptor-ref>
				<interceptor-ref name="userInterceptor"></interceptor-ref>
			</interceptor-stack>
		</interceptors>
		<! Execute the specified interceptor -->
		<default-interceptor-ref name="myStack"></default-interceptor-ref>
	
Copy the code
  • The login returned by the interceptor needs to be configured with a global view

        <global-results>
            <! Return to the display list page -->
            <result name="listPage" type="redirectAction">user_list</result>


            <! -- Interceptor returns login-->
            <result name="login" type="redirect">/login.jsp</result>
        </global-results>
Copy the code
  • Effect:

conclusion

This article mainly uses SSH framework to develop a relatively simple CRUD project. Let’s get familiar with the process of SSH framework development.

  • The design entity
  • Write a mapping file for each entity
  • Load the mapping file into Hibernate for management
  • Use BaseDao to manage all daos so that each Dao has a Curd method. This saves us from having to write Crud on every Dao
  • If the normal CURD method does not satisfy us, we can write the desired functionality in the specific Dao
  • The Service layer invokes the methods of the Dao layer
  • The Controller calls the method of the Service layer to implement the function. If the acquired data is needed on the page, we first call the Service to obtain the data, and then store the data through the domain object (value stack object) and display it on the page.

If you find this article helpful, give the author a little encouragement