SpringMVC+Spring+mybatis 项目实践

码云地址:https://gitee.com/ZeroLuo328/java2enews.git 

注意是javaEESSM这个项目文件

 

创建项目,并整合ssm

SpringMVC+Spring+mybatis 项目实践_第1张图片

 

SpringMVC+Spring+mybatis 项目实践_第2张图片

 

 项目结构:

SpringMVC+Spring+mybatis 项目实践_第3张图片

将MVCModel2的网页资源copy过来

SpringMVC+Spring+mybatis 项目实践_第4张图片

 

导入要用到的包的坐标

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

<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/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0modelVersion>

  <groupId>com.zerogroupId>
  <artifactId>javaEESSMartifactId>
  <version>1.0-SNAPSHOTversion>
  <packaging>warpackaging>

  <name>javaEESSM Maven Webappname>
  
  <url>http://www.example.comurl>

  <properties>
    <project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
    <maven.compiler.source>1.7maven.compiler.source>
    <maven.compiler.target>1.7maven.compiler.target>
    <spring.version>5.0.2.RELEASEspring.version>
    <slf4j.version>1.6.6slf4j.version>
    <log4j.version>1.2.12log4j.version>
    <mysql.version>5.1.6mysql.version>
    <mybatis.version>3.4.5mybatis.version>
  properties>

  <dependencies>
    <dependency>
      <groupId>junitgroupId>
      <artifactId>junitartifactId>
      <version>4.11version>
      <scope>testscope>
    dependency>

    
    <dependency>
      <groupId>org.aspectjgroupId>
      <artifactId>aspectjweaverartifactId>
      <version>1.6.8version>
    dependency>

    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-aopartifactId>
      <version>${spring.version}version>
    dependency>

    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-contextartifactId>
      <version>${spring.version}version>
    dependency>


    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-webartifactId>
      <version>${spring.version}version>
    dependency>

    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-webmvcartifactId>
      <version>${spring.version}version>
    dependency>

    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-testartifactId>
      <version>${spring.version}version>
    dependency>

    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-txartifactId>
      <version>${spring.version}version>
    dependency>

    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-jdbcartifactId>
      <version>${spring.version}version>
    dependency>

    <dependency>
      <groupId>junitgroupId>
      <artifactId>junitartifactId>
      <version>4.12version>
      <scope>testscope>
    dependency>

    <dependency>
      <groupId>mysqlgroupId>
      <artifactId>mysql-connector-javaartifactId>
      <version>${mysql.version}version>
    dependency>

    <dependency>
      <groupId>javax.servletgroupId>
      <artifactId>servlet-apiartifactId>
      <version>2.5version>
      <scope>providedscope>
    dependency>

    <dependency>
      <groupId>javax.servlet.jspgroupId>
      <artifactId>jsp-apiartifactId>
      <version>2.0version>
      <scope>providedscope>
    dependency>

    <dependency>
      <groupId>jstlgroupId>
      <artifactId>jstlartifactId>
      <version>1.2version>
    dependency>

    
    <dependency>
      <groupId>log4jgroupId>
      <artifactId>log4jartifactId>
      <version>${log4j.version}version>
    dependency>

    <dependency>
      <groupId>org.slf4jgroupId>
      <artifactId>slf4j-apiartifactId>
      <version>${slf4j.version}version>
    dependency>

    <dependency>
      <groupId>org.slf4jgroupId>
      <artifactId>slf4j-log4j12artifactId>
      <version>${slf4j.version}version>
    dependency>
    
    <dependency>
      <groupId>org.mybatisgroupId>
      <artifactId>mybatisartifactId>
      <version>${mybatis.version}version>
    dependency>

    <dependency>
      <groupId>org.mybatisgroupId>
      <artifactId>mybatis-springartifactId>
      <version>1.3.0version>
    dependency>

    <dependency>
      <groupId>commons-beanutilsgroupId>
      <artifactId>commons-beanutilsartifactId>
      <version>1.8.0version>
    dependency>

  dependencies>

  <build>
    <finalName>javaEESSMfinalName>
    <pluginManagement>
      <plugins>
        <plugin>
          <artifactId>maven-clean-pluginartifactId>
          <version>3.1.0version>
        plugin>
        
        <plugin>
          <artifactId>maven-resources-pluginartifactId>
          <version>3.0.2version>
        plugin>
        <plugin>
          <artifactId>maven-compiler-pluginartifactId>
          <version>3.8.0version>
        plugin>
        <plugin>
          <artifactId>maven-surefire-pluginartifactId>
          <version>2.22.1version>
        plugin>
        <plugin>
          <artifactId>maven-war-pluginartifactId>
          <version>3.2.2version>
        plugin>
        <plugin>
          <artifactId>maven-install-pluginartifactId>
          <version>2.5.2version>
        plugin>
        <plugin>
          <artifactId>maven-deploy-pluginartifactId>
          <version>2.8.2version>
        plugin>
      plugins>
    pluginManagement>
  build>
