Fork me on GitHub

JAVAEE第六次作业-SpringMVC+Spring+mybatis 项目实践

## JAVAEE第六次作业-SpringMVC+Spring+mybatis 项目实践

注:由于对SSM框架很陌生,配置文件部分自己弄了很久也不清楚,配置文件部分内容参考了罗付强同学的博客https://www.cnblogs.com/lfq4588/p/13094221.html

一、任务

使用ssm重新开发计科院新闻网站

二、创建SSM框架环境

2.1 新建Maven项目

方便对需要用的包进行管理

1593051519583

Maven导入需要用到的包

<dependencies>
   <!--Junit-->
   <dependency>
       <groupId>junit</groupId>
       <artifactId>junit</artifactId>
       <version>4.12</version>
   </dependency>
   <!--数据库驱动-->
   <dependency>
       <groupId>mysql</groupId>
       <artifactId>mysql-connector-java</artifactId>
       <version>5.1.47</version>
   </dependency>
   <!-- 数据库连接池 -->
   <dependency>
       <groupId>com.mchange</groupId>
       <artifactId>c3p0</artifactId>
       <version>0.9.5.2</version>
   </dependency>

   <!--Servlet - JSP -->
   <dependency>
       <groupId>javax.servlet</groupId>
       <artifactId>servlet-api</artifactId>
       <version>2.5</version>
   </dependency>
   <dependency>
       <groupId>javax.servlet.jsp</groupId>
       <artifactId>jsp-api</artifactId>
       <version>2.2</version>
   </dependency>
   <dependency>
       <groupId>javax.servlet</groupId>
       <artifactId>jstl</artifactId>
       <version>1.2</version>
   </dependency>

   <!--Mybatis-->
   <dependency>
       <groupId>org.mybatis</groupId>
       <artifactId>mybatis</artifactId>
       <version>3.5.2</version>
   </dependency>
   <dependency>
       <groupId>org.mybatis</groupId>
       <artifactId>mybatis-spring</artifactId>
       <version>2.0.2</version>
   </dependency>

   <!--Spring-->
   <dependency>
       <groupId>org.springframework</groupId>
       <artifactId>spring-webmvc</artifactId>
       <version>5.1.9.RELEASE</version>
   </dependency>
   <dependency>
       <groupId>org.springframework</groupId>
       <artifactId>spring-jdbc</artifactId>
       <version>5.1.9.RELEASE</version>
   </dependency>
</dependencies>

2.2 添加Web环境支持

1593051594889

2.3 创建SSM项目文件结构

1593051727488

  • Controller:用于将service的结果展示在前端页面
  • mapper:mabatis映射接口,编写SQL语句
  • pojo:实体类
  • service:业务层,和Controller进行交互

2.4 编写配置文件代码

  1. 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: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">

    <!--开启注解的扫描,希望处理service和dao,controller不需要Spring框架去处理-->
    <context:component-scan base-package="com.example" >
        <!--配置哪些注解不扫描-->
        <context:exclude-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.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/users?useUnicode=true&amp;characterEncoding=utf8"/>
        <property name="username" value="root"/>
        <property name="password" value="123"/>
    </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.example.mapper"/>
    </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.example.service.impl.*ServiceImpl.*(..))"/>
    </aop:config>

</beans>
  1. 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.example">
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller" />
    </context:component-scan>

    <!--配置的视图解析器对象-->
    <bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!-- JSP文件所在的目录 -->
        <property name="prefix" value="/"/>
        <!-- 文件的后缀名 -->
        <property name="suffix" value=".jsp"/>
    </bean>

    <!--过滤静态资源-->
    <mvc:resources location="css/" mapping="/css/**" />
    <mvc:resources location="js/" mapping="/js/**" />
    <mvc:resources location="image/" mapping="/image/**" />
    <mvc:resources location="UEditor/" mapping="/UEditor/**" />
    <mvc:resources location="images/" mapping="/images/**" />
    <mvc:resources location="page/" mapping="/page/**" />

    <!--开启SpringMVC注解的支持-->
    <mvc:annotation-driven/>

</beans>

三、完成SSM项目代码

编写代码之前,可以将MVC Model2中的Web资源拷贝到该项目,代码部分也可以简单修改转换为ssm的形式

3.1 pojo实体类编写

此处用到了lombok工具,实体类就不用编写复杂的get set方法了

//用户实体类
@Data
@AllArgsConstructor
@NoArgsConstructor
public class UserInfo {
    String uName="";    //用户名
    String uPwd="";     //用户密码
}
//新闻实体类
@Data
@AllArgsConstructor
@NoArgsConstructor
public class News {

    private String newsId;
    private String title;
    private String newsContent;
    private String author;
    private String newsDate;

}

3.2 编写mapper数据库映射

  1. UserMapper
