ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

JavaEE之SSM框架——SSM整合

2021-01-15 20:33:07  阅读:400  来源: 互联网

标签:框架 spring JavaEE springframework SSM student mybatis org public


目录

ssm框架整合

避坑指南

作业

文件树

后台部分

bean包和dao包由mybatis逆向生成

service包

controller包

配置文件

前端部分

web配置文件web.xml(设置编码格式以及过滤器,以及提升为web-app2.5版本)

登录页面index.jsp

主界面

注意


ssm框架整合

1.添加依赖包,可以通过properties统一框架版本

<properties> 
​
<springversion>5.0.8.RELEASE</springversion> 
​
</properties> 
​
<dependencies> 
​
<!-- 加入ServletAPI --> 
​
<dependency> 
​
<groupId>javax.servlet</groupId> 
​
<artifactId>javax.servlet-api</artifactId> 
​
<version>3.1.0</version> 
​
<scope>provided</scope> 
​
</dependency> 
​
<!-- MySQL依赖 start --> 
​
<dependency> 
​
<groupId>mysql</groupId> 
​
<artifactId>mysql-connector-java</artifactId> 
​
<version>5.1.38</version> 
​
</dependency> 
​
<!-- 加入MyBatis 依赖 start --> 
​
<dependency> 
​
<groupId>org.mybatis</groupId> 
​
<artifactId>mybatis</artifactId> 
​
<version>3.2.8</version> 
​
</dependency> 
​
<!-- 引入Spring(包含SpringMVC) 依赖 start --> 
​
<dependency> 
​
<groupId>org.springframework</groupId> 
​
<artifactId>spring-core</artifactId> 
​
<version>${springversion}</version> 
​
</dependency>
​
<dependency> 
​
<groupId>org.springframework</groupId> 
​
<artifactId>spring-web</artifactId> 
​
<version>${springversion}</version> 
​
</dependency> 
​
<dependency> 
​
<groupId>org.springframework</groupId> 
​
<artifactId>spring-oxm</artifactId> 
​
<version>${springversion}</version> 
​
</dependency> 
​
<dependency> 
​
<groupId>org.springframework</groupId> 
​
<artifactId>spring-tx</artifactId> 
​
<version>${springversion}</version> 
​
</dependency> 
​
<dependency> 
​
<groupId>org.springframework</groupId> 
​
<artifactId>spring-jdbc</artifactId> 
​
<version>${springversion}</version> 
​
</dependency> 
​
<dependency> 
​
<groupId>org.springframework</groupId> 
​
<artifactId>spring-webmvc</artifactId> 
​
<version>${springversion}</version> 
​
</dependency> 
​
<dependency> 
​
<groupId>org.springframework</groupId> 
​
<artifactId>spring-aop</artifactId> 
​
<version>${springversion}</version> 
​
</dependency> 
​
<dependency> 
​
<groupId>org.springframework</groupId> 
​
<artifactId>spring-context-support</artifactId> 
​
<version>${springversion}</version> 
​
</dependency> 
​
<dependency> 
​
<groupId>org.springframework</groupId> 
​
<artifactId>spring-test</artifactId> 
​
<version>${springversion}</version> 
​
</dependency> 
​
<!-- 引用插件依赖:MyBatis整合Spring,如果mybatis版本在3.4及以上版本 
​
mybatis-spring的版本要在1.3以上 --> 
​
<dependency> 
​
<groupId>org.mybatis</groupId> 
​
<artifactId>mybatis-spring</artifactId> 
​
<version>1.2.2</version> 
​
</dependency> 
​
<!-- JSTL --> 
​
<dependency> 
​
<groupId>jstl</groupId> 
​
<artifactId>jstl</artifactId> 
​
<version>1.2</version> 
​
</dependency>
​
<!-- 德鲁伊数据连接池 --> 
​
<dependency> 
​
<groupId>com.alibaba</groupId> 
​
<artifactId>druid</artifactId> 
​
<version>1.0.9</version> 
​
</dependency> 
​
<!-- pagehelper --> 
​
<dependency> 
​
<groupId>com.github.pagehelper</groupId> 
​
<artifactId>pagehelper</artifactId> 
​
<version>4.1.6</version> 
​
</dependency> 
​
<!--处理json--> 
​
<dependency> 
​
<groupId>com.fasterxml.jackson.core</groupId> 
​
<artifactId>jackson-databind</artifactId> 
​
<version>2.9.5</version> 
​
</dependency> 
​
<!--javaee--> 
​
<dependency> 
​
<groupId>javax</groupId> 
​
<artifactId>javaee-api</artifactId> 
​
<version>7.0</version> 
​
<scope>provided</scope> 
​
</dependency> 
​
<!--文件上传下载--> 
​
<dependency> 
​
<groupId>commons-fileupload</groupId> 
​
<artifactId>commons-fileupload</artifactId> 
​
<version>1.3.1</version> 
​
</dependency> 
​
<dependency> 
​
<groupId>commons-io</groupId> 
​
<artifactId>commons-io</artifactId> 
​
<version>2.4</version> 
​
</dependency> 
​
</dependencies> 
​
如果遇到声明式事务报错,需要添加下面的依赖包 
​
<dependency> 
​
<groupId>org.aspectj</groupId> 
​
<artifactId>aspectjweaver</artifactId> 
​
<version>1.9.1</version> 
​
</dependency> 