project>
pom.xml

 

创建spring的配置文件applicationContext.xml,并整合SpringMVC和Mybatis

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:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context.xsd
    http://www.springframework.org/schema/aop
    http://www.springframework.org/schema/aop/spring-aop.xsd
    http://www.springframework.org/schema/tx
    http://www.springframework.org/schema/tx/spring-tx.xsd">

    
    <context:component-scan base-package="com.zero" >
        
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" />
    context:component-scan>

    
    
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/java2ee"/>
        <property name="username" value="root"/>
        <property name="password" value="47LfQlFq"/>
    bean>

    
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
    bean>

    
    <bean id="mapperScanner" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.zero.dao"/>
    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="*" isolation="DEFAULT"/>
        tx:attributes>
    tx:advice>

    
    <aop:config>
        <aop:advisor advice-ref="txAdvice" pointcut="execution(* com.zero.service.impl.*ServiceImpl.*(..))"/>
    aop:config>

beans>
applicationContext.xml

 

 创建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:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context.xsd
    http://www.springframework.org/schema/aop
    http://www.springframework.org/schema/aop/spring-aop.xsd
    http://www.springframework.org/schema/tx
    http://www.springframework.org/schema/tx/spring-tx.xsd">

    
    <context:component-scan base-package="com.zero" >
        
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" />
    context:component-scan>

    
    
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/java2ee"/>
        <property name="username" value="root"/>
        <property name="password" value="47LfQlFq"/>
    bean>

    
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
    bean>

    
    <bean id="mapperScanner" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.zero.dao"/>
    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="*" isolation="DEFAULT"/>
        tx:attributes>
    tx:advice>

    
    <aop:config>
        <aop:advisor advice-ref="txAdvice" pointcut="execution(* com.zero.service.impl.*ServiceImpl.*(..))"/>
    aop:config>

beans>
springmvc.xml

 

编写dao层

package com.zero.dao;

import com.zero.domain.User;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Repository;


@Repository
public interface UserDao {
    /**
     * 通过名字查询用户
     * @param username 要查询用户的姓名
     * @return
     */
    @Select("select * from user where username=#{username}")
    User findUserByName(String username);

}
UserDao
package com.zero.dao;

import com.zero.domain.News;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public interface NewsDao {
    /**
     * 查询所有的新闻
     * @return 所有新闻的内容
     */
    @Select("select * from news")
    List findAllNews();

    /**
     * 根据id删除新闻
     * @param id 新闻的id
     */
    @Delete("delete from news where id=#{id}")
    void deleteById(int id);

    /**
     * 根据id查询新闻
     * @param id 要查询新闻的id
     * @return 新闻
     */
    @Select("select * from news where id=#{id}")
    News findNewsById(int id);

    /**
     * 插入新闻数据
     * @param news
     */
    @Insert("INSERT INTO news(title,content,author,cdate) VALUES(#{title},#{content},#{author},#{cdate})")
    void saveNews(News news);

    /**
     * 修改新闻
     * @param news 要修改的新闻
     */
    @Update("update news set title=#{title},content=#{content},author=#{author},cdate=#{cdate} where id=#{id}")
    void updateNews(News news);

}
NewsDao

 

编写实体类,其实和上一个作业的一样

package com.zero.domain;

import java.io.Serializable;

public class User implements Serializable {
    private String username;
    private String userpwd;

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getUserpwd() {
        return userpwd;
    }

    public void setUserpwd(String userpwd) {
        this.userpwd = userpwd;
    }

