使用IDEA+Maven搭建整合一个Struts2+Spring4+Hibernate4项目,混合使用传统Xml与@注解,返回JSP视图或JSON数据,快来给你的SSH老项目翻新一下吧

大学时做过一些基于Struts+Spring+Hibernate的项目,但是项目是使用MyEclipse或者Eclipse工具来开发的,而且还是外部地引入依赖包,甚是麻烦。想着翻新一下曾今写的一些SSH项目,于是使用IDEA+Maven来搭建整合一下。主要就是拿来玩的,听说Struts2挺多漏洞的,有过几次漏洞事故,不知修复得怎么样,至于这个技术,大家就简单看看就好了。

一、创建一个Maven项目

(1)项目名称为“j2ee-struts2-spring4-hibernate4”

(2)pom.xml



  4.0.0
  org.example
  j2ee-struts2-spring4-hibernate4
  1.0-SNAPSHOT
  war

  
    
    UTF-8
    
    4.0.3.RELEASE
    
    2.5.26
    
    4.3.5.Final
    
    3.1.1
  

  
    
    
      org.springframework
      spring-core
      ${spring.version}
    

    
      org.springframework
      spring-beans
      ${spring.version}
    

    
      org.springframework
      spring-context
      ${spring.version}
    

    
      org.springframework
      spring-web
      ${spring.version}
    

    
      org.springframework
      spring-orm
      ${spring.version}
    

    
      org.springframework
      spring-tx
      ${spring.version}
    
    

    
    
      org.apache.struts
      struts2-core
      ${struts2.version}
    

    
      org.apache.struts
      struts2-spring-plugin
      ${struts2.version}
    

    
      org.apache.struts
      struts2-convention-plugin
      ${struts2.version}
    

    
      org.apache.struts
      struts2-json-plugin
      ${struts2.version}
    
    

    
    
      org.hibernate
      hibernate-core
      ${hibernate.version}
    

    
      org.hibernate
      hibernate-ehcache
      ${hibernate.version}
    
    

    
    
      org.mybatis
      mybatis
      ${mybatis.version}
    

    
      org.mybatis
      mybatis-spring
      1.2.2
    
    

    
    
      org.apache.openejb
      javaee-api
      5.0-1
      provided
    

    
      javax.faces
      jsf-api
      1.2_04
      provided
    

    
      javax.servlet
      jstl
      1.2
      provided
    

    
      javax.servlet.jsp
      jsp-api
      2.1
      provided
    
    

    
    
      com.mchange
      c3p0
      0.9.2.1
    

    
    
      mysql
      mysql-connector-java
      5.1.38
    

    
    
      org.projectlombok
      lombok
      1.18.16
      provided
    

    
    
      com.alibaba
      fastjson
      1.2.73
    
  

  
  
    
      
        org.apache.maven.plugins
        maven-compiler-plugin
        2.3.2
        
          1.6
          1.6
        
      
    
  

二、设计目录结构

(1)在项目目录 “/src/main/java”新建“org.example”包名,里面再新建“action,dao,entity,service,utils”目录

(2)在项目目录 “/src/main”新建“webapp”包目录,里面再新建“views/jsp,WEB_INF”目录

(3)在项目目录 “/src/main/resource”新建“spring,struts,hibernate,config”目录

三、实现项目模块

(1)在webapp目录下放置一个index.jsp文件

<%--
  Created by IntelliJ IDEA.
  User: 帅龍之龍
  Date: 2023/7/25
  Time: 15:37
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>


    Title


    
你好,世界! ...