2.添加spring配置文件,ssm中可以省略mybatis.xml文件

3.配置web.xml文件,同时加载spring配置文件

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
​
xmlns="http://java.sun.com/xml/ns/javaee"
​
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
​
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5"> 
​
<servlet> 
​
<servlet-name>mvc</servlet-name> 
​
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> 
​
<init-param> 
​
<param-name>contextConfigLocation</param-name> 
​
<param-value>classpath:applicationContext.xml</param-value> 
​
</init-param> 
​
</servlet> 
​
<servlet-mapping> 
​
<servlet-name>mvc</servlet-name> 
​
<url-pattern>/</url-pattern> 
​
</servlet-mapping> 
​
<filter> 
​
<filter-name>aa</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>aa</filter-name> 
​
<url-pattern>/*</url-pattern> 
​
</filter-mapping> 

4.创建数据表,添加项目包结构,包括实体类等

给dao,service,web包下使用注解创建对象,给service,web中的属性注入对象

  • 创建对象:dao实现类用@Repository,service实现类用@Service,controller层用@@Controller

  • 注入对象

    • service实现类:先用 private BooksDao dao;创建,然后用@Resource进行对象注入

    • controller:先用private BookService bookService;创建,然后用@Resource进行对象注入

  • 匹配请求,调取service方法

    • 在controller的方法通过@RequestMapping内的地址与前端的地址进行关联,并调取service方法。

5.配置文件代码

<!--1.创建数据源,使用spring连接数据库 --> 
​
<context:property-placeholder location="db.properties" system-properties-mode="FALLBACK"/> 
​
<bean id="db" destroy-method="close" class="com.alibaba.druid.pool.DruidDataSource"> 
​
<property name="url" value="${url}"></property> 
​
<property name="username" value="${username}"></property> 
​
<property name="password" value="${password}"></property> 
​
<property name="driverClassName" value="${driver}"></property> 
​
<property name="maxActive" value="10"/> 
​
<property name="minIdle" value="5"/> 
​
</bean> 
​
<!--2.扫描注解包--> 
​
<context:component-scan base-package="com"></context:component-scan> 
​
<!--3.创建视图解析器-->
​
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> 
​
<property name="prefix" value="/"/> 
​
<property name="suffix" value=".jsp"/> 
​
</bean> 
​
<!--4.加载注解驱动--> 
​
<mvc:annotation-driven></mvc:annotation-driven> 
​
<!--5.创建sqlsession工厂--> 
​
<bean id="fac" class="org.mybatis.spring.SqlSessionFactoryBean"> 
​
<property name="dataSource" ref="db" ></property> 
​
<property name="mapperLocations" value="classpath:/mapper/*.xml"></property> 
​
<property name="configLocation" value="classpath:mybatis.xml"></property> 
​
</bean> 
​
<!--6.使用dao层实现类的时候,需要得到sqlSessionTemplate对象 
​
<bean id="temp" class="org.mybatis.spring.SqlSessionTemplate"> 
​
<constructor-arg index="0" ref="fac"></constructor-arg> 
​
</bean>--> 
​
<!--7.配置事务--> 
​
<bean id="tx" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> 
​
<property name="dataSource" ref="db"></property> 
​
</bean> 
​
<tx:annotation-driven transaction-manager="mytx"></tx:annotation-driven> 
​
<!--8.配置静态资源--> 
​
<mvc:resources mapping="/css/**" location="/css/"></mvc:resources> 
​
<mvc:resources mapping="/dtree/**" location="/dtree/"></mvc:resources> 
​
<mvc:resources mapping="/Images/**" location="/Images/"></mvc:resources> 
​
<mvc:resources mapping="/img/**" location="/img/"></mvc:resources> 
​
<mvc:resources mapping="/Script/**" location="/Script/"></mvc:resources> 
​
<mvc:resources mapping="/Style/**" location="/Style/"></mvc:resources> 
​
或者: 
​
<mvc:default-servlet-handler></mvc:default-servlet-handler>

6.配置controller文件

使用的注解:@Controller,@RequestMapping,@AutoWired,@Qualififier("empBiz")

7.添加service,dao层

使用的注解:@Service ,@AutoWired

(1) dao层省略了实现类

(2) dao 层只定义接口,由spring.xml创建dao层对象以及扫描mapper文件 (spring.xml中的MapperScannerConfigurer和context:component-scan)

注:当添加了spring-jdbc的jar包后,会自动提交事务

补充:

分页插件:

<plugins> 
​
<!-- PageHelper4.1.6 --> 
​
<plugin interceptor="com.github.pagehelper.PageHelper"> 
​
<property name="dialect" value="mysql"/> 
​
</plugin> 
​
</plugins> 

(1) 省略dao层实现类(使用MapperScannerConfifigurer替代SqlSessionTemplate):

<!--省略实现类--> 
​
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> 
​
<property name="basePackage" value="com.dao"></property> 
​
<property name="sqlSessionFactoryBeanName" value="fac"></property> 
​
</bean> 

注意:此时也可以测试使用属性文件的方式来加载数据源(支持属性文件链接数据源)

(2) maven类型的web项目加载mybatis-generator插件 (mybatis-generator:generate -e )

注意:反向生成后,最好把该指令删除,否则不小心点了之后,又会生成一遍代码,尤其是mapper.xml文件中sql语句又会生成一遍,运行时会报错。

避坑指南

1.类注入失败

解决:

  • 检查mapper.xml的配置文件的namespace路径有没有写错

  • 检查spring.xml文件中的MapperScannerConfigurer,component-scan等配置的路径有没有写错

2.SSL证书警告

WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.

原因:高版本数据库默认要使用SSL证书进行用户验证

解决办法:在spring.xml文件中,配置数据源的部分,在数据库地址后面加上useSSL=false参数。

3.增删改都要加事务注解@Transactional

作业

要求:使用ssm框架实现用户登录与退出,以及学生表得增删改查

文件树

后台部分

bean包和dao包由mybatis逆向生成

service包

  • 接口类

public interface LogService {
    //登录
    Admin login(Admin admin);
}
public interface StudentService {
    public List<Student> getAll();
    public int add(Student student);
    public Student findById(Integer id);
    public int update(Student student);
    public int deleteByPrimaryKey(Integer studentid);
}
  • 实现类

@Service
public class LogServiceImpl implements LogService {
    @Resource
    private AdminMapper adminMapper;
    @Override
    public Admin login(Admin admin) {
        return adminMapper.login(admin);
    }
}
@Service
public class StudentServiceImpl implements StudentService {
    @Resource
    StudentMapper studentMapper;
    @Override
    public List<Student> getAll() {
        return studentMapper.findAll();
    }
​
    @Override
    public int add(Student student) {
        return studentMapper.insert(student);
    }
​
    @Override
    public Student findById(Integer id) {
        return studentMapper.selectByPrimaryKey(id);
    }
​
    @Override
    public int update(Student student) {
        return studentMapper.updateByPrimaryKey(student);
    }
​
    @Override
    public int deleteByPrimaryKey(Integer studentid) {
        return studentMapper.deleteByPrimaryKey(studentid);
    }
}

controller包

@Controller
public class LogController {
    @Resource
    private LogService logService;
    @RequestMapping("/login")
    public void login(Admin admin, HttpServletResponse response){
        Admin login = logService.login(admin);
        response.setContentType("text/html;charset=utf-8");
        try {
            PrintWriter writer = response.getWriter();
            if (login!=null){
                writer.print("<script>alert('登录成功');location.href='main.jsp'</script>");
            }else{
                writer.print("<script>alert('登录失败,请检查账号密码,正在返回登录界面');location.href='index.jsp'</script>");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
​
    @RequestMapping("/logout")
    public void logout(HttpServletRequest request,HttpServletResponse response){
        //1.销毁session
        request.getSession().invalidate();
        response.setContentType("text/html;charset=utf-8");
        try {
            PrintWriter writer = response.getWriter();
            writer.print("<script>alert('退出成功,正在返回登录页面');location.href='index.jsp'</script>");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
​
}
@Controller
public class StudentController {
    @Resource
    private StudentService studentService;
    @RequestMapping("/getall")
    public String getAll(ModelMap map){
        List<Student> students = studentService.getAll();
        map.addAttribute("info",students);
        return "getall";
    }
​
    @RequestMapping("/findById")
    public String findById(Integer id,ModelMap map,HttpServletResponse response){
        Student student = studentService.findById(id);
        map.addAttribute("student",student);
        return "update";
    }
​
    @RequestMapping("/findById2")
    public String findById2(Integer id,ModelMap map,HttpServletResponse response){
        Student student = studentService.findById(id);
        map.addAttribute("student",student);
        return "delete";
    }
​
    @Transactional(rollbackFor=Exception.class)
    @RequestMapping("/add")
    public void add(Student student, HttpServletResponse response){
        int i = studentService.add(student);
        response.setContentType("text/html;charset=utf-8");
        try {
            PrintWriter writer = response.getWriter();
            if (i>0){
                writer.print("<script>alert('新增成功,正在返回主界面');location.href='main.jsp'</script>");
            }else{
                writer.print("<script>alert('新增失败,正在返回输入界面');location.href='add.jsp'</script>");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
​
    @Transactional(rollbackFor=Exception.class)
    @RequestMapping("/update")
    public  void update(Student student, HttpServletResponse response){
        int i = studentService.update(student);
        response.setContentType("text/html;charset=utf-8");
        try {
            PrintWriter writer = response.getWriter();
            if (i>0){
                writer.print("<script>alert('修改成功,正在返回主界面');location.href='main.jsp'</script>");
            }else {
                writer.print("<script>alert('修改失败,正在返回输入界面');location.href='find.jsp'</script>");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
​
    @Transactional(rollbackFor=Exception.class)
    @RequestMapping("/delete")
    public  void delete(Integer stuid, HttpServletResponse response){
        System.out.println(stuid);
        int i = studentService.deleteByPrimaryKey(stuid);
        response.setContentType("text/html;charset=utf-8");
        try {
            PrintWriter writer = response.getWriter();
            if (i>0){
                writer.print("<script>alert('删除成功,正在返回主界面');location.href='main.jsp'</script>");
            }else {
                writer.print("<script>alert('删除失败,正在返回输入界面');location.href='find2.jsp'</script>");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
​
}

配置文件

mapper包由mybatis逆向工程生成

mybatis逆向工程配置文件generatorConfig.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
        PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
        "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
​
<!-- 配置生成器 -->
<generatorConfiguration>
    <!--数据库驱动jar -->
    <classPathEntry
            location="E:\maven_repository\mysql\mysql-connector-java\5.1.40\mysql-connector-java-5.1.40.jar" />
​
    <context id="MyBatis" targetRuntime="MyBatis3">
​
        <!--去除注释 -->
        <commentGenerator>
            <property name="suppressAllComments" value="true" />
        </commentGenerator>
​
        <!--数据库连接 -->
        <jdbcConnection driverClass="com.mysql.jdbc.Driver"
                        connectionURL="jdbc:mysql://localhost:3306/water?useUnicode=true&amp;characterEncoding=utf-8&amp;useSSL=false"
                        userId="root"
                        password="">
        </jdbcConnection>
​
        <!--生成实体类 指定包名 以及生成的地址 (可以自定义地址,但是路径不存在不会自动创建
        使用Maven生成在target目录下,会自动创建) -->
        <javaModelGenerator targetPackage="com.xzk.bean"
                            targetProject="G:\kaikeba\charpter12 SSM\homework_SSM\src\main\java">
            <property name="trimStrings" value="true" />
        </javaModelGenerator>
​
​
        <!--生成SQLmapper文件 -->
        <sqlMapGenerator targetPackage="mapper"
                         targetProject="G:\kaikeba\charpter12 SSM\homework_SSM\src\main\resources">
        </sqlMapGenerator>
        <!--生成Dao文件,生成接口 -->
        <javaClientGenerator type="XMLMAPPER"
                             targetPackage="com.xzk.dao"
                             targetProject="G:\kaikeba\charpter12 SSM\homework_SSM\src\main\java">
        </javaClientGenerator>
​
​
        <table tableName="admin" enableCountByExample="false"
               enableUpdateByExample="false" enableDeleteByExample="false"
               enableSelectByExample="false" selectByExampleQueryId="false">
        </table>
​
​
    </context>
</generatorConfiguration>

mybatis分页插件以及文件夹别名配置文件mybatis.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>
        <!--<typeAlias type="com.yhp.bean.Student" alias="stu"></typeAlias>-->
        <package name="com.xzk.bean"></package>
    </typeAliases>
<!--分页插件-->
    <plugins>
        <!-- PageHelper4.1.6 -->
        <plugin interceptor="com.github.pagehelper.PageHelper">
            <property name="dialect" value="mysql"/>
        </plugin>
    </plugins>
​
</configuration>

spring配置文件spring.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:p="http://www.springframework.org/schema/p"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       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/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
    <!-- 1.配置数据源-->
    <bean id="db" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
        <property name="url" value="jdbc:mysql://localhost:3306/water?useUnicode=true&amp;characterEncoding=utf-8&amp;useSSL=false"></property>
        <property name="username" value="root"></property>
        <property name="password" value=""></property>
    </bean>
    <!--2.创建sqlSessionFactory-->
    <bean id="fac" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="db"></property>
        <property name="configLocation" value="classpath:mybatis.xml"></property> <!--指定mybatis的配置文件路径-->
        <property name="mapperLocations" value="classpath:mapper/*.xml"></property><!--指定mybatis的mapper文件路径-->
    </bean>
    <!--3.创建MapperScannerConfigurer,用于省略dao的实现类-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="sqlSessionFactoryBeanName" value="fac"></property>
        <property name="basePackage"  value="com.xzk.dao"></property><!--接口所在包的路径-->
    </bean>
    <!--4.配置事务-->
    <bean id="mytx" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="db"></property>
    </bean>
    <tx:annotation-driven transaction-manager="mytx"></tx:annotation-driven>
    <!--5.启用springmvc注解-->
    <mvc:annotation-driven></mvc:annotation-driven>
    <!--6.配置视图解析器-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/"/>
        <property name="suffix" value=".jsp"></property>
    </bean>
    <!--7.扫描注解包-->
    <context:component-scan base-package="com.xzk"></context:component-scan>
    <!--8.配置静态资源访问-->
    <mvc:default-servlet-handler></mvc:default-servlet-handler>
</beans>

maven插件配置文件pom.xml

 <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.7</maven.compiler.source>
    <maven.compiler.target>1.7</maven.compiler.target>
    <springversion>5.0.8.RELEASE</springversion>
  </properties>
​
  <dependencies>
​
    <!-- 加入ServletAPI -->
​
    <dependency>
​
      <groupId>javax.servlet</groupId>
​
      <artifactId>javax.servlet-api</artifactId>
​
      <version>3.1.0</version>
​
      <scope>provided</scope>
​
    </dependency>
​
    <!-- MySQL依赖 start -->
​
    <dependency>
​
      <groupId>mysql</groupId>
​
      <artifactId>mysql-connector-java</artifactId>
​
      <version>5.1.38</version>
​
    </dependency>
​
    <!-- 加入MyBatis 依赖 start -->
​
    <dependency>
​
      <groupId>org.mybatis</groupId>
​
      <artifactId>mybatis</artifactId>
​
      <version>3.2.8</version>
​
    </dependency>
​
    <!-- 引入Spring(包含SpringMVC) 依赖 start -->
​
    <dependency>
​
      <groupId>org.springframework</groupId>
​
      <artifactId>spring-core</artifactId>
​
      <version>${springversion}</version>
​
    </dependency>
​
    <dependency>
​
      <groupId>org.springframework</groupId>
​
      <artifactId>spring-web</artifactId>
​
      <version>${springversion}</version>
​
    </dependency>
​
    <dependency>
​
      <groupId>org.springframework</groupId>
​
      <artifactId>spring-oxm</artifactId>
​
      <version>${springversion}</version>
​
    </dependency>
​
    <dependency>
​
      <groupId>org.springframework</groupId>
​
      <artifactId>spring-tx</artifactId>
​
      <version>${springversion}</version>
​
    </dependency>
​
    <dependency>
​
      <groupId>org.springframework</groupId>
​
      <artifactId>spring-jdbc</artifactId>
​
      <version>${springversion}</version>
​
    </dependency>
​
    <dependency>
​
      <groupId>org.springframework</groupId>
​
      <artifactId>spring-webmvc</artifactId>
​
      <version>${springversion}</version>
​
    </dependency>
​
    <dependency>
​
      <groupId>org.springframework</groupId>
​
      <artifactId>spring-aop</artifactId>
​
      <version>${springversion}</version>
​
    </dependency>
​
    <dependency>
​
      <groupId>org.springframework</groupId>
​
      <artifactId>spring-context-support</artifactId>
​
      <version>${springversion}</version>
​
    </dependency>
​
    <dependency>
​
      <groupId>org.springframework</groupId>
​
      <artifactId>spring-test</artifactId>
​
      <version>${springversion}</version>
​
    </dependency>
​
    <!-- 引用插件依赖:MyBatis整合Spring,如果mybatis版本在3.4及以上版本
​
    mybatis-spring的版本要在1.3以上 -->
​
    <dependency>
​
      <groupId>org.mybatis</groupId>
​
      <artifactId>mybatis-spring</artifactId>
​
      <version>1.2.2</version>
​
    </dependency>
​
    <!-- JSTL -->
​
    <dependency>
​
      <groupId>jstl</groupId>
​
      <artifactId>jstl</artifactId>
​
      <version>1.2</version>
​
    </dependency>
​
    <!-- 德鲁伊数据连接池 -->
​
    <dependency>
​
      <groupId>com.alibaba</groupId>
​
      <artifactId>druid</artifactId>
​
      <version>1.0.9</version>
​
    </dependency>
​
    <!-- pagehelper -->
​
    <dependency>
​
      <groupId>com.github.pagehelper</groupId>
​
      <artifactId>pagehelper</artifactId>
​
      <version>4.1.6</version>
​
    </dependency>
​
    <!--处理json-->
​
    <dependency>
​
      <groupId>com.fasterxml.jackson.core</groupId>
​
      <artifactId>jackson-databind</artifactId>
​
      <version>2.9.5</version>
​
    </dependency>
​
    <!--javaee-->
​
    <dependency>
​
      <groupId>javax</groupId>
​
      <artifactId>javaee-api</artifactId>
​
      <version>7.0</version>
​
      <scope>provided</scope>
​
    </dependency>
​
    <!--文件上传下载-->
​
    <dependency>
​
      <groupId>commons-fileupload</groupId>
​
      <artifactId>commons-fileupload</artifactId>
​
      <version>1.3.1</version>
​
    </dependency>
​
    <dependency>
​
      <groupId>commons-io</groupId>
​
      <artifactId>commons-io</artifactId>
​
      <version>2.4</version>
​
    </dependency>
​
    <dependency>
​
      <groupId>org.mybatis.generator</groupId>
​
      <artifactId>mybatis-generator-core</artifactId>
​
      <version>1.3.5</version>
​
    </dependency>
​
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>
  </dependencies>
​
  <build>
    <finalName>homework_SSM</finalName>
    <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
      <plugins>
        <plugin>
          <artifactId>maven-clean-plugin</artifactId>
          <version>3.1.0</version>
        </plugin>
        <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
        <plugin>
          <artifactId>maven-resources-plugin</artifactId>
          <version>3.0.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-compiler-plugin</artifactId>
          <version>3.8.0</version>
        </plugin>
        <plugin>
          <artifactId>maven-surefire-plugin</artifactId>
          <version>2.22.1</version>
        </plugin>
        <plugin>
          <artifactId>maven-war-plugin</artifactId>
          <version>3.2.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-install-plugin</artifactId>
          <version>2.5.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-deploy-plugin</artifactId>
          <version>2.8.2</version>
        </plugin>
        <plugin>
​
          <groupId>org.mybatis.generator</groupId>
​
          <artifactId>mybatis-generator-maven-plugin</artifactId>
​
          <version>1.3.5</version>
​
          <configuration>
​
            <!--配置⽂件的路径-->
​
​
​
            <configurationFile>src/main/resources/generatorConfig.xml</configurationFile>
​
            <overwrite>true</overwrite>
​
          </configuration>
​
          <dependencies>
​
            <dependency>
​
              <groupId>org.mybatis.generator</groupId>
​
              <artifactId>mybatis-generator-core</artifactId>
​
              <version>1.3.5</version>
​
            </dependency>
​
          </dependencies>
​
        </plugin>
​
      </plugins>
    </pluginManagement>
  </build>
</project>

前端部分

web配置文件web.xml(设置编码格式以及过滤器,以及提升为web-app2.5版本)

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
​
         xmlns="http://java.sun.com/xml/ns/javaee"
​
         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>Archetype Created Web Application</display-name>
  <servlet>
​
    <servlet-name>mvc</servlet-name>
​
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
​
    <init-param>
​
      <param-name>contextConfigLocation</param-name>
​
      <param-value>classpath:spring.xml</param-value>
​
    </init-param>
​
  </servlet>
​
  <servlet-mapping>
​
    <servlet-name>mvc</servlet-name>
​
    <url-pattern>/</url-pattern>
​
  </servlet-mapping>
​
  <filter>
​
    <filter-name>aa</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>aa</filter-name>
​
    <url-pattern>/*</url-pattern>
​
  </filter-mapping>
</web-app>

登录页面index.jsp

<html>
<body>
<h2>用户登录界面</h2>
    <form action="/login" method="post">
    用户名:<input type="text" name="username"><br>
    密码:<input type="text" name="password"><br>
    <input type="submit" value="登录">
    </form>
</body>
</html>

主界面

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
    <head>
        <title>Title</title>
    </head>
    <body>
        <h1>主界面</h1>
        <a href="/getall">查询所有信息</a><br>
        <a href="/add.jsp">新增信息</a><br>
        <a href="/find.jsp">修改信息</a><br>
        <a href="/find2.jsp">删除信息</a><br>
        <a href="/logout">退出</a>
    </body>
</html>

 

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
    <head>
        <title>Title</title>
    </head>
    <body>
        <h1>添加学生信息</h1>
        <form action="/add" method="post">
            编号:<input type="text" name="studentno"><br>
            姓名:<input type="text" name="stuname"><br>
            年龄:<input type="text" id="age" name="stuage"><br>
            班级:<input type="text" id="grade" name="gradeid">(班级编号为1-9)<br>
            <input type="submit" id="insert" value="保存">
        </form>
    </body>
</html>

 

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
    <head>
        <title>Title</title>
    </head>
    <body>
        <h1>删除学生信息</h1>
        <form action="/findById2" method="post">
            请输入学生的id:<input name="id">
            <input type="submit" value="立即查找">
        </form>
    </body>
</html>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
    <head>
        <title>Title</title>
    </head>
    <body>
        <c:if test="${student==null}">
            <script>alert('查无此人,请确认id是否输入有误,正在返回查询页面');location.href="find2.jsp"</script>
        </c:if>
        <c:if test="${student!= null}">
            <form action="/delete" method="post">
                查找的信息如下:
                <p>id:<input  type="text" name="stuid" readonly="on" value="${student.studentid}"></p>
                <p>编号:<input type="text"  name="studentno" readonly="disabled"  value="${student.studentno}"></p>
                <p>姓名:<input type="text"  name="stuname" readonly="disabled"  value="${student.stuname}"></p>
                <p>年龄:<input type="text"  name="stuage" readonly="disabled" value="${student.stuage}"></p>
                <p>班级:<input type="text" name="gradeid" readonly="disabled" value="${student.gradeid}"></p>
                <input type="submit" value="删除">
            </form>
        </c:if>
    </body>
</html>

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
    <head>
        <title>Title</title>
    </head>
    <body>
        <h1>修改学生信息</h1>
        <form action="/findById" method="post">
            请输入学生的id:<input name="id">
            <input type="submit" value="立即查找">
        </form>
    </body>
</html>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
    <head>
        <title>Title</title>
        <script src="../jquery2.1.4.js"></script>
        <script>
            $(function () {
                $(".p:eq(0)").hide();
                $("#p1").hide();
            })
        </script>
    </head>
    <body>
        <c:if test="${student==null}">
            <script>alert('查无此人,请确认id是否输入有误,正在返回查询页面');location.href="find.jsp"</script>
        </c:if>
        <c:if test="${student != null}">
        <form action="/update" method="post">
        查找的信息如下:
            <p id="p1" type="hidden">id:<input type="hidden" id="studentid" name="studentid" value="${student.studentid}"></p>
            <p>编号:<input type="text"  name="studentno" value="${student.studentno}"></p>
            <p>姓名:<input type="text"  name="stuname" value="${student.stuname}"></p>
            <p>年龄:<input type="text"  name="stuage" value="${student.stuage}"></p>
            <p>班级:<input type="text" name="gradeid" value="${student.gradeid}"></p>
            <input type="submit" value="修改">
        </form>
        </c:if>
    </body>
</html>

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
    <head>
        <title>查询所有信息</title>
    </head>
    <body>
        <form action="/getall" method="post">
        <table border="1" width="600" >
            <tbody>
        <tr>
            <td>studentid</td>
            <td>studentno</td>
            <td>stuname</td>
            <td>stuage</td>
            <td>gradeid</td>
        </tr>
        <c:if test="${info.size()>0}">
        <c:forEach items="${info}" var="student">
            <tr>
                <td>${student.studentid}</td>
                <td>${student.studentno}</td>
                <td>${student.stuname}</td>
                <td>${student.stuage}</td>
                <td>${student.gradeid}</td>
            </tr>
        </c:forEach>
        </c:if>
        <c:if test="${info.size()==0}">
            <tr>
                <td colspan="5"> <h3 align="center">没有任何数据</h3> </td>
            </tr>
        </c:if>
            </tbody>
        </table>
        </form>
    </body>
</html>

注意

  • 1.使input文本框不可编辑的3种方法

  • 2.el表达式的表达式判断是在{}里面

  • 3.JQ的$function是编译入口,就像main是jvm的入口。

  • 4.修改和删除因为需要先查找,然后做数据回显,再做修改或者删除。所以要分开成两个页面来写,不可以写在同一个页面

  • controller层的增删改方法需要添加事务注解@Transactional(rollbackFor=Exception.class)

标签:框架,spring,JavaEE,springframework,SSM,student,mybatis,org,public
来源: https://blog.csdn.net/qq_36279562/article/details/112687313

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有