    @Override
    public String toString() {
        return "User{" +
                "username='" + username + '\'' +
                ", password='" + userpwd + '\'' +
                '}';
    }
}
User
package com.zero.domain;

import java.io.Serializable;
import java.util.Date;

public class News implements Serializable {
    private int id;
    private String title;
    private String content;
    private String author;
    private Date cdate;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    public String getAuthor() {
        return author;
    }

    public void setAuthor(String author) {
        this.author = author;
    }

    public Date getCdate() {
        return cdate;
    }

    public void setCdate(Date cdate) {
        this.cdate = cdate;
    }
}
News

 

然后是编写Service层

package com.zero.service;

import com.zero.domain.User;



public interface UserService {
    /**
     * 用于判断登录的用户名和密码是否正确
     * @param user 浏览器传过来的用户
     * @return 返回登录结果
     */
    boolean loginUser(User user);

}
UserService
package com.zero.service.impl;

import com.zero.dao.UserDao;
import com.zero.domain.User;
import com.zero.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service("userService")
public class UserServiceImpl implements UserService {
    @Autowired
    private UserDao userDao;

    @Override
    public boolean loginUser(User user) {
        User u = userDao.findUserByName(user.getUsername());
        if (user.getUsername().equals(u.getUsername()) && user.getUserpwd().equals(u.getUserpwd())){
            return true;
        }
        return false;
    }
}
UserServiceImpl
package com.zero.service;

import com.zero.domain.News;
import com.zero.domain.User;

import java.util.List;

public interface NewsService {
    /**
     * 得到所有的新闻
     * @return 所有的新闻
     */
    List showNewsList();

    /**
     * 根据id得到新闻
     * @param id
     * @return
     */
    News findNewsById(int id);

    /**
     * 删除新闻
     * @param id 要删除新闻的id
     */
    void deleteNews(int id);

    /**
     * 保存添加的新闻
     * @param news
     */
    void saveNews(News news);

    /**
     * 修改新闻
     * @param news
     */
    void updateNews(News news);
}
NewsService
package com.zero.service.impl;

import com.zero.dao.NewsDao;
import com.zero.domain.News;
import com.zero.service.NewsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service("newsService")
public class NewsServiceImpl implements NewsService {

    @Autowired
    private NewsDao newsDao;

    @Override
    public List showNewsList() {
        List newsList = newsDao.findAllNews();
        return newsList;
    }

    @Override
    public News findNewsById(int id) {
        News news = newsDao.findNewsById(id);
        return news;
    }

    @Override
    public void deleteNews(int id) {
        newsDao.deleteById(id);
    }

    @Override
    public void saveNews(News news) {
        newsDao.saveNews(news);
    }

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


}
NewsServiceImpl

 

接着是写Controller

package com.zero.controller;


import com.zero.domain.User;
import com.zero.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Controller
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 验证登录
     * @return
     */
    @RequestMapping("/login")
    public void login(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        User user = new User();
        user.setUsername(username);
        user.setUserpwd(password);
        boolean b = userService.loginUser(user);
        if(b){
            Cookie userNameCo= new Cookie("username", username);
            userNameCo.setMaxAge(60*60*24*30);
            response.addCookie(userNameCo);

            Cookie userPwdCo= new Cookie("userpwd", password);
            userPwdCo.setMaxAge(60*60*24*30);
            response.addCookie(userPwdCo);

            // 这里添加一个error的cookie,用来判断用户名密码是否正确,200正确,400不正确
            Cookie errorCo = new Cookie("error","200");
            response.addCookie(errorCo);
            // 用户名密码正确跳转到主页面
            response.sendRedirect(request.getContextPath() + "/showlist");
            return;
        }
        // 不正确则继续返回登录界面
        Cookie errorCo = new Cookie("error","400");
        response.addCookie(errorCo);
        response.sendRedirect("/login.jsp");
    }
}
UserController
package com.zero.controller;

import com.zero.domain.News;
import com.zero.service.NewsService;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.FilterChain;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Controller
public class NewsController {

    @Autowired
    private NewsService newsService;