(2)在webapp/WEB_INF目录下放置一个web.xml文件




  我爱你

  
    
    index.jsp
  

  
    contextConfigLocation
    classpath:spring/applicationContext.xml,classpath:spring/**/applicationContext*.xml
  

  
    org.springframework.web.context.ContextLoaderListener
  

  
    struts2

    
    

    
    org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter

    
      config
      
      platform-web.xml,struts-default.xml,struts-plugin.xml,struts/struts.xml
    
  

  
    struts2
    /*
  

(3)在webapp/views/jsp目录下放置一个success.jsp,error.jsp,login.jsp,home.jsp

success.jsp

<%@ taglib prefix="s" uri="/struts-tags" %>
<%--
  Created by IntelliJ IDEA.
  User: 帅龍之龍
  Date: 2023/7/25
  Time: 15:37
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>


    Title


    

你好,${request.username}

error.jsp

<%@ taglib prefix="s" uri="/struts-tags" %>
<%--
  Created by IntelliJ IDEA.
  User: 帅龍之龍
  Date: 2023/7/25
  Time: 15:37
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>


    Title


你好,匿名用户

login.jsp

<%--
  Created by IntelliJ IDEA.
  User: 帅龍之龍
  Date: 2023/7/25
  Time: 15:37
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>



    
    
    前台系统登录页面
    
    

    







home.jsp

<%--
  Created by IntelliJ IDEA.
  User: 帅龍之龍
  Date: 2023/7/25
  Time: 15:37
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="s" uri="/struts-tags" %>


    Title


尊敬的用户:${session.ssh_user.username}, 尊敬的匿名用户, 欢迎来到前台系统首页 ~

(4)在resource/struts目录下放置struts.xml,struts-hi.xml





    
    

    
    

    
    

    
    
        
        
            /views/jsp/success.jsp
            /views/jsp/error.jsp
        

        
        

        
        

        
        

        
        
    

    
    

    
    
        
            
        

        
            
        
    

struts-hi.xml





    
        
        
            /views/jsp/success.jsp
            /views/jsp/error.jsp
        
    

(5)在resource/spring目录下放置applicationContext.xml




  
  
  

  
  
  

  
  

(6)实现具体代码

org.example.action.IndexAction

package org.example.action;

import lombok.Getter;
import lombok.Setter;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import org.example.entity.User;
import org.example.service.IUserService;
import org.example.utils.BaseAction;
import org.springframework.stereotype.Controller;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

/**
 * 基于注解方式注册Action
 */
@Controller(value = "indexAction") // 若使用 @Controller 注解,则在 applicationContext.xml 配置文件中无需手动注册此类,因为其由 spring 进行实例化
public class IndexAction extends BaseAction {

    @Getter
    @Setter
    protected IUserService userService;

    @Getter
    @Setter
    private User user;

    /**
     * 跳转前台首页
     */
    @Action(value = "/home", results = {
            @Result(name="success", location = "/views/jsp/home.jsp")
    })
    public String home() {
        return SUCCESS;
    }

    /**
     * 跳转登录页面
     */
    @Action(value = "/toLogin", results = {
            @Result(name="success", location = "/views/jsp/login.jsp")
    })
    public String toLogin() {
        return SUCCESS;
    }

    /**
     * 用户登录
     */
    @Action(value = "/login", results = {
            @Result(name="success", type = "redirect", location = "home"),
            @Result(name="error", type = "redirect", location = "toLogin")
    })
    public String login() {
        String method = ServletActionContext.getRequest().getMethod();
        System.out.println("请求方式 = " + method);
        System.out.println(user);
        return userService.login(user.getUsername(), user.getPassword());
    }

    /**
     * 用户登出
     */
    @Action(value = "/loginOut", results = {
            @Result(name="success", type = "redirect", location = "toLogin")
    })
    public String loginOut() {
        return SUCCESS;
    }

    @PostConstruct
    public void init() {
        System.out.println("正在初始化 IndexAction ...");
    }

    @PreDestroy
    public void destory() {
        System.out.println("正在销毁 IndexAction ...");
    }
}

org.example.action.J2EEAction

package org.example.action;

