Maven集成Struts2+mybatis

本文介绍如何使用Maven构建工具搭建Struts2框架,包括配置依赖、web.xml、struts.xml等关键文件,以及实现简单的登录功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

maven是一个功能强大的工具,最近有兴趣对maven搭建相关框架感兴趣,所以试着用maven搭建相关框架。
下面介绍maven集成Struts2
1.首先创建一个maven web项目。
这里写图片描述

2.在pom.xml中添加相关依赖

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.struts2</groupId>
    <artifactId>mavenStruts2</artifactId>
    <packaging>war</packaging>
    <version>1.0-SNAPSHOT</version>
    <name>mavenStruts2 Maven Webapp</name>
    <url>http://maven.apache.org</url>
    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>org.apache.struts</groupId>
            <artifactId>struts2-core</artifactId>
            <version>2.5.1</version>
        </dependency>

        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.1</version>
        </dependency>

        <dependency>
            <groupId>jstl</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>

        <dependency>
            <groupId>taglibs</groupId>
            <artifactId>standard</artifactId>
            <version>1.1.2</version>
        </dependency>

        <!-- Oracle Jdbc Driver -->
        <dependency>
            <groupId>com.oracle</groupId>
            <artifactId>ojdbc14</artifactId>
            <version>10.2.0.1.0</version>
            <scope>runtime</scope>
        </dependency>
    </dependencies>

    <build>
        <finalName>mavenStruts2</finalName>
    </build>
</project>

3.配置web.xml

<!DOCTYPE web-app PUBLIC
        "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
        "http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
    <display-name>Archetype Created Web Application</display-name>

    <!-- 定义Struts2核心filter -->
    <filter>
        <filter-name>struts2</filter-name>
        <!--如果是早起的Struts2可能是下面的样子 -->
        <filter-class>org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter</filter-class>
       <!-- <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>-->
    </filter>
    <filter-mapping>
        <filter-name>struts2</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <welcome-file-list>
        <welcome-file>index.html</welcome-file>
        <welcome-file>index.htm</welcome-file>
        <welcome-file>index.jsp</welcome-file>
        <welcome-file>default.html</welcome-file>
        <welcome-file>default.htm</welcome-file>
        <welcome-file>default.jsp</welcome-file>
    </welcome-file-list>
</web-app>

3.在resources文件夹下添加struts.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
        "-//Apache Software Foundation//DTD Struts Configuration 2.5//EN"
        "http://struts.apache.org/dtds/struts-2.5.dtd">
<struts>
    <constant name="struts.devMode" value="true"></constant>
    <constant name="struts.i18n.encoding" value="UTF-8"></constant>
    <constant name="struts.locale" value="zh_CN"></constant>
    <constant name="struts.enable.DynamicMethodInvocation" value="true"/>

    <package name="default" extends="struts-default" namespace="/">
       <global-allowed-methods>goTo</global-allowed-methods>
        <action name="login" class="action.LoginAction">
            <result name="success">
                welcome.jsp
            </result>

            <result name="welcome">
                welcome.jsp
            </result>
        </action>
    </package>
</struts>

4.在webapp文件夹下添加index.jsp

<html>
<body>
<form action="/login!goTo">
    UserId:<input type="text" name="per.personId"/>
    <input type="submit" value="Submit">
</form>
</body>
</html>

5.添加welcome.jsp

<%--
  Created by IntelliJ IDEA.
  User: lenovo
  Date: 2018/1/17
  Time: 13:54
  To change this template use File | Settings | File Templates.
--%>
<%@ page isELIgnored="false"%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
<head>
    <title>Title</title>
</head>
<body style="background: #80ffa5">
<table border=1 style="background: #b7ff47">
    <tr><td>Id</td><td>Name</td><td>Age</td></tr>
    <c:forEach items="${plist}" var="plist">
    <tr>
        <td>${plist.personId}</td>
        <td>${plist.personName}</td>
        <td>${plist.personAge}</td>
    </tr>
    </c:forEach>
</body>
</html>

6.在main下添加action包,并添加LoginAction

package action;

import bean.Person;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import service.IPersonService;
import serviceImpl.PersonServiceImpl;

import java.util.ArrayList;
import java.util.List;

public class LoginAction extends ActionSupport {
    private Person per;
    private IPersonService iper;

    public String goTo(){
       /* Person p1 = new Person();
        Person p2 = new Person();
        Person p3 = new Person();
        p1.setPersonId(1);
        p1.setPersonName("Tom1");
        p1.setPersonAge(21);

        p2.setPersonId(2);
        p2.setPersonName("Tom2");
        p2.setPersonAge(21);

        p3.setPersonId(3);
        p3.setPersonName("Tom3");
        p3.setPersonAge(21);*/

        /*Person p = new Person();
        p.setPersonId(2);*/
        List <Person > plist = new ArrayList<Person>();
        iper = new PersonServiceImpl();
        plist = iper.getPersonListById(per);

        ActionContext.getContext().getSession().put("plist", plist);
        return "welcome";
    }

