SSM项目实战

创建一个maven工程,在pom.xml中配置需要的jar包

<?xml version="1.0" encoding="UTF-8"?>
<!--
  Licensed to the Apache Software Foundation (ASF) under one
  or more contributor license agreements.  See the NOTICE file
  distributed with this work for additional information
  regarding copyright ownership.  The ASF licenses this file
  to you under the Apache License, Version 2.0 (the
  "License"); you may not use this file except in compliance
  with the License.  You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing,
  software distributed under the License is distributed on an
  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  KIND, either express or implied.  See the License for the
  specific language governing permissions and limitations
  under the License.
-->
<!-- $Id: pom.xml 642118 2008-03-28 08:04:16Z reinhard $ -->
<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>
  <packaging>war</packaging>

  <name>SSM</name>
  <groupId>com</groupId>
  <artifactId>SSM</artifactId>
  <version>1.0-SNAPSHOT</version>

  <build>
    <plugins>
      <plugin>
        <groupId>org.mortbay.jetty</groupId>
        <artifactId>maven-jetty-plugin</artifactId>
        <version>6.1.7</version>
        <configuration>
          <connectors>
            <connector implementation="org.mortbay.jetty.nio.SelectChannelConnector">
              <port>8888</port>
              <maxIdleTime>30000</maxIdleTime>
            </connector>
          </connectors>
          <webAppSourceDirectory>${project.build.directory}/${pom.artifactId}-${pom.version}</webAppSourceDirectory>
          <contextPath>/</contextPath>
        </configuration>
      </plugin>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <configuration>
          <source>6</source>
          <target>6</target>
        </configuration>
      </plugin>
    </plugins>
  </build>

  <dependencies>

    <!--spring相关-->

    <!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->

    <dependency>

      <groupId>org.springframework</groupId>

      <artifactId>spring-context</artifactId>

      <version>4.3.18.RELEASE</version>

    </dependency>



    <!-- https://mvnrepository.com/artifact/org.springframework/spring-core -->

    <dependency>

      <groupId>org.springframework</groupId>

      <artifactId>spring-core</artifactId>

      <version>4.3.18.RELEASE</version>

    </dependency>



    <!-- https://mvnrepository.com/artifact/org.springframework/spring-beans -->

    <dependency>

      <groupId>org.springframework</groupId>

      <artifactId>spring-beans</artifactId>

      <version>4.3.18.RELEASE</version>

    </dependency>



    <!-- https://mvnrepository.com/artifact/org.springframework/spring-web -->

    <dependency>

      <groupId>org.springframework</groupId>

      <artifactId>spring-web</artifactId>

      <version>4.3.18.RELEASE</version>

    </dependency>



    <!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->

    <dependency>

      <groupId>org.springframework</groupId>

      <artifactId>spring-webmvc</artifactId>

      <version>4.3.18.RELEASE</version>

    </dependency>

    <!--mybatis-->

    <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->

    <dependency>

      <groupId>org.mybatis</groupId>

      <artifactId>mybatis</artifactId>

      <version>3.4.6</version>

    </dependency>



    <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->

    <dependency>

      <groupId>mysql</groupId>

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

      <version>8.0.18</version>

    </dependency>

    <!--数据库事务管理-->

    <!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->

    <dependency>

      <groupId>org.springframework</groupId>

      <artifactId>spring-jdbc</artifactId>

      <version>4.3.18.RELEASE</version>

    </dependency>



    <!-- https://mvnrepository.com/artifact/org.springframework/spring-tx -->

    <dependency>

      <groupId>org.springframework</groupId>

      <artifactId>spring-tx</artifactId>

      <version>4.3.18.RELEASE</version>

    </dependency>

    <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring -->

    <dependency>

      <groupId>org.mybatis</groupId>

      <artifactId>mybatis-spring</artifactId>

      <version>1.3.2</version>

    </dependency>

    <!--jsp-->

    <!-- https://mvnrepository.com/artifact/javax.servlet/jstl -->

    <dependency>

      <groupId>javax.servlet</groupId>

      <artifactId>jstl</artifactId>

      <version>1.2</version>

    </dependency>



    <!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->

    <dependency>

      <groupId>javax.servlet</groupId>

      <artifactId>javax.servlet-api</artifactId>

      <version>3.1.0</version>

      <scope>provided</scope>

    </dependency>

  </dependencies>

</project>

 

 

编写web.xml配置文件

<?xml version="1.0" encoding="UTF-8"?>
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->

<!--
- This is the Cocoon web-app configurations file
-
- $Id$
-->
<web-app version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

<!-- Servlet Filters ================================================ -->

<!--
- Declare a filter for multipart MIME handling
-->