import org.apache.struts2.ServletActionContext;
import org.example.utils.BaseAction;
import com.alibaba.fastjson.JSONObject;
import org.example.entity.User;
import org.example.service.IUserService;
import lombok.Getter;
import lombok.Setter;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@ParentPackage("json-default") // 使用默认的 JSON 处理器,若想自定义其它 JSON 处理器,可在 struts.xml 文件中配置,并使用包名,如:jsonPackage
@Namespace("/j2ee/api") // 指定所属的名称空间
@Scope(value = "prototype") // 原型模式
@Controller(value = "demoAction") // 若使用 @Controller 注解,则在 applicationContext.xml 配置文件中无需手动注册此类,因为其由 spring 进行实例化
public class J2EEAction extends BaseAction {

    @Getter
    @Setter
    protected IUserService userService;

    @Setter
    @Getter
    private JSONObject responseJson = new JSONObject();

    @Action(value = "getUserList_1", results = {@Result(name="success", type = "json", params = {"root", "responseJson"})})
    public String getUserList_1() {
        String method = ServletActionContext.getRequest().getMethod();
        System.out.println("请求方式 = " + method);

        User user1 = new User("云缨", "111111");
        User user2 = new User("手法英雄-赵怀真", "222222");
        List userList = new ArrayList();
        userList.add(user1);
        userList.add(user2);
        responseJson.put("success", true);
        responseJson.put("data", userList);
        responseJson.put("msg", "getUserList 成功");
        return SUCCESS;
    }

    @Action(value = "getUserList_2", results = {@Result(name="success", type = "json", params = {"root", "responseJson"})})
    public String getUserList_2() {
        String method = ServletActionContext.getRequest().getMethod();
        System.out.println("请求方式 = " + method);

        User user1 = new User("项羽", "111111");
        User user2 = new User("虞姬", "222222");
        List userList = new ArrayList();
        userList.add(user1);
        userList.add(user2);
        responseJson.put("success", true);
        responseJson.put("data", userList);
        responseJson.put("msg", "getUserList 成功");
        return SUCCESS;
    }

    @PostConstruct
    public void init() {
        System.out.println("正在初始化 J2EEAction ...");
    }

    @PreDestroy
    public void destory() {
        System.out.println("正在销毁 J2EEAction ...");
    }
}

org.example.action.JavaEEAction

package org.example.action;

import com.alibaba.fastjson.JSONObject;
import lombok.Getter;
import lombok.Setter;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.example.entity.User;
import org.example.service.IUserService;
import org.example.utils.BaseAction;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.util.ArrayList;
import java.util.List;

@ParentPackage("jsonPackage") // 使用默认的 JSON 处理器,若想自定义其它 JSON 处理器,可在 struts.xml 文件中配置,并使用包名,如:jsonPackage
@Namespace("/javaee/api") // 指定所属的名称空间
@Scope(value = "prototype") // 原型模式
@Controller(value = "demo2Action") // 若使用 @Controller 注解,则在 applicationContext.xml 配置文件中无需手动注册此类,因为其由 spring 进行实例化
public class JavaEEAction extends BaseAction {

    @Getter
    @Setter
    protected IUserService userService;

    @Setter
    @Getter
    private JSONObject responseJson = new JSONObject();

    @Action(value = "getUserList_1", results = {@Result(name="success", type = "json", params = {"root", "responseJson"})})
    public String getUserList_1() {
        String method = ServletActionContext.getRequest().getMethod();
        System.out.println("请求方式 = " + method);

        User user1 = new User("至尊宝", "111111");
        User user2 = new User("露娜", "222222");
        List userList = new ArrayList();
        userList.add(user1);
        userList.add(user2);
        responseJson.put("success", true);
        responseJson.put("data", userList);
        responseJson.put("msg", "getUserList 成功");
        return SUCCESS;
    }

    @Action(value = "getUserList_2", results = {@Result(name="success", type = "json", params = {"root", "responseJson"})})
    public String getUserList_2() {
        String method = ServletActionContext.getRequest().getMethod();
        System.out.println("请求方式 = " + method);

        User user1 = new User("吕布", "111111");
        User user2 = new User("貂蝉", "222222");
        List userList = new ArrayList();
        userList.add(user1);
        userList.add(user2);
        responseJson.put("success", true);
        responseJson.put("data", userList);
        responseJson.put("msg", "getUserList 成功");
        return SUCCESS;
    }