@Repository
public interface UserMapper {
    //判断当前账号是否正确
    @Select("select * from users_info where UID = #{UID} AND UPWD = #{UPWD}")
    UserInfo isUserExist(UserInfo userInfo);
}
  1. NewsMapper
@Repository
public interface NewsMapper {

    //增加新闻
    @Insert("insert into users.news (NewID,Title, NewsContent, Author, NewsDate)\n" +
            "        values (#{NewID},#{Title},#{NewsContent},#{Author},#{NewsDate});")
    int addNews(News news);

    //删除新闻
    @Delete(" delete from users.news where NewID = #{NewID};")
    int deleteNewsById(@Param("NewID") String newId);

    //修改新闻
    @Update("update users.news\n" +
            "set Title=#{Title},NewsContent=#{NewsContent},Author=#{Author},NewsDate=#{NewsDate}\n" +
            "where NewID = #{NewID};")
    int updateNewsById(News news);

    //查询一条新闻
    @Select("select * from users.news where NewID = #{NewID};")
    News queryNewsById(@Param("NewID") String newId);

    //查询所有新闻
    @Select("select * from users.news;")
    List<News> queryAllNews();
}

3.3 编写service的实现

  1. NewsServiceImpl
@Service("NewsService")
public class NewsServiceImpl implements NewsService {
    //service调dao层  组合mapper
    @Autowired
    private NewsMapper newsMapper;

    public void setNewsMapper(NewsMapper newsMapper) {
        //可增加其他代码
        this.newsMapper = newsMapper;
    }

    public boolean addNews(News news) {

        int rows = newsMapper.addNews(news);
        if (rows > 0) {
            return true;
        } else {
            return false;
        }
    }

    public boolean deleteNewsById(String newId) {
        int rows = newsMapper.deleteNewsById(newId);
        if (rows > 0) {
            return true;
        } else {
            return false;
        }
    }

    public boolean updateNewsById(News news) {
        int rows = newsMapper.updateNewsById(news);
        if (rows > 0) {
            return true;
        } else {
            return false;
        }
    }

    public News queryNewsById(String newId) {
        return newsMapper.queryNewsById(newId);
    }

    public List<News> queryAllNews() {
        return newsMapper.queryAllNews();
    }
}
  1. UserServiceImpl
@Service("UserService")
public class UserServiceImpl implements UserService {
    //service调dao层  组合mapper
    @Autowired
    private UserMapper userMapper;

    public void setUserMapper(UserMapper userMapper) {
        this.userMapper = userMapper;
    }

    //账号结果是否正确
    public boolean isUserExist(UserInfo userInfo) {
        UserInfo quertRes = userMapper.isUserExist(userInfo);
        if (quertRes == null) {
            return false;
        }

        if (quertRes.getUID() != null && quertRes.getUPWD() != null) {
            return true;
        } else {
            return false;
        }
    }
}

3.4 编写controller

  1. UserController
@Controller
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping("/login")
    public void login(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        UserInfo user = new UserInfo();
        user.setUID(username);
        user.setUPWD(password);

        boolean b = userService.isUserExist(user);
        if (b) {
            response.sendRedirect("page/index.html");
        } else {
            response.sendRedirect("index.jsp");
        }
    }
}
  1. NewsController(由于内容太多,只展示部分)
@RequestMapping("/viewNew")
public void viewNew(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
    request.setCharacterEncoding("UTF-8");
    response.setCharacterEncoding("UTF-8");
    response.setContentType("text/html; charset=UTF-8");

    String newsID = request.getParameter("newid");
    System.out.println(newsID);

    News news = null;
    news = newsService.queryNewsById(newsID);

    System.out.println(news.getNewID());
    System.out.println(news.getNewsContent());
    System.out.println(news.getNewsDate());
    System.out.println(news.getAuthor());

    request.setAttribute("news", news);
    //转发到content.jsp
    request.getRequestDispatcher("NewsContent.jsp").forward(request, response);
}

四、效果实现

效果与MVC Model2作业类似,但是SSM实现起来更方便了

  1. 删除编号为7的新闻

1592903434426

1592903455270

成功实现删除功能

  1. 添加新闻,点击左上方按钮即可

1592903515575

  1. 跳转到新闻管理表单

1592903556497

  1. 点写完内容点击更新

1592903667005

  1. 成功添加新闻

1592903693584

  1. 点击编辑按钮开始修改新闻内容

1592903748676

  1. 修改部分内容

1592903787233

成功完成修改

1592903804328

  1. 点击查看新闻即可跳转到新闻详细界面中

1592965432461

  1. 官网效果实现

跳转后页面

1592965501142

五、码云地址

码云地址: https://gitee.com/Jason98/JavaEE-Course

1593053573620

posted @ 2020-06-25 10:57  jasonlalala  阅读(1161)  评论(0编辑  收藏  举报