    /**
     * 展示所有新闻
     * @return
     */
    @RequestMapping("/showlist")
    public void showList(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, ParseException {
        List newsList = newsService.showNewsList();
        request.setAttribute("newsList",newsList);
        request.getRequestDispatcher("/showlist.jsp").forward(request,response);
    }


    @RequestMapping("/edit")
    public void edit(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        int id=Integer.valueOf( request.getParameter("id"));
        News news = newsService.findNewsById(id);
        request.setAttribute("news",news);
        request.getRequestDispatcher("/edit.jsp").forward(request,response);
    }

    @RequestMapping("/save")
    public void save(HttpServletRequest request, HttpServletResponse response) throws InvocationTargetException, IllegalAccessException, ParseException, IOException {
        Map parameterMap = request.getParameterMap();
        News news = new News();
        BeanUtils.populate(news,parameterMap);
        news.setCdate(new Date());
        if(news.getId() != 0){
            newsService.updateNews(news);
            response.sendRedirect( request.getContextPath() + "/showlist");
            return;
        }
        newsService.saveNews(news);
        response.sendRedirect(request.getContextPath() + "/showlist");
    }

    @RequestMapping("/delete")
    public void delete(HttpServletRequest request, HttpServletResponse response) throws IOException {
        int id=Integer.valueOf( request.getParameter("id"));
        newsService.deleteNews(id);
        response.sendRedirect(request.getContextPath() + "/showlist");
    }

    @RequestMapping("/view")
    public void view(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, ParseException {
        int id=Integer.valueOf( request.getParameter("id"));
        News news = newsService.findNewsById(id);
        request.setAttribute("news",news);
        request.getRequestDispatcher("/showone.jsp").forward(request,response);
    }


}
NewsController

 

还写了个过滤器,用来初始化index.jsp的数据用的,这里为了查数据写了个DBUtil

package com.zero.controller;


import com.zero.domain.News;
import com.zero.service.NewsService;
import com.zero.service.impl.NewsServiceImpl;
import com.zero.util.DBUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import javax.servlet.*;
import java.io.IOException;
import java.util.List;

public class IndexFilter implements Filter {

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        Object newsList = req.getAttribute("newsList");
        if (newsList == null){
            List list = DBUtil.getNewsList();
            req.setAttribute("newsList",list);
        }
        chain.doFilter(req, resp);
    }

    @Override
    public void init(FilterConfig config) throws ServletException {

    }

    @Override
    public void destroy() {

    }

}
IndexFilter
package com.zero.util;

import com.zero.domain.News;
import com.zero.service.NewsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

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

@Component
public class DBUtil {
    @Autowired
    private NewsService newsService;

    public static DBUtil dbUtil;

    @PostConstruct
    public void init() {
        dbUtil = this;
    }

    public static List getNewsList(){
        List newsList = dbUtil.newsService.showNewsList();
        return newsList;
    }
}
DBUtil

 

web.xml的内容

app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >


         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">


  Archetype Created Web Application

  
  
    class>org.springframework.web.context.ContextLoaderListenerclass>
  
  
  
    contextConfigLocation
    classpath:applicationContext.xml
  


  
  
    dispatcherServlet
    class>org.springframework.web.servlet.DispatcherServletclass>
    
    
      contextConfigLocation
      classpath:springmvc.xml
    
    
    1
  
  
    dispatcherServlet
    /
  

  
  
    characterEncodingFilter
    class>org.springframework.web.filter.CharacterEncodingFilterclass>
    
      encoding
      UTF-8
    
  
  
    characterEncodingFilter
    /*
  

  
    indexFilter
    com.zero.controller.IndexFilter
  
  
    indexFilter
    /index.jsp
  
web.xml

 

最后的项目结构

SpringMVC+Spring+mybatis 项目实践_第5张图片

 

 

最后的效果和MVC2一样

SpringMVC+Spring+mybatis 项目实践_第6张图片

 

 

 

SpringMVC+Spring+mybatis 项目实践_第7张图片

SpringMVC+Spring+mybatis 项目实践_第8张图片

 

SpringMVC+Spring+mybatis 项目实践_第9张图片

 

 

SpringMVC+Spring+mybatis 项目实践_第10张图片

 

 

增删改查都没问题。

 

到此所有工作完成

码云地址:https://gitee.com/ZeroLuo328/java2enews.git 

注意是javaEESSM这个项目文件

你可能感兴趣的:(SpringMVC+Spring+mybatis 项目实践)