    @PostConstruct
    public void init() {
        System.out.println("正在初始化 JavaEEAction ...");
    }

    @PreDestroy
    public void destory() {
        System.out.println("正在销毁 JavaEEAction ...");
    }
}

org.example.action.TestAction

package org.example.action;

import lombok.Getter;
import lombok.Setter;
import org.example.utils.BaseAction;
import org.springframework.util.StringUtils;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

/**
 * 基于 xml 传统方式注册 Action,见 struts.xml 文件中注册
 */
public class TestAction extends BaseAction {

    @Getter
    @Setter
    private String username;

    /**
     * 你好
     */
    public String hello() {
        if (!StringUtils.isEmpty(username)) {
            return SUCCESS;
        } else {
            return ERROR;
        }
    }

    /**
     * 你好
     */
    public String hi() {
        if (!StringUtils.isEmpty(username)) {
            return SUCCESS;
        } else {
            return ERROR;
        }
    }

    @PostConstruct
    public void init() {
        System.out.println("正在初始化 TestAction ...");
    }

    @PreDestroy
    public void destory() {
        System.out.println("正在销毁 TestAction ...");
    }
}

org.example.entity.User

package org.example.entity;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
    private String username;
    private String password;
}

org.example.service.IUserService

package org.example.service;

public interface IUserService {

    String login(String username, String password);
}

org.example.service.impl.UserServiceImpl

package org.example.service.impl;

import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionContext;
import org.example.entity.User;
import org.example.service.IUserService;
import org.springframework.stereotype.Service;

import java.util.Map;

@Service(value = "userService") // 若使用 @Service 注解,则在 applicationContext.xml 配置文件中无需手动注册此类,因为其由 spring 进行实例化
public class UserServiceImpl implements IUserService {

    @Override
    public String login(String username, String password) {
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        if (user != null) {
            Map session = ActionContext.getContext().getSession();
            session.put("ssh_user", user);
            System.out.println("session => " + session);
            return Action.SUCCESS;
        }
        return Action.ERROR;
    }
}

org.example.utils.BaseAction

package org.example.utils;

import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;
import org.apache.struts2.interceptor.SessionAware;
import org.apache.struts2.util.ServletContextAware;

import com.opensymphony.xwork2.ActionSupport;

public class BaseAction extends ActionSupport implements ServletContextAware, ServletResponseAware, ServletRequestAware, SessionAware {

    private static final long serialVersionUID = 1L;

    protected ServletContext servletContext;

    protected HttpServletRequest httpServletRequest;

    protected HttpServletResponse httpServletResponse;

    protected HttpSession httpSession;

    protected Map session;

    @Override
    public void setServletContext(ServletContext context) {
        this.servletContext = context;
    }

    @Override
    public void setServletResponse(HttpServletResponse response) {
        response.addHeader("Access-Control-Allow-Origin", "*");
        response.addHeader("Access-Control-Allow-Methods", "*");
        response.addHeader("Access-Control-Allow-Headers","Content-Type");
        response.addHeader("Access-Control-Max-Age", "3600");
        this.httpServletResponse = response;
    }

    @Override
    public void setServletRequest(HttpServletRequest request) {
        this.httpServletRequest = request;
        this.httpSession = request.getSession();
    }

    @Override
    public void setSession(Map session) {
        this.session = session;
    }
}

效果如下 ~

http://localhost:8080/j2ee_struts2_spring4_hibernate4/love/hi?username=帅龍之龍
http://localhost:8080/j2ee_struts2_spring4_hibernate4/love/hello?username=帅龍之龍
http://localhost:8080/j2ee_struts2_spring4_hibernate4/toLogin
http://localhost:8080/j2ee_struts2_spring4_hibernate4/home
http://localhost:8080/j2ee_struts2_spring4_hibernate4/javaee/api/getUserList_2
http://localhost:8080/j2ee_struts2_spring4_hibernate4/j2ee/api/getUserList_2

你可能感兴趣的:(#,SSH古董框架,Java,java,后端)