SSM项目实践 第六次作业

实验小组成员:

 

(1)郭昭杰  学号:201731062608

 

(2)庞斌  学号:201731062609

 

(3)唐任峻杰  学号:201731062610

 

项目码云地址:https://gitee.com/ashes-g/SSM

 

一、配置SSM框架

创建Maven项目,勾选Create from archetype后,选择maven-archetype-webapp

 

 

 

输入项目名并选择保存位置

 

 

 

继续下一步,使用本地的setting文件和jar包地址

 

 

 

点击finish后项目创建完成,下面开始正式配置

 

 

 

首先要配置文件的目录结构,配置完成后的目录结构如图所示:

 

 

 

注意:我在建包时遇到了无法在com包下建立它的下级包的情况,在下图所示位置取消勾选compact middle packlages选项即可

 

 

修改pom.xml文件,导入需要的包

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.xiaogroupId>
    <artifactId>SSMartifactId>
    <version>1.0-SNAPSHOTversion>
    <packaging>warpackaging>
 
    
    <properties>
        <spring.version>4.2.4.RELEASEspring.version>
        <mybatis.version>3.2.8mybatis.version>
        <mybatis.spring.version>1.2.2mybatis.spring.version>
        <slf4j.version>1.6.4slf4j.version>
        <log4j.version>1.2.17log4j.version>
        <jackson.version>2.4.2jackson.version>
        <druid.version>1.0.9druid.version>
        <mysql.version>5.1.32mysql.version>
        <jstl.version>1.2jstl.version>
        <servlet-api.version>2.5servlet-api.version>
        <jsp-api.version>2.0jsp-api.version>
        <commons-io.version>1.3.2commons-io.version>
        <commons-fileupload.version>1.3.1commons-fileupload.version>
    properties>
 
    
    <dependencyManagement>
        <dependencies>
            
            <dependency>
                <groupId>org.springframeworkgroupId>
                <artifactId>spring-contextartifactId>
                <version>${spring.version}version>
            dependency>
            <dependency>
                <groupId>org.springframeworkgroupId>
                <artifactId>spring-beansartifactId>
                <version>${spring.version}version>
            dependency>
            <dependency>
                <groupId>org.springframeworkgroupId>
                <artifactId>spring-webmvcartifactId>
                <version>${spring.version}version>
            dependency>
            <dependency>
                <groupId>org.springframeworkgroupId>
                <artifactId>spring-jdbcartifactId>
                <version>${spring.version}version>
            dependency>
            <dependency>
                <groupId>org.springframeworkgroupId>
                <artifactId>spring-aspectsartifactId>
                <version>${spring.version}version>
            dependency>
            <dependency>
                <groupId>org.springframeworkgroupId>
                <artifactId>spring-jmsartifactId>
                <version>${spring.version}version>
            dependency>
            <dependency>
                <groupId>org.springframeworkgroupId>
                <artifactId>spring-context-supportartifactId>
                <version>${spring.version}version>
            dependency>
 
            
            <dependency>
                <groupId>org.mybatisgroupId>
                <artifactId>mybatisartifactId>
                <version>${mybatis.version}version>
            dependency>
            <dependency>
                <groupId>org.mybatisgroupId>
                <artifactId>mybatis-springartifactId>
                <version>${mybatis.spring.version}version>
            dependency>
 
            
            <dependency>
                <groupId>org.slf4jgroupId>
                <artifactId>slf4j-log4j12artifactId>
                <version>${slf4j.version}version>
            dependency>
            <dependency>
                <groupId>log4jgroupId>
                <artifactId>log4jartifactId>
                <version>${log4j.version}version>
            dependency>
 
            
            <dependency>
                <groupId>com.fasterxml.jackson.coregroupId>
                <artifactId>jackson-databindartifactId>
                <version>${jackson.version}version>
            dependency>
 
            
            <dependency>
                <groupId>com.alibabagroupId>
                <artifactId>druidartifactId>
                <version>${druid.version}version>
            dependency>
 
            
            <dependency>
                <groupId>mysqlgroupId>
                <artifactId>mysql-connector-javaartifactId>
                <version>${mysql.version}version>
            dependency>
 
            
            <dependency>
                <groupId>org.apache.commonsgroupId>
                <artifactId>commons-ioartifactId>
                <version>${commons-io.version}version>
            dependency>
 
            
            <dependency>
                <groupId>commons-fileuploadgroupId>
                <artifactId>commons-fileuploadartifactId>
                <version>${commons-fileupload.version}version>
            dependency>
 
            
            <dependency>
                <groupId>jstlgroupId>
                <artifactId>jstlartifactId>
                <version>${jstl.version}version>
            dependency>
            <dependency>
                <groupId>javax.servletgroupId>
                <artifactId>servlet-apiartifactId>
                <version>${servlet-api.version}version>
                <scope>providedscope>
            dependency>
            <dependency>
                <groupId>javax.servletgroupId>
                <artifactId>jsp-apiartifactId>
                <version>${jsp-api.version}version>
                <scope>providedscope>
            dependency>
        dependencies>
    dependencyManagement>
 
    
    <dependencies>
        
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-contextartifactId>
        dependency>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-beansartifactId>
        dependency>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-webmvcartifactId>
        dependency>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-jdbcartifactId>
        dependency>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-aspectsartifactId>
        dependency>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-jmsartifactId>
        dependency>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-context-supportartifactId>
        dependency>
 
        
        <dependency>
            <groupId>org.mybatisgroupId>
            <artifactId>mybatisartifactId>
        dependency>
        <dependency>
            <groupId>org.mybatisgroupId>
            <artifactId>mybatis-springartifactId>
        dependency>
 
        
        <dependency>
            <groupId>org.slf4jgroupId>
            <artifactId>slf4j-log4j12artifactId>
        dependency>
 
        
        <dependency>
            <groupId>com.fasterxml.jackson.coregroupId>
            <artifactId>jackson-databindartifactId>
        dependency>
 
        
        <dependency>
            <groupId>com.alibabagroupId>
            <artifactId>druidartifactId>
        dependency>
 
        
        <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
        dependency>
 
        
        <dependency>
            <groupId>org.apache.commonsgroupId>
            <artifactId>commons-ioartifactId>
        dependency>
 
        
        <dependency>
            <groupId>commons-fileuploadgroupId>
            <artifactId>commons-fileuploadartifactId>
        dependency>
 
        
        <dependency>
            <groupId>jstlgroupId>
            <artifactId>jstlartifactId>
        dependency>
        <dependency>
            <groupId>javax.servletgroupId>
            <artifactId>servlet-apiartifactId>
            <scope>providedscope>
        dependency>
        <dependency>
            <groupId>javax.servletgroupId>
            <artifactId>jsp-apiartifactId>
            <scope>providedscope>
        dependency>
    dependencies>
 
    <build>
        
        <plugins>
            <plugin>
                <groupId>org.apache.maven.pluginsgroupId>
                <artifactId>maven-compiler-pluginartifactId>
                <version>3.2version>
                <configuration>
                    <source>1.8source>
                    <target>1.8target>
                    <encoding>UTF-8encoding>
                configuration>
            plugin>
        plugins>
 
        
        <resources>
            <resource>
                <directory>src/main/javadirectory>
                <includes>
                    <include>**/*.xmlinclude>
                includes>
                <filtering>falsefiltering>
            resource>
 
            <resource>
                <directory>src/main/resourcesdirectory>
                <includes>
                    <include>**/*.propertiesinclude>
                    <include>**/*.xmlinclude>
                includes>
                <filtering>falsefiltering>
            resource>
        resources>
 
    build>
 
project>

 

修改完成后,在项目名处右击,选择Maven-Reimport即可完成引入

 

 

 

下一步,在resource目录进行配置文件的添加,共4个文件

(1)连接数据库配置信息文件:db.properties

druid.driver=com.mysql.jdbc.Driver
druid.url=jdbc:mysql://localhost:3306/all_db?characterEncoding=utf-8
druid.username=root
druid.password=Guozhaojie610

(2)Mybatis配置文件:SqlMapConfig.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.xiao.pojo"/>
    typeAliases>

configuration>

(3)Spring配置文件:applicationContext.xml

 

xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
                        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd
                        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd">

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

    
    <mvc:annotation-driven />

    

    <mvc:resources location="/js/" mapping="/js/**"/>
    <mvc:resources location="/css/" mapping="/css/**"/>
    <mvc:resources location="/images/" mapping="/images/**"/>
    <mvc:resources location="/img_source/" mapping="/img_source/**"/>
    <mvc:resources location="/ueditor/" mapping="/ueditor/**"/>
    <mvc:resources location="/utilLib/" mapping="/utilLib/**"/>

    
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        
        <property name="prefix" value="/WEB-INF/jsp/" />
        
        <property name="suffix" value=".jsp" />

    bean>

beans>

 

 

最后需要在web.xml文件中进行配置:

xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
          http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
         version="2.5">

  <display-name>SSMdisplay-name>

  <welcome-file-list>
    <welcome-file>index.jspwelcome-file>
  welcome-file-list>

  
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>
  listener>

  
  <context-param>
    <param-name>contextConfigLocationparam-name>
    <param-value>classpath:applicationContext.xmlparam-value>
  context-param>

  
  <filter>
    <filter-name>encodingfilter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
    <init-param>
      <param-name>encodingparam-name>
      <param-value>UTF-8param-value>
    init-param>
  filter>
  <filter-mapping>
    <filter-name>encodingfilter-name>
    <url-pattern>/*url-pattern>
  filter-mapping>

  
  <servlet>
    <servlet-name>springmvcservlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
    
    <init-param>
      <param-name>contextConfigLocationparam-name>
      <param-value>classpath:springmvc.xmlparam-value>
    init-param>
    <load-on-startup>1load-on-startup>
  servlet>
  <servlet-mapping>
    <servlet-name>springmvcservlet-name>
    <url-pattern>/url-pattern>
  servlet-mapping>

web-app>

 

最终的目录结构:

 

 

二、修改项目代码

将原项目的java类、页面文件复制进项目后,需要进行一定的修改使其基于spring框架运行

将原有的各个NewsServlet类集合到一个新建的NewsController类中

package com.controller;

import com.entity.News;
import com.entity.User;
import com.service.NewsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;


import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.List;

public class NewsController {

    @Autowired
    private NewsService newsService;

    //显示所有新闻
    @RequestMapping("/ShowNews")
    public void ShowNews(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        try {
            List newsList = newsService.QueryNews();
            for (News s:newsList
            ) {
                System.out.println(s.getNewsId());
            }

            request.setAttribute("News", newsList);
            request.getRequestDispatcher("ShowNews.jsp").forward(request, response);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @RequestMapping("/AddNews")
    public void addNew(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Context-Type","text/html;charset=utf-8");
        News news =new News();
        news.setNewsId(Integer.valueOf(request.getParameter("newsid")));
        news.setNewsAuthor(request.getParameter("author"));
        news.setNewsContent(request.getParameter("Content"));
        news.setNewsTitle(request.getParameter("title"));
        NewsService newsService=new NewsService();
        try {
            newsService.AddNews(news);
            request.getRequestDispatcher("ShowNews").forward(request,response);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @RequestMapping("/UpdateNews")
    public void editNew(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        response.setContentType("text/html; charset=UTF-8");
        request.setCharacterEncoding("UTF-8");
        response.setHeader("Context-Type", "text/html;charset=utf-8");
        News news = new News();
        news.setNewsId(Integer.valueOf(request.getParameter("newsid")));
        news.setNewsAuthor(request.getParameter("author"));
        news.setNewsContent(request.getParameter("Content"));
        news.setNewsTitle(request.getParameter("title"));
        NewsService newsService = new NewsService();
        try {
            newsService.UpdateNews(news);
            request.getRequestDispatcher("ShowNews").forward(request, response);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }


    @RequestMapping("/deleteNew")
    public void deleteNew(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {

        int newsID=Integer.valueOf(request.getParameter("newsid"));
        NewsService newsService=new NewsService();
        try {
            newsService.DeleteNews(newsID);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        request.getRequestDispatcher("com.controller.ShowNewsServlet").forward(request,response);
    }

    @RequestMapping("/viewNew")
    public void viewNew(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        int newsID=Integer.valueOf(request.getParameter("newsid"));
        NewsService newsService=new NewsService();
        try {
            News news=newsService.QueryIndividualNews(newsID);
            request.setAttribute("news",news);
            request.getRequestDispatcher("NewsDetail.jsp").forward(request,response);
        }catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    
}

将LoginServlet类改为UserController类

package com.controller;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

@Controller
public class UserController {

    @RequestMapping("/Login")
    public void login(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setContentType("text/html; charset=UTF-8");
        request.setCharacterEncoding("UTF-8");
        response.setHeader("Context-Type", "text/html;charset=utf-8");

        PrintWriter output = response.getWriter();
        String uname = request.getParameter("username");
        String pwd = request.getParameter("pwd");
        ResultSet rs;
        Statement statement = null;
        Connection conn = null;
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306?serverTimezone=GMT&characterEncoding=utf-8", "root", "Guozhaojie610");
            String sql = "select * from new_schema.login where username='" + uname + "' and password='" + pwd + "'";
            statement = conn.createStatement();
            rs = statement.executeQuery(sql);
            if (rs.next()) {
                request.setAttribute("username", uname);
                response.sendRedirect("index.html");
            } else {
                output.println("账号或密码错误");
                response.sendRedirect("index.jsp");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

实体类:

News

package com.entity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class News {
    private int newsId;
    private String newsContent;
    private  String newsAuthor;
    private  String newsTitle;

    public int getNewsId() {
        return newsId;
    }

    public void setNewsId(int newsId) {
        this.newsId = newsId;
    }

    public String getNewsContent() {
        return newsContent;
    }

    public void setNewsContent(String newsContent) {
        this.newsContent = newsContent;
    }

    public String getNewsAuthor() {
        return newsAuthor;
    }

    public void setNewsAuthor(String newsAuthor) {
        this.newsAuthor = newsAuthor;
    }

    public String getNewsTitle() {
        return newsTitle;
    }

    public void setNewsTitle(String newsTitle) {
        this.newsTitle = newsTitle;
    }

}

User

package com.entity;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
    String username;
    String password;

    public String getUsername() {
        return username;
    }

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

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}

 

最后将页面的连接进行重定向,这里不再放出代码

最终项目结构:

 

 

 

三、最终效果展示

与MVC版本效果相同

 

 

 

 

 

 

 

 

 

 

你可能感兴趣的:(SSM项目实践 第六次作业)