SSM框架搭建

本文详细介绍了一个基于SpringMVC、MyBatis和Spring(简称SSM)的Java Web项目从搭建到配置的全过程,包括Maven依赖管理、SpringMVC配置、MyBatis配置、数据源配置、Web应用配置及日志配置等关键步骤。

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

目录

 

一、maven导包配置(pom.xml)

二、SpringMVC配置(spring-mvc.xml)

三、Mybatis配置(mybatis.xml)

四、Spring-Mybatis配置(spring-mybatis.xml、 jdbc.properties)

五、web配置(web.xml)

六、日志配置(log4j.properties)


一、maven导包配置(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.zldc</groupId>

  <artifactId>portalZL</artifactId>

  <packaging>war</packaging>

  <version>1.0</version>

  <name>portalZL Maven Webapp</name>

  <url>http://maven.apache.org</url>

 

  <properties>

    <jackson-databind>2.6.5</jackson-databind>

    <spring.version>4.3.7.RELEASE</spring.version>

    <jdk.version>1.8</jdk.version>

    <oracle.version>11.2.0.3</oracle.version>

    <druid.version>1.0.28</druid.version>

    <mybatis.version>3.2.5</mybatis.version>

    <log4j.version>1.2.17</log4j.version>

    <junit.version>4.12</junit.version>

    <freemarker.version>2.3.23</freemarker.version>

    <mybatis.spring.version>1.3.0</mybatis.spring.version>

    <servlet.api.version>2.5</servlet.api.version>

    <jsp.api.version>2.0</jsp.api.version>

    <fastjson.version>1.2.30</fastjson.version>

    <json.lib.version>2.4</json.lib.version>

    <commons.fileupload.version>1.3.1</commons.fileupload.version>

    <slf4j.version>1.7.2</slf4j.version>

  </properties>

 

  <dependencies>

    <dependency>

      <groupId>com.fasterxml.jackson.core</groupId>

      <artifactId>jackson-databind</artifactId>

      <version>${jackson-databind}</version>

    </dependency>

    <dependency>

      <groupId>com.fasterxml.jackson.core</groupId>

      <artifactId>jackson-core</artifactId>

      <version>${jackson-databind}</version>

    </dependency>

    <dependency>

      <groupId>com.fasterxml.jackson.core</groupId>

      <artifactId>jackson-annotations</artifactId>

      <version>${jackson-databind}</version>

    </dependency>

    <!-- 引入Spring(包含SpringMVC) 依赖 start -->

    <dependency>

      <groupId>org.springframework</groupId>

      <artifactId>spring-core</artifactId>

      <version>${spring.version}</version>

    </dependency>

 

    <dependency>

      <groupId>org.springframework</groupId>

      <artifactId>spring-web</artifactId>

      <version>${spring.version}</version>

    </dependency>

    <dependency>

      <groupId>org.springframework</groupId>

      <artifactId>spring-oxm</artifactId>

      <version>${spring.version}</version>

    </dependency>

    <dependency>

      <groupId>org.springframework</groupId>

      <artifactId>spring-tx</artifactId>

      <version>${spring.version}</version>

    </dependency>

 

    <dependency>

      <groupId>org.springframework</groupId>

      <artifactId>spring-jdbc</artifactId>

      <version>${spring.version}</version>

    </dependency>

 

    <dependency>

      <groupId>org.springframework</groupId>

      <artifactId>spring-webmvc</artifactId>

      <version>${spring.version}</version>

    </dependency>

    <dependency>

      <groupId>org.springframework</groupId>

      <artifactId>spring-aop</artifactId>

      <version>${spring.version}</version>

    </dependency>

 

    <dependency>

      <groupId>org.springframework</groupId>

      <artifactId>spring-context-support</artifactId>

      <version>${spring.version}</version>

    </dependency>

 

    <dependency>

      <groupId>org.springframework</groupId>

      <artifactId>spring-test</artifactId>

      <version>${spring.version}</version>

    </dependency>

    <!-- 引入Spring 依赖 end -->

 

    <!-- 加入ServletAPI -->

    <dependency>

      <groupId>javax.servlet</groupId>

      <artifactId>servlet-api</artifactId>

      <version>${servlet.api.version}</version>

      <scope>provided</scope>

    </dependency>

    <dependency>

      <groupId>javax.servlet</groupId>

      <artifactId>jsp-api</artifactId>

      <version>${jsp.api.version}</version>

      <scope>provided</scope>

    </dependency>

 

    <!-- 数据库依赖 -->

<dependency>

      <groupId>mysql</groupId>

      <artifactId>mysql-connector-java</artifactId>

      <version>6.0.6</version>

    </dependency>

 

    <!-- 引用druid数据源依赖 -->

    <dependency>

      <groupId>com.alibaba</groupId>

      <artifactId>druid</artifactId>

      <version>${druid.version}</version>

    </dependency>

 

    <!-- 加入MyBatis 依赖 -->

    <dependency>

      <groupId>org.mybatis</groupId>

      <artifactId>mybatis</artifactId>

      <version>${mybatis.version}</version>

    </dependency>

 

    <!-- 引用插件依赖:MyBatis整合Spring -->

    <dependency>

      <groupId>org.mybatis</groupId>

      <artifactId>mybatis-spring</artifactId>

      <version>${mybatis.spring.version}</version>

    </dependency>

 

    <!-- 文件上传 -->

    <dependency>

      <groupId>commons-fileupload</groupId>

      <artifactId>commons-fileupload</artifactId>

      <version>${commons.fileupload.version}</version>

    </dependency>

 

    <!-- json-lib -->

    <dependency>

      <groupId>net.sf.json-lib</groupId>

      <artifactId>json-lib</artifactId>

      <version>${json.lib.version}</version>

      <classifier>jdk15</classifier>

    </dependency>

 

    <!-- Log4j -->

    <dependency>

      <groupId>log4j</groupId>

      <artifactId>log4j</artifactId>

      <version>${log4j.version}</version>

    </dependency>

 

    <!-- fastjson -->

    <dependency>

      <groupId>com.alibaba</groupId>

      <artifactId>fastjson</artifactId>

      <version>${fastjson.version}</version>

    </dependency>

 

    <!-- slf4j -->

    <dependency>

      <groupId>org.slf4j</groupId>

      <artifactId>slf4j-api</artifactId>

      <version>${slf4j.version}</version>

    </dependency>

    <dependency>

      <groupId>org.slf4j</groupId>

      <artifactId>slf4j-log4j12</artifactId>

      <version>${slf4j.version}</version>

    </dependency>

 

    <!-- junit -->

    <dependency>

      <groupId>junit</groupId>

      <artifactId>junit</artifactId>

      <version>${junit.version}</version>

      <scope>test</scope>

    </dependency>

 

    <!-- freemarker -->

    <dependency>

      <groupId>org.freemarker</groupId>

      <artifactId>freemarker</artifactId>

      <version>${freemarker.version}</version>

    </dependency>

    <dependency>

      <groupId>commons-httpclient</groupId>

      <artifactId>commons-httpclient</artifactId>

      <version>3.0</version>

    </dependency>

 

  </dependencies>

  <build>

    <!-- 打包时候的包名 -->

    <finalName>${project.artifactId}</finalName>

    <plugins>

      <!-- 设置编译版本 -->

      <plugin>

        <groupId>org.apache.maven.plugins</groupId>

        <artifactId>maven-compiler-plugin</artifactId>

        <configuration>

          <source>${jdk.version}</source>

          <target>${jdk.version}</target>

          <encoding>UTF-8</encoding>

        </configuration>

      </plugin>

    </plugins>

  </build>

</project>

二、SpringMVC配置(spring-mvc.xml)

<?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:aop="http://www.springframework.org/schema/aop"

    xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context"

    xmlns:tx="http://www.springframework.org/schema/tx"

    xsi:schemaLocation="http://www.springframework.org/schema/beans 

        http://www.springframework.org/schema/beans/spring-beans-4.3.xsd 

        http://www.springframework.org/schema/tx 

        http://www.springframework.org/schema/tx/spring-tx-4.3.xsd 

        http://www.springframework.org/schema/aop 

        http://www.springframework.org/schema/aop/spring-aop-4.3.xsd 

        http://www.springframework.org/schema/context 

        http://www.springframework.org/schema/context/spring-context-4.3.xsd 

        http://www.springframework.org/schema/mvc 

        http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd">

 

    <!-- 1、配置映射器与适配器 -->

    <mvc:annotation-driven></mvc:annotation-driven>

 

    <!-- 2、视图解析器 -->

    <!-- 配置jsp视图解析器 -->

    <!-- <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">

       <property name="prefix" value="/" /> <property name="suffix" value=".jsp" />

       </bean> -->

 

    <!-- 配置json视图解析器 -->

    <bean id="mappingJacksonHttpMessageConverter"

        class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">

       <property name="supportedMediaTypes">

           <list>

              <value>text/html;charset=UTF-8</value>

              <value>application/json;charset=UTF-8</value>

           </list>

       </property>

    </bean>

    <bean

        class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">

       <property name="messageConverters">

           <list>

              <ref bean="mappingJacksonHttpMessageConverter" />

           </list>

       </property>

    </bean>

 

    <!-- 3、自动扫描 将标注Spring注解的类自动转化Bean -->

    <context:component-scan base-package="com.zldc,com.jointstarc" />

 

    <!-- 上传文件的设置 -->

    <bean id="multipartResolver"

       class="org.springframework.web.multipart.commons.CommonsMultipartResolver">

       <!-- 上传文件总的大小限制 -->

       <property name="maxUploadSize" value="102400000" /> <!-- 60M上限 -->

       <!-- 设置每个上传文件的大小限制 -->

       <property name="maxUploadSizePerFile" value="20480000" /> <!-- 20M上限 -->

    </bean>

</beans>

三、Mybatis配置(mybatis.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>

        <!-- 批量扫描别名 -->

        <package name="com.zldc.yf.dto"/>

        <package name="com.zldc.bs.dto" />

        <package name="com.zldc.system.dto" />

        <package name="com.zldc.gc.dto" />

        <package name="com.zldc.ywfx.bs.dto" />

        <package name="com.zldc.ywfx.yf.dto" />

    </typeAliases>

   

</configuration>

四、Spring-Mybatis配置(spring-mybatis.xml、 jdbc.properties)

spring-mybatis.xml

<?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:aop="http://www.springframework.org/schema/aop"

    xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context"

    xmlns:tx="http://www.springframework.org/schema/tx"

    xsi:schemaLocation="http://www.springframework.org/schema/beans 

        http://www.springframework.org/schema/beans/spring-beans-4.3.xsd 

        http://www.springframework.org/schema/tx 

        http://www.springframework.org/schema/tx/spring-tx-4.3.xsd 

        http://www.springframework.org/schema/aop 

        http://www.springframework.org/schema/aop/spring-aop-4.3.xsd 

        http://www.springframework.org/schema/context 

        http://www.springframework.org/schema/context/spring-context-4.3.xsd 

        http://www.springframework.org/schema/mvc 

        http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd">

 

    <!--1 加载数据资源属性文件 -->

    <bean id="propertyConfigurer"

        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">

       <property name="location" value="classpath:jdbc.properties" />

    </bean>

    <!-- 2 配置数据源 -->

    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"

       destroy-method="close">

       <property name="driverClassName" value="${driver}" />

       <property name="url" value="${url}" />

       <property name="username" value="${username}" />

       <property name="password" value="${password}" />

       <!-- 初始化连接大小 -->

       <property name="initialSize" value="${initialSize}"></property>

       <!-- 连接池最大数量 -->

       <property name="maxActive" value="${maxActive}"></property>

       <!-- 连接池最大空闲 -->

       <property name="maxIdle" value="${maxIdle}"></property>

       <!-- 连接池最小空闲 -->

       <property name="minIdle" value="${minIdle}"></property>

       <!-- 获取连接最大等待时间 -->

       <property name="maxWait" value="${maxWait}"></property>

        <!-- 检测连接是否有效的sql,可以解决启动程序第一次访问慢的原因 -->

        <property name="validationQuery" value="select 1 from dual" />

        <property name="testOnBorrow" value="false"/>

    </bean>

    <!-- 3 配置sessionfactory -->

    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">

       <property name="dataSource" ref="dataSource" />

       <!-- 自动扫描mapping.xml文件 -->

       <property name="mapperLocations" value="classpath:com/zldc/mapper/*.xml" />

       <!-- 扫描实体类的包,为每个实体类注册一个别名,别名为类的名字 -->

       <property name="typeAliasesPackage" value="com.zldc.dto" />

    </bean>

    <!-- 4 装配dao接口 -->

    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">

       <property name="basePackage" value="com.zldc.mapper" /> <!-- DAO接口所在包名,Spring会自动查找其下的类 -->

       <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>

    </bean>

    <!-- 5、声明式事务管理 -->

    <bean id="transactionManager"

       class="org.springframework.jdbc.datasource.DataSourceTransactionManager">

       <property name="dataSource" ref="dataSource" />

    </bean>

    <!-- 6、注解事务切面 -->

    <tx:annotation-driven transaction-manager="transactionManager" />

</beans>

 

jdbc.properties

diver=com.mysql.jdbc.Driver

#测试机

url=jdbc:mysql://127.0.0.1:3306/zldcpt?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC

#UAT

#url=jdbc:mysql://127.0.0.1:3306/zldcpt?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC

#正式机

#url=jdbc:mysql://127.0.0.1:3306/zldcpt?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC

username=root

password=123456

 

 

jdbc.initialSize=5

jdbc.maxActive=20

jdbc.maxIdle=20

jdbc.minIdle=1

jdbc.maxWait=60000

 

五、web配置(web.xml)

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

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

    xmlns="http://java.sun.com/xml/ns/javaee" xmlns:jsp="http://java.sun.com/xml/ns/javaee/jsp"

    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"

    id="WebApp_ID" version="3.0">

 

    <context-param> <!--全局范围内环境参数初始化 -->

       <param-name>contextConfigLocation</param-name>          <!--参数名称 -->

       <param-value>classpath:spring-mybatis.xml</param-value>     <!--参数取值 -->

    </context-param>

    <context-param>

       <param-name>webAppRootKey</param-name>

       <param-value>webApp.root</param-value>

    </context-param>

    <context-param>

       <param-name>log4jConfigLocation</param-name>

       <param-value>classpath:log4j.properties</param-value>

    </context-param>

    <listener>

       <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>

    </listener>

 

    <!--编码过滤器 -->

    <filter>

       <filter-name>encodingFilter</filter-name>

       <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>

       <async-supported>true</async-supported>

       <init-param>

           <param-name>encoding</param-name>

           <param-value>UTF-8</param-value>

       </init-param>

       <init-param>

           <param-name>forceEncoding</param-name>

           <param-value>true</param-value>

       </init-param>

    </filter>

    <filter-mapping>

       <filter-name>encodingFilter</filter-name>

       <url-pattern>/*</url-pattern>

    </filter-mapping>

    <!-- web基础过滤器(自己写的过滤器) -->

    <filter>

       <filter-name>BaseFilter</filter-name>

       <filter-class>com.zldc.common.filter.BaseFilter</filter-class>

    </filter>

    <filter-mapping>

       <filter-name>BaseFilter</filter-name>

       <url-pattern>/*</url-pattern>

    </filter-mapping>

   

    <servlet>

       <servlet-name>SpringMVC</servlet-name>

       <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>

       <init-param>

           <param-name>contextConfigLocation</param-name>

           <param-value>classpath:spring-*.xml</param-value>

       </init-param>

       <load-on-startup>1</load-on-startup>

       <async-supported>true</async-supported>

    </servlet>

    <servlet-mapping>

       <servlet-name>SpringMVC</servlet-name>

       <url-pattern>*.action</url-pattern>

    </servlet-mapping>

 

    <welcome-file-list>

       <welcome-file>/index.jsp</welcome-file>

       <welcome-file>/index.html</welcome-file>

    </welcome-file-list>

 

</web-app>

六、日志配置(log4j.properties)

log4j.rootLogger=debug,console,dailyFile

 

log4j.appender.console=org.apache.log4j.ConsoleAppender

log4j.appender.console.encoding=UTF-8

log4j.appender.console.layout=org.apache.log4j.PatternLayout

log4j.appender.console.layout.ConversionPattern=[%t] - [%p] %m%n

 

# 定期滚动日志文件,每天都会生成日志

log4j.appender.dailyFile=org.apache.log4j.DailyRollingFileAppender

log4j.appender.dailyFile.encoding=UTF-8

log4j.appender.dailyFile.Threshold=DEBUG

log4j.appender.dailyFile.ImmediateFlush=true

log4j.appender.dailyFile.Append = true

log4j.appender.dailyFile.File=D:/logs/portalZL/portalZL.log

log4j.appender.dailyFile.DatePattern='.'yyyy-MM-dd

log4j.appender.dailyFile.layout=org.apache.log4j.PatternLayout

log4j.appender.dailyFile.layout.ConversionPattern=%-d{yyyy-MM-dd HH:mm:ss,SSS} [%t] [%l] - [%p] %m%n

 

#mybatis显示SQL语句日志配置 

#log4j.logger.org.mybatis=DEBUG

#log4j.logger.com.zldc.yf.mapper=DEBUG 

#log4j.logger.com.zldc.bs.mapper=DEBUG

#log4j.logger.com.zldc.gc.mapper=DEBUG

#log4j.logger.com.zldc.system.mapper=DEBUG

 

### 显示 sql ###

log4j.logger.com.ibatis=debug

log4j.logger.com.ibatis.common.jdbc.SimpleDataSource=debug

log4j.logger.com.ibatis.common.jdbc.ScriptRunner=debug

log4j.logger.com.ibatis.sqlmap.engine.impl.SqlMapClientDelegate=debug

log4j.logger.java.sql.Connection=debug

log4j.logger.java.sql.Statement=debug

log4j.logger.java.sql.PreparedStatement=debug

### MCP in Python Usage and Implementation #### Overview of MCP in Python The Model Context Protocol (MCP) is a protocol designed to facilitate interactions between AI models and external tools, data sources, or APIs[^3]. In the context of Python, MCP can be implemented using the MCP Python SDK, which provides tools for building both servers and clients. This implementation allows developers to interact with MCP bridges or agents effectively. #### Installing MCP Python SDK To integrate MCP into Python projects, the MCP Python SDK can be installed via pip: ```bash pip install mcp ``` This command installs the necessary libraries for interacting with MCP servers or clients[^1]. #### Configuring MCP Server in Python A MCP server can be configured in Python by defining its behavior and endpoints. Below is an example of setting up a basic MCP server using Python: ```python from mcp.server import MCPServer def handle_request(data): # Process incoming request data return {"result": "Processed"} if __name__ == "__main__": server = MCPServer(handle_request, port=8080) server.start() ``` In this example, the `MCPServer` class initializes a server that listens on port 8080 and processes incoming requests by calling the `handle_request` function[^1]. #### Configuring MCP Client in Python For interacting with an existing MCP server, a client can be set up as follows: ```python from mcp.client import MCPClient client = MCPClient(mcp_url="http://localhost:8080", mcp_port=8080) response = client.send_request({"action": "fetch_data"}) print(response) ``` Here, the `MCPClient` sends a request to the MCP server at the specified URL and port, and retrieves the response[^2]. #### Advanced Configuration Options MCP servers and clients can be further customized with additional parameters such as JSON formatting, logging levels, and security settings. For instance: ```python client = MCPClient( mcp_url="http://localhost:8080", mcp_port=8080, hide_json=True, json_width=120 ) ``` This configuration hides JSON results from tool executions and sets the maximum width for JSON output to 120 characters. #### Integration with Databases MCP can also be integrated with databases to enhance data retrieval and model interaction. This approach offers advantages over traditional RAG methods by providing more efficient and precise data access[^4]. An example of integrating MCP with a database might look like this: ```python from mcp.server import MCPServer import sqlite3 def fetch_data_from_db(query): conn = sqlite3.connect("example.db") cursor = conn.cursor() cursor.execute(query) result = cursor.fetchall() conn.close() return result def handle_request(data): query = data.get("query") if query: return {"data": fetch_data_from_db(query)} return {"error": "No query provided"} if __name__ == "__main__": server = MCPServer(handle_request, port=8080) server.start() ``` This script sets up an MCP server that executes SQL queries against a SQLite database[^4]. #### Best Practices for MCP Implementation - Ensure secure communication between MCP clients and servers using authentication mechanisms. - Optimize performance by configuring appropriate logging levels and resource limits. - Test the MCP implementation thoroughly to handle edge cases and errors gracefully.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值