<!-- 过滤器 解决表单post提交乱码问题 -->
<filter>
<filter-name>encoding</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>encoding</filter-name>
<!-- 拦截全部 /* -->
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- 配置监听器 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<!--
- Declare Spring request listener which sets up the required RequestAttributes
- to support Springs and Cocoon custom bean scopes like the request scope or the
- session scope.
-->
<listener>
<listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
</listener>

<!-- Servlet Configuration ========================================== -->

<!--
- Servlet that dispatches requests to the Spring managed block servlets
-->
<servlet>
<display-name>DispatcherServlet</display-name>
<servlet-name>DispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>

<!-- URL space mappings ============================================= -->

<!--
- Cocoon handles all the URL space assigned to the webapp using its sitemap.
- It is recommended to leave it unchanged. Under some circumstances though
- (like integration with proprietary webapps or servlets) you might have
- to change this parameter.
-->
<servlet-mapping>
<servlet-name>DispatcherServlet</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>

</web-app>

编写springmvc配置文件springmvc.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:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-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/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd">
        
        <!-- 开启注解扫描 -->
        <context:component-scan base-package="Controller"></context:component-scan>
        
        <!-- 配置视图解析器  配置viewName 前缀与后缀 -->
        <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
            <property name="prefix" value="/pages/"/>
            <property name="suffix" value=".jsp"/>
        </bean>
        
</beans>

编写数据库连接池配置文件dp.properties

dbc.driverClass=com.mysql.cj.jdbc.Driver
jdbc.jdbcUrl=jdbc:mysql://localhost:3306/new_database?serverTimezone=UTC&useSSL=false
jdbc.user=root
jdbc.password=root

 

编写配置文件applicationContext.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:context="http://www.springframework.org/schema/context"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-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/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">

        <context:component-scan base-package="Service"/>

        <!-- 读取配置文件 数据库 -->
        <context:property-placeholder location="classpath:db.properties"/>
        
        <!-- 配置连接池 -->
    <bean name="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/new_database?serverTimezone=UTC"/>
        <property name="username" value="root"/>
        <property name="password" value="root}"/>
    </bean>
    <!--    Spring整合mybatis    -->
    <bean id="sessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
    </bean>
    <!--配置扫描Mapper所在的包  -->
    <bean id="mapperScannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="sqlSessionFactory" ref="sessionFactory"/>
        <property name="basePackage" value="Mapper"/>
    </bean>
    <!--配置声明式事务管理    -->
    <!--平台事务管理    -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>
    <!--配置事务的通知-->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="find" read-only="true"/>
            <tx:method name="*"/>
        </tx:attributes>
    </tx:advice>
    <!--配置事务的增强-->
    <aop:config>
        <aop:advisor advice-ref="txAdvice" pointcut="execution(public * Service.*ServiceImpl.*(..))"></aop:advisor>
    </aop:config>
</beans>

 编写Mapper类

package Mapper;

import java.util.List;

import Entity.News;

public interface NewsMapper {

    public void addNews(News news);

    public void deleteNews(Integer id);

    public void updateNews(News news);

    public  News queryNewsById(Integer id);

    public List<News> queryNews();
}
<?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 namespace="com.SSM.Mapper">
      <select id="queryNews" resultType="News">
          SELECT * FROM news
      </select>

    <select id="selectById" parameterType="Integer" resultType="News">
        SELECT * FROM news WHERE id = #{id}
    </select>


    <delete id="deleteNews" parameterType="Integer">
        DELETE FROM item_info WHERE item_id = #{id}
    </delete>
    

    <insert id="addNews" parameterType="News">
        INSERT INTO item_info VALUES(
            #{title},
            #{content},
            #{author},
            #{date}
        )
    </insert>
    
<update id="updateNews" parameterMap="News">
        UPDATE news SET
        title=#{title},
        content=#{content},
        author=#{author},
        date=#{date}
</update>
    
  </mapper>

 

修改Service类

 

package Service.Impl;
import Entity.News;
import Mapper.NewsMapper;
import Service.NewsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
@Service
public class NewsServiceImpl implements NewsService {
@Autowired
private NewsMapper newsMapper ;


@Override
public void addNews(News news) {
newsMapper.addNews(news);
}


@Override
public void deleteNews(Integer id) {
newsMapper.deleteNews(id);
}

@Override
public void updateNews(News news) {
newsMapper.updateNews(news);
}

@Override
public News queryNewsById(Integer id) {
return newsMapper.queryNewsById(id);
}

@Override
public List<News> queryNews() {
return newsMapper.queryNews();
}
}

 

修改Controller类

package Controller;

import Entity.News;
import Service.Impl.NewsServiceImpl;
import Service.NewsService;
import Utils.WebUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@Controller
@RequestMapping("/news")
public class NewsController extends BaseServlet {
    private Service.NewsService NewsService = new NewsServiceImpl();

    @RequestMapping("/add.do")
    protected void add(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        News News = WebUtils.copyParamToBean(req.getParameterMap(),new News());
        NewsService.addNews(News);
        resp.sendRedirect(req.getContextPath() + "/Controller.NewsServlet?action=list");

    }


    @RequestMapping("/delete.do")
    protected void delete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int id = WebUtils.parseInt(req.getParameter("id"), 0);
        NewsService.deleteNewsById(id);
        resp.sendRedirect(req.getContextPath() + "/Controller.NewsServlet?action=list");
    }


    @RequestMapping("/update.do")
    protected void update(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        News News = WebUtils.copyParamToBean(req.getParameterMap(),new News());
        NewsService.updateNews(News);
        resp.sendRedirect(req.getContextPath() + "/Controller.NewsServlet?action=list");
    }

    @RequestMapping("/getNews.do")
    protected void getNews(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int id = WebUtils.parseInt(req.getParameter("id"), 0);
        News News = NewsService.queryNewsById(id);
        req.setAttribute("News", News) ;
        req.getRequestDispatcher("/pages/news_edit.jsp").forward(req,resp);
    }


    @RequestMapping("/list.do")
    protected void list(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        List<News> News = NewsService.queryNews();
        req.setAttribute("News", News);
        req.getRequestDispatcher("/pages/news_manager.jsp").forward(req,resp);
        System.out.println(News);
    }

}

 码云地址:https://gitee.com/ioklkiol/javaee_second_job/tree/master/SSM

posted on 2020-06-27 15:00  空理彷徨的程序世界  阅读(232)  评论(0)    收藏  举报

导航