    @Override
    public String execute() throws Exception {
        return "success";
    }

    public Person getPer() {
        return per;
    }

    public void setPer(Person per) {
        this.per = per;
    }

    public IPersonService getIper() {
        return iper;
    }

    public void setIper(IPersonService iper) {
        this.iper = iper;
    }
}

7.添加base包,并添加DataConfig

package base;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

public class DataConfig {
    public static SqlSessionFactory sqlSessionFactory = null;

    public static SqlSessionFactory dataConfig() throws IOException {
        String resource = "config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        return sqlSessionFactory;
    }
}

8.在resources下添加config.xml

<?xml version="1.0" encoding="UTF-8"?>
                 <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" 
                 "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <!-- 注册对象的空间命名 -->
    <typeAliases>
        <typeAlias type="bean.Person" alias="Person" />
    </typeAliases>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC" />
            <dataSource type="POOLED">
                <!-- 1.加载数据库驱动:oracle.jdbc.driver.OracleDriver -->
                <property name="driver" value="oracle.jdbc.driver.OracleDriver" />
                <!-- 2.数据库连接地址:oracle.jdbc.driver.OracleDriver -->
                <property name="url" value="jdbc:oracle:thin:@localhost:1521:ORCL" />
                <!-- 数据库用户 -->
                <property name="username" value="**********************" />
                <!-- 数据库密码-->
                <property name="password" value="**********************" />
            </dataSource>
        </environment>
    </environments>
    <!-- 注册映射文件:java对象与数据库之间的xml文件路径! -->
    <mappers>
        <mapper resource="mapper/person.xml" />
    </mappers>
</configuration>

9.在resources下添加mapper,并添加person.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!-- 命名空间mapper:bean.Person -->
<mapper namespace="dao.PersonDao">
    <resultMap type="Person" id="selectPerson">
        <id column="perId" property="personId"/>
        <result property="personId" column="perId"/>
        <result property="personName" column="perName"/>
        <result property="personAge" column="perAge"/>
    </resultMap>

    <select id="getPersonListById" parameterType="Person" resultType="Person" resultMap="selectPerson">
        <!-- 底层的SQL语句 -->
        select * from person p where p.perid =#{personId}
    </select>

    <select id="getAllPersonList" resultType="Person" resultMap="selectPerson">
        <!-- 底层的SQL语句 -->
        select * from person p
    </select>
</mapper>

10.在main下添加bean、dao、service、serviceImpl
bean

package bean;

import java.io.Serializable;

public class Person implements Serializable {
    /**
     *
     */
    private static final long serialVersionUID = 1L;
    private int personId;
    private String personName;
    private int personAge;

    public int getPersonId() {
        return personId;
    }

    public void setPersonId(int personId) {
        this.personId = personId;
    }

    public String getPersonName() {
        return personName;
    }

    public void setPersonName(String personName) {
        this.personName = personName;
    }

    public int getPersonAge() {
        return personAge;
    }

    public void setPersonAge(int personAge) {
        this.personAge = personAge;
    }

    public Person() {
        super();
        // TODO Auto-generated constructor stub
    }

    public Person(int personId, String personName, int personAge) {
        super();
        this.personId = personId;
        this.personName = personName;
        this.personAge = personAge;
    }


}

dao

package dao;

import java.util.List;

import bean.Person;

public interface PersonDao {
  public List<Person> getPersonListById(Person p);
  public List<Person> getAllPersonList();
}

service

package service;

import java.util.List;

import bean.Person;

public interface IPersonService {
  public List<Person> getPersonListById(Person p);
  public List<Person> getAllPersonList();
}

serviceImpl

package serviceImpl;

import java.util.List;

import base.DataConfig;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import service.IPersonService;
import bean.Person;
import dao.PersonDao;

public class PersonServiceImpl implements IPersonService {
    public static SqlSessionFactory sqlSessionFactory = null;
    private static PersonDao personDao;
    private static SqlSession session = null;

    public static void dataConfig(){
        try{
            sqlSessionFactory = DataConfig.dataConfig();
            session = sqlSessionFactory.openSession();
            personDao = session.getMapper(PersonDao.class);
        }catch(Exception e){
            e.printStackTrace();
        }
    }

    public List<Person> getPersonListById(Person p) {
    // TODO Auto-generated method stub
        dataConfig();
        List<Person> plist = null;
        try{
            plist = personDao.getPersonListById(p);
            for(Person p2 : plist){
                System.out.println(p2.getPersonId()+"\t"+p2.getPersonName()+"\t"+p2.getPersonAge());
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            session.close();
        }
        return plist;
    }

    public List<Person> getAllPersonList() {
        dataConfig();
        List<Person> plist = null;
        try{
            plist = personDao.getAllPersonList();
            for(Person p : plist){
                System.out.println(p.getPersonId()+"\t"+p.getPersonName()+"\t"+p.getPersonAge());
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
             session.close();
        }
        return plist;
    }

}

7.将项目部署到tomcat,并启动访问
首页

登录成功

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值