zoukankan      html  css  js  c++  java
  • SpringMVC+Spring+mybatis 项目实践

    SpringMVC+Spring+mybatis 项目实践

    一、配置环境

     勾选Create from archetype

    选择自己下载的maven地址,点击+号添加archetypeCatalog

    配置pom.xml文件

      1 <?xml version="1.0" encoding="UTF-8"?>
      2 
      3 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      4   xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
      5   <modelVersion>4.0.0</modelVersion>
      6 
      7   <groupId>org.example</groupId>
      8   <artifactId>ssm</artifactId>
      9   <version>1.0-SNAPSHOT</version>
     10   <packaging>war</packaging>
     11 
     12   <name>ssm Maven Webapp</name>
     13   <!-- FIXME change it to the project's website -->
     14   <url>http://www.example.com</url>
     15 
     16   <!-- 提取版本属性 -->
     17   <properties>
     18     <spring.version>4.2.4.RELEASE</spring.version>
     19     <mybatis.version>3.2.8</mybatis.version>
     20     <mybatis.spring.version>1.2.2</mybatis.spring.version>
     21     <slf4j.version>1.6.4</slf4j.version>
     22     <log4j.version>1.2.17</log4j.version>
     23     <jackson.version>2.4.2</jackson.version>
     24     <druid.version>1.0.9</druid.version>
     25     <sqlserver.version>10.50.4000</sqlserver.version>
     26     <jstl.version>1.2</jstl.version>
     27     <servlet-api.version>2.5</servlet-api.version>
     28     <jsp-api.version>2.0</jsp-api.version>
     29     <commons-io.version>1.3.2</commons-io.version>
     30     <commons-fileupload.version>1.3.1</commons-fileupload.version>
     31   </properties>
     32 
     33   <dependencies>
     34     <dependency>
     35       <groupId>junit</groupId>
     36       <artifactId>junit</artifactId>
     37       <version>4.11</version>
     38       <scope>test</scope>
     39     </dependency>
     40   </dependencies>
     41 
     42 
     43   <!-- 版本锁定 -->
     44   <dependencyManagement>
     45     <dependencies>
     46       <!-- Spring -->
     47       <dependency>
     48         <groupId>org.springframework</groupId>
     49         <artifactId>spring-context</artifactId>
     50         <version>${spring.version}</version>
     51       </dependency>
     52       <dependency>
     53         <groupId>org.springframework</groupId>
     54         <artifactId>spring-beans</artifactId>
     55         <version>${spring.version}</version>
     56       </dependency>
     57       <dependency>
     58         <groupId>org.springframework</groupId>
     59         <artifactId>spring-webmvc</artifactId>
     60         <version>${spring.version}</version>
     61       </dependency>
     62       <dependency>
     63         <groupId>org.springframework</groupId>
     64         <artifactId>spring-jdbc</artifactId>
     65         <version>${spring.version}</version>
     66       </dependency>
     67       <dependency>
     68         <groupId>org.springframework</groupId>
     69         <artifactId>spring-aspects</artifactId>
     70         <version>${spring.version}</version>
     71       </dependency>
     72       <dependency>
     73         <groupId>org.springframework</groupId>
     74         <artifactId>spring-jms</artifactId>
     75         <version>${spring.version}</version>
     76       </dependency>
     77       <dependency>
     78         <groupId>org.springframework</groupId>
     79         <artifactId>spring-context-support</artifactId>
     80         <version>${spring.version}</version>
     81       </dependency>
     82 
     83       <!-- Mybatis -->
     84       <dependency>
     85         <groupId>org.mybatis</groupId>
     86         <artifactId>mybatis</artifactId>
     87         <version>${mybatis.version}</version>
     88       </dependency>
     89       <dependency>
     90         <groupId>org.mybatis</groupId>
     91         <artifactId>mybatis-spring</artifactId>
     92         <version>${mybatis.spring.version}</version>
     93       </dependency>
     94 
     95       <!-- 日志处理 -->
     96       <dependency>
     97         <groupId>org.slf4j</groupId>
     98         <artifactId>slf4j-log4j12</artifactId>
     99         <version>${slf4j.version}</version>
    100       </dependency>
    101       <dependency>
    102         <groupId>log4j</groupId>
    103         <artifactId>log4j</artifactId>
    104         <version>${log4j.version}</version>
    105       </dependency>
    106 
    107       <!-- Jackson Json处理工具包 -->
    108       <dependency>
    109         <groupId>com.fasterxml.jackson.core</groupId>
    110         <artifactId>jackson-databind</artifactId>
    111         <version>${jackson.version}</version>
    112       </dependency>
    113 
    114       <!-- 连接池 -->
    115       <dependency>
    116         <groupId>com.alibaba</groupId>
    117         <artifactId>druid</artifactId>
    118         <version>${druid.version}</version>
    119       </dependency>
    120 
    121       <!-- MySql -->
    122       <dependency>
    123         <groupId>sqlserver</groupId>
    124         <artifactId>sqljdbc4-java</artifactId>
    125         <version>${sqlserver.version}</version>
    126       </dependency>
    127 
    128       <!-- io包 -->
    129       <dependency>
    130         <groupId>org.apache.commons</groupId>
    131         <artifactId>commons-io</artifactId>
    132         <version>${commons-io.version}</version>
    133       </dependency>
    134 
    135       <!-- 文件上传组件 -->
    136       <dependency>
    137         <groupId>commons-fileupload</groupId>
    138         <artifactId>commons-fileupload</artifactId>
    139         <version>${commons-fileupload.version}</version>
    140       </dependency>
    141 
    142       <!-- JSP相关 -->
    143       <dependency>
    144         <groupId>jstl</groupId>
    145         <artifactId>jstl</artifactId>
    146         <version>${jstl.version}</version>
    147       </dependency>
    148       <dependency>
    149         <groupId>javax.servlet</groupId>
    150         <artifactId>servlet-api</artifactId>
    151         <version>${servlet-api.version}</version>
    152         <scope>provided</scope>
    153       </dependency>
    154       <dependency>
    155         <groupId>javax.servlet</groupId>
    156         <artifactId>jsp-api</artifactId>
    157         <version>${jsp-api.version}</version>
    158         <scope>provided</scope>
    159       </dependency>
    160     </dependencies>
    161   </dependencyManagement>
    162 
    163   <build>
    164     
    178     <!--配置资源文件映射 -->
    179     <resources>
    180       <resource>
    181         <directory>src/main/java</directory>
    182         <includes>
    183           <include>**/*.xml</include>
    184         </includes>
    185         <filtering>false</filtering>
    186       </resource>
    187 
    188       <resource>
    189         <directory>src/main/resources</directory>
    190         <includes>
    191           <include>**/*.properties</include>
    192           <include>**/*.xml</include>
    193         </includes>
    194         <filtering>false</filtering>
    195       </resource>
    196     </resources>
    197 
    198   </build>
    199 
    200   <build>
    201     <finalName>ssm</finalName>
    202     <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
    203       <plugins>
    204         <plugin>
    205           <artifactId>maven-clean-plugin</artifactId>
    206           <version>3.1.0</version>
    207         </plugin>
    208         <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
    209         <plugin>
    210           <artifactId>maven-resources-plugin</artifactId>
    211           <version>3.0.2</version>
    212         </plugin>
    213         <plugin>
    214           <artifactId>maven-compiler-plugin</artifactId>
    215           <version>3.8.0</version>
    216         </plugin>
    217         <plugin>
    218           <artifactId>maven-surefire-plugin</artifactId>
    219           <version>2.22.1</version>
    220         </plugin>
    221         <plugin>
    222           <artifactId>maven-war-plugin</artifactId>
    223           <version>3.2.2</version>
    224         </plugin>
    225         <plugin>
    226           <artifactId>maven-install-plugin</artifactId>
    227           <version>2.5.2</version>
    228         </plugin>
    229         <plugin>
    230           <artifactId>maven-deploy-plugin</artifactId>
    231           <version>2.8.2</version>
    232         </plugin>
    233       </plugins>
    234     </pluginManagement>
    235   </build>
    236 </project>

    新建resources文件夹, 创建之后,选择Recourses,点击Apply

    配置applicationContext.xml

     1 <?xml version="1.0" encoding="UTF-8"?>
     2 <beans xmlns="http://www.springframework.org/schema/beans"
     3        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     4        xmlns:context="http://www.springframework.org/schema/context"
     5        xmlns:aop="http://www.springframework.org/schema/aop"
     6        xmlns:tx="http://www.springframework.org/schema/tx"
     7        xsi:schemaLocation="http://www.springframework.org/schema/beans
     8     http://www.springframework.org/schema/beans/spring-beans.xsd
     9     http://www.springframework.org/schema/context
    10     http://www.springframework.org/schema/context/spring-context.xsd
    11     http://www.springframework.org/schema/aop
    12     http://www.springframework.org/schema/aop/spring-aop.xsd
    13     http://www.springframework.org/schema/tx
    14     http://www.springframework.org/schema/tx/spring-tx.xsd">
    15 
    16     <!--开启注解的扫描,希望处理service和dao,controller不需要Spring框架去处理-->
    17     <context:component-scan base-package="com" >
    18         <!--配置哪些注解不扫描-->
    19         <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" />
    20     </context:component-scan>
    21 
    22 </beans>
    applicationContext.xml

    添加springmvc.xml

    
    
    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="
    http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/mvc
    http://www.springframework.org/schema/mvc/spring-mvc.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context.xsd">
    <!--开启注解扫描,只扫描Controller注解-->
    <context:component-scan base-package="com">
    <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>

    <!--Spring整合MyBatis框架-->
    <!--配置连接池-->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="com.microsoft.sqlserver.jdbc.SQLServerDriver"/>
    <property name="url" value="jdbc:sqlserver://localhost:3306/ssm"/>
    <property name="username" value="sa"/>
    <property name="password" value="123456cyl"/>
    </bean>

    <!--配置SqlSessionFactory工厂-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    <property name="dataSource" ref="dataSource" />
    </bean>

    <!--配置Dao接口所在包-->
    <bean id="mapperScanner" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    <property name="basePackage" value="com.DAL"/>
    </bean>

    <!--配置Spring框架声明式事务管理-->
    <!--配置事务管理器-->
    <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="*" isolation="DEFAULT"/>
    </tx:attributes>
    </tx:advice>

    <!--配置AOP增强-->
    <aop:config>
    <aop:advisor advice-ref="txAdvice" pointcut="execution(* com.Service.impl.*ServiceImpl.*(..))"/>
    </aop:config>
    </beans>
     

    配置web.xml

     1 <?xml version="1.0" encoding="UTF-8"?>
     2 <web-app xmlns="http://java.sun.com/xml/ns/javaee"
     3          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     4          xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
     5           http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
     6          version="2.5">
     7 
     8   <display-name>ssm</display-name>
     9 
    10   <welcome-file-list>
    11     <welcome-file>index.jsp</welcome-file>
    12   </welcome-file-list>
    13 
    14   <!-- 配置Spring的监听器 -->
    15   <listener>
    16     <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    17   </listener>
    18   <!-- 配置加载类路径的配置文件 -->
    19   <context-param>
    20     <param-name>contextConfigLocation</param-name>
    21     <param-value>classpath:applicationContext.xml</param-value>
    22   </context-param>
    23 
    24 
    25   <!-- 配置前端控制器:服务器启动必须加载,需要加载springmvc.xml配置文件 -->
    26   <servlet>
    27     <servlet-name>dispatcherServlet</servlet-name>
    28     <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    29     <!-- 配置初始化参数,创建完DispatcherServlet对象,加载springmvc.xml配置文件 -->
    30     <init-param>
    31       <param-name>contextConfigLocation</param-name>
    32       <param-value>classpath:springmvc.xml</param-value>
    33     </init-param>
    34     <!-- 服务器启动的时候,让DispatcherServlet对象创建 -->
    35     <load-on-startup>1</load-on-startup>
    36   </servlet>
    37   <servlet-mapping>
    38     <servlet-name>dispatcherServlet</servlet-name>
    39     <url-pattern>/</url-pattern>
    40   </servlet-mapping>
    41 
    42   <!--解决中文乱码的过滤器-->
    43   <filter>
    44     <filter-name>characterEncodingFilter</filter-name>
    45     <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    46     <init-param>
    47       <param-name>encoding</param-name>
    48       <param-value>UTF-8</param-value>
    49     </init-param>
    50   </filter>
    51   <filter-mapping>
    52     <filter-name>characterEncodingFilter</filter-name>
    53     <url-pattern>/*</url-pattern>
    54   </filter-mapping>
    55 
    56   <filter>
    57     <filter-name>indexFilter</filter-name>
    58     <filter-class>com.zero.controller.IndexFilter</filter-class>
    59   </filter>
    60   <filter-mapping>
    61     <filter-name>indexFilter</filter-name>
    62     <url-pattern>/index.jsp</url-pattern>
    63   </filter-mapping>
    64 
    65 </web-app>
    web.xml

    二、整合项目代码

    1.把原项目的代码复制到现项目,Service,DAL,Entity的和原来一样,只是需要把Controller中的代码修改一下

      1 package com.Controller;
      2 
      3 import com.Entity.News;
      4 import com.Service.NewsService;
      5 import org.apache.commons.beanutils.BeanUtils;
      6 import org.springframework.beans.factory.annotation.Autowired;
      7 import org.springframework.stereotype.Controller;
      8 import org.springframework.web.bind.annotation.RequestMapping;
      9 import javax.servlet.FilterChain;
     10 import javax.servlet.ServletContext;
     11 import javax.servlet.ServletException;
     12 import javax.servlet.http.HttpServletRequest;
     13 import javax.servlet.http.HttpServletResponse;
     14 import java.io.IOException;
     15 import java.lang.reflect.InvocationTargetException;
     16 import java.sql.Date;
     17 import java.sql.SQLException;
     18 import java.text.ParseException;
     19 import java.text.SimpleDateFormat;
     20 import java.util.List;
     21 import java.util.Map;
     22 
     23 public class NewsController {
     24 
     25     @RequestMapping("/Add")
     26     protected void Add(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, java.io.IOException {
     27 
     28         request.setCharacterEncoding("utf-8");
     29         response.sendRedirect("AddNews.jsp");
     30     }
     31 
     32 
     33     @RequestMapping("/AddNews")
     34     protected void AddNews(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
     35 
     36         request.setCharacterEncoding("utf-8");
     37         News news = new News();
     38         news.setCategory(request.getParameter("category"));
     39         news.setTitle(request.getParameter("title"));
     40         news.setContents(request.getParameter("contents"));
     41         news.setAuthor(request.getParameter("author"));
     42        /* String newsDate=request.getParameter("newsdate");
     43         SimpleDateFormat sDateFormat=new SimpleDateFormat("yyyy-MM-dd"); //加上时间
     44         Date date= null;
     45         try {
     46             date = sDateFormat.parse(newsDate);
     47         } catch (ParseException e) {
     48             e.printStackTrace();
     49         }*/
     50         news.setNewsdate(Date.valueOf(request.getParameter("newsdate")));
     51         NewsService service = new NewsService();
     52         service.AddNews(news);
     53         request.getRequestDispatcher("ShowNewsListServlet").forward(request, response);
     54     }
     55 
     56     @RequestMapping("/DeleteNews")
     57     protected void DeleteNews(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
     58     {
     59 
     60         int newsid=Integer.valueOf( request.getParameter("newsid"));
     61         NewsService service= new NewsService();
     62         service.DeleteNews(newsid);
     63         request.getRequestDispatcher("ShowNewsListServlet").forward(request,response);
     64     }
     65 
     66     @RequestMapping("/ViewNews")
     67     protected void ViewNews(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
     68     {
     69 
     70         response.setContentType(("text/html;charset=UTF-8"));
     71         request.setCharacterEncoding("UTF-8");
     72         int id = Integer.parseInt(request.getParameter("newsid"));
     73         System.out.println(id);
     74         NewsService service = new NewsService();
     75         try
     76         {
     77             News news = service.GetNews(id);
     78             request.setAttribute("news",news);
     79             request.getRequestDispatcher("ViewNews.jsp").forward(request,response);
     80         }
     81         catch (SQLException e)
     82         {
     83             e.printStackTrace();
     84         }
     85 
     86     }
     87 
     88     @RequestMapping("/ShowNews")
     89     protected void ShowNews(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
     90     {
     91 
     92         NewsService newsService = new NewsService();
     93         try{
     94             List<News> listNews  = newsService.QueryNews();
     95             request.setAttribute("listNews",listNews);
     96             request.getRequestDispatcher("ShowNewsList.jsp").forward(request,response);
     97         }catch (SQLException e)
     98         {
     99             e.printStackTrace();
    100         }
    101     }
    102 
    103     @RequestMapping("/SaveNews")
    104     protected void SaveNews(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    105 
    106         request.setCharacterEncoding("utf-8");
    107         News news=new News ();
    108         news.setNewsid(Integer.valueOf( request.getParameter("newsid")));
    109         news.setCategory(request.getParameter("category"));
    110         news.setTitle(request.getParameter("title"));
    111         news.setAuthor(request.getParameter("author"));
    112         String newsDate=request.getParameter("newsdate");
    113         SimpleDateFormat sDateFormat=new SimpleDateFormat("yyyy-MM-dd"); //加上时间
    114         java.util.Date date= null;
    115         try {
    116             date = sDateFormat.parse(newsDate);
    117         } catch (ParseException e) {
    118             e.printStackTrace();
    119         }
    120         news.setNewsdate(date);
    121         news.setContents(request.getParameter("contents"));
    122         NewsService service=new NewsService();
    123         System.out.println(service.UpdateNews(news));
    124         request.getRequestDispatcher("ShowNewsListServlet").forward(request,response);
    125 
    126     }
    127 
    128     @RequestMapping("/EditNews")
    129     protected void EditNews(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    130     {
    131 
    132         request.setCharacterEncoding("UTF-8");
    133         int newsid=Integer.valueOf( request.getParameter("newsid"));
    134         System.out.println("newsID:"+newsid);
    135         NewsService service= new NewsService();
    136         try {
    137             News news=service.GetNews(newsid);
    138             request.setAttribute("news", news);
    139             request.getRequestDispatcher("EditNews.jsp").forward(request,response);
    140         } catch (SQLException e) {
    141             e.printStackTrace();
    142         }
    143     }
    144 
    145 }
    NewsController
     1 package com.Controller;
     2 
     3 import com.Entity.Users;
     4 import com.Service.UsersService;
     5 
     6 import org.springframework.beans.factory.annotation.Autowired;
     7 import org.springframework.stereotype.Controller;
     8 import org.springframework.web.bind.annotation.RequestMapping;
     9 
    10 import javax.servlet.ServletException;
    11 import javax.servlet.http.Cookie;
    12 import javax.servlet.http.HttpServletRequest;
    13 import javax.servlet.http.HttpServletResponse;
    14 import javax.servlet.http.HttpSession;
    15 import java.io.IOException;
    16 import java.io.PrintWriter;
    17 
    18 
    19 public class UserController {
    20 
    21 
    22     @RequestMapping("/Login")
    23     protected void Login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    24     {
    25         response.setContentType("text/html; charset=UTF-8");
    26         request.setCharacterEncoding("UTF-8");
    27         PrintWriter out = response.getWriter();
    28         Users user = new Users();
    29         user.setUsername(request.getParameter("txtName"));
    30         user.setPassword(request.getParameter("txtPwd"));
    31         UsersService userService = new UsersService();
    32         if(userService.QueryUser(user))
    33         {
    34             Cookie cookieUserName = new Cookie("username", user.getUsername());//创建一个键值对的cookie对象
    35             cookieUserName.setMaxAge(60*60*24*30);//设置cookie的生命周期
    36             response.addCookie(cookieUserName);//添加到response中
    37 
    38             Cookie cookiePwd= new Cookie("password", user.getPassword());//创建一个键值对的cookie对象
    39             cookiePwd.setMaxAge(60*60*24*30);//设置cookie的生命周期
    40             response.addCookie(cookiePwd);//添加到response中
    41 
    42             HttpSession session = request.getSession(true);
    43 
    44             response.sendRedirect("page/index.html");
    45 
    46         }
    47 
    48         else{
    49             out.println("错误的用户名和密码");
    50 
    51         }
    52 
    53     }
    54 }
    UserController

    2.配置Tomcat并运行

     

    三、GitHub地址

    https://github.com/youthcyl/SSM

  • 相关阅读:
    报错Required String parameter 'customerInfo' is not present的原因及处理办法
    Mybatis 中$与#的区别
    ON DUPLICATE KEY UPDATE单个增加更新及批量增加更新的sql
    Git使用
    前后端分离
    对excel文件的读取
    POI导入和导出Excel总结
    git权限
    @RequestParam与@PathVariable
    lombok学习
  • 原文地址:https://www.cnblogs.com/youthlll/p/13196671.html
Copyright © 2011-2022 走看看