Java笔记之SSM项目整合

1.新建Dynamic Web Project项目ssm

2.导入jar包,并Build Path

3.配置web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
  
  <!-- 配置Spring的监听器 -->
  <listener>
      <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  <!-- 配置Spring的配置文件位置 -->
  <context-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:applicationContext.xml</param-value>
  </context-param>
  
  <!-- 配置SpringMVC的前端控制器 -->
  <servlet>
      <servlet-name>springmvc</servlet-name>
      <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
      <!-- 配置SpringMVC的配置文件位置 -->
      <init-param>
          <param-name>contextConfigLocation</param-name>
          <param-value>classpath:springmvc.xml</param-value>
      </init-param>
      <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
      <servlet-name>springmvc</servlet-name>
      <!-- 拦截所有请求 -->
      <url-pattern>/</url-pattern>
  </servlet-mapping>
  
  <!-- 配置post请求的编码过滤器 -->
  <filter>
      <filter-name>CharacterEncodingFilter</filter-name>
      <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
      <!-- 设置编码方式为UTF-8 -->
      <init-param>
          <param-name>encoding</param-name>
          <param-value>UTF-8</param-value>
      </init-param>
  </filter>
  <filter-mapping>
      <filter-name>CharacterEncodingFilter</filter-name>
      <!-- 过滤所有请求 -->
      <url-pattern>/*</url-pattern>
  </filter-mapping>
  
  <display-name>ssm</display-name>
  <welcome-file-list>
    <welcome-file>/WEB-INF/jsp/index.jsp</welcome-file>
  </welcome-file-list>
</web-app>

4.配置jdbc.properties

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

 5.配置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:tx="http://www.springframework.org/schema/tx"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        https://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/tx
        https://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/aop
        https://www.springframework.org/schema/aop/spring-aop.xsd">
       
    <!-- 开启注解扫描,指定基础包下的所有类对象都交给Spring创建和管理 -->
    <context:component-scan base-package="com.ssm.service"></context:component-scan>
    <context:component-scan base-package="com.ssm.serviceImpl"></context:component-scan>
    <!-- 加载jdbc配置文件 -->
    <context:property-placeholder location="classpath:jdbc.properties"/>
    <!-- 配置数据库资源池 -->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="${jdbc.driver}"></property>
        <property name="url" value="${jdbc.url}"></property>
        <property name="username" value="${jdbc.username}"></property>
        <property name="password" value="${jdbc.password}"></property>
    </bean>
    <!-- 配置会话工厂 -->
    <bean id="sqlSessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"></property>
        <!-- 配置mybatis配置文件位置 -->
        <property name="configLocation" value="classpath:mybatisConfig.xml"></property>
    </bean>
    <!-- 配置事务管理  -->
    <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"></property>
    </bean>
    <!-- 配置事务通知 -->
    <tx:advice id="txAdvice" transaction-manager="txManager">
        <tx:attributes>
            <tx:method name="get*" propagation="SUPPORTS"/>
            <tx:method name="save*" propagation="REQUIRED"/>
            <tx:method name="update*" propagation="REQUIRED"/>
            <tx:method name="delete*" propagation="REQUIRED"/>
        </tx:attributes>
    </tx:advice>
    <!-- 配置切面 -->
    <aop:config>
        <aop:pointcut expression="execution(* com.ssm.serviceImpl.*.*(..))" id="pointCut"/>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="pointCut"/>
    </aop:config>
    <!-- 配置Mapper扫描器,使用会话工厂创建Mapper的代理对象并注入Spring容器中 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.ssm.mapper"></property>
    </bean>
</beans>

6.配置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:mvc="http://www.springframework.org/schema/mvc"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/mvc
        https://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/context
        https://www.springframework.org/schema/context/spring-context.xsd">
    <!-- 开启注解扫描,配置Controller类所在的包信息 -->
    <context:component-scan base-package="com.ssm.controller"></context:component-scan>
    <!-- 配置SpringMVC的注解驱动,默认添加注解形式的处理器映射器和处理器适配器,以及一系列的消息转换器 -->
    <mvc:annotation-driven></mvc:annotation-driven>
    <!-- 访问静态资源 -->
    <mvc:default-servlet-handler/>
    <!-- 配置视图解析器 -->
    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>
    <!-- 配置文件上传解析器,这里的id一定要配置成multipartResolver,否则会报错 -->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!-- 设置上传文件的最大大小,这里设置的是10M(=10*1024*1024) -->
        <property name="maxUploadSize" value="10485760"></property>
    </bean>   
</beans>

7.配置mybatisConfig.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>
    <settings>
        <!-- 开启驼峰命名规则映射 -->
        <setting name="mapUnderscoreToCamelCase" value="true"/>
        <!-- 开启延时加载 -->
        <setting name="lazyLoadingEnabled" value="true"/>
        <!-- 将积极加载改为消极加载,也就是按需加载 -->
        <setting name="aggressiveLazyLoading" value="false"/>
    </settings>
    <!-- 为该包下的类起别名 -->
    <typeAliases>
        <package name="com.ssm.bean"/>
    </typeAliases>
    <!-- 配置Mapper映射文件的位置 -->
    <mappers>
        <package name="com.ssm.mapper"/>
    </mappers>
</configuration>

8.配置日志文件log4j.properties

log4j.rootLogger=DEBUG,stdout,FILE
log4j.addivity.org.apache=true

#stdout输出到控制台
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%-5p - %m%n

#FILE输出到文件,每天产生一个文件
log4j.appender.FILE=org.apache.log4j.DailyRollingFileAppender 
#日志文件的位置
log4j.appender.FILE.File=G:/log/ssm.log
#日志文件的编码方式
log4j.appender.FILE.File.Encoding=utf-8
log4j.appender.FILE.DatePattern="'_'yyyyMMdd"
#当天的日志使用追加的方式写入日志文件
log4j.appender.FILE.Append=true 
log4j.appender.FILE.layout=org.apache.log4j.PatternLayout 
#日志的格式
log4j.appender.FILE.layout.ConversionPattern=%-5p %c - %m%n 

9.新建Student类

package com.ssm.bean;

public class Student {
    private Integer studentId;
    private String studentName;
    private Integer studentAge;
    
    public Integer getStudentId() {
        return studentId;
    }
    public void setStudentId(Integer studentId) {
        this.studentId = studentId;
    }
    public String getStudentName() {
        return studentName;
    }
    public void setStudentName(String studentName) {
        this.studentName = studentName;
    }
    public Integer getStudentAge() {
        return studentAge;
    }
    public void setStudentAge(Integer studentAge) {
        this.studentAge = studentAge;
    }
    @Override
    public String toString() {
        return "Student [studentId=" + studentId + ", studentName=" + studentName + ", studentAge=" + studentAge + "]";
    }
    
    
}

10.新建StudentController类

package com.ssm.controller;

import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.ssm.bean.Student;
import com.ssm.service.StudentService;

@Controller
@RequestMapping("/student")
public class StudentController {
    @Resource
    private StudentService studentService;
    
    @RequestMapping("/getAllStudents")
    public String getAll(HttpServletRequest request){
        List<Student> students = studentService.getAll();
        request.setAttribute("students", students);
        return "students";
    }
}

11.新建FileController类

package com.ssm.controller;

import java.io.File;
import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

@Controller
@RequestMapping("/file")
public class FileController {
    @RequestMapping("/init")
    public String init(){
        return "fileupload";
    }
    
    @RequestMapping("/upload")
    public String upload(HttpServletRequest request,MultipartFile myFile){
        String fileName=myFile.getOriginalFilename();
        String dest = request.getServletContext().getRealPath("/upload");
        File destFile=new File(dest,fileName);
        if (!destFile.exists()) {
            destFile.mkdirs();
        }
        try {
            myFile.transferTo(destFile);
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        request.setAttribute("message", "上传成功");
        return "fileupload";
    }
}

12.新建JsonController类

package com.ssm.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ssm.bean.Student;

@Controller
@RequestMapping("/json")
public class JsonController {
    @RequestMapping("/init")
    public String init(){
        return "json";
    }
    
    @RequestMapping("/dealJson")
    @ResponseBody
    public Student dealJson(@RequestBody Student student){
        
        return student;
    }
}

13.新建StudentMapper接口

package com.ssm.mapper;

import java.util.List;

import com.ssm.bean.Student;

public interface StudentMapper {
    
    public List<Student> getAll();
}

14.新建StudentMapper.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.ssm.mapper.StudentMapper">
    <select id="getAll" resultType="Student">
        select * from t_student
    </select>
</mapper>

15.新建StudentService接口

package com.ssm.service;

import java.util.List;

import com.ssm.bean.Student;

public interface StudentService {
    
    public List<Student> getAll();
}

16.新建StudentServiceImpl类,实现StudentService接口

package com.ssm.serviceImpl;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.ssm.bean.Student;
import com.ssm.mapper.StudentMapper;
import com.ssm.service.StudentService;
@Service
public class StudentServiceImpl implements StudentService {
    @Resource
    private StudentMapper StudentMapper;
    @Override
    public List<Student> getAll() {
        return StudentMapper.getAll();
    }

}

17.WEB-INF下的jsp文件夹新建index.jsp、students.jsp、fileupload.jsp、json.jsp

index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>默认页面</title>
</head>
<body>
<a href="student/getAllStudents">查询所有的学生信息</a><br>
<a href="file/init">上传文件</a><br>
<a href="json/init">json</a>
</body>
</html>

students.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>学生列表</title>
</head>
<body>
    ${message }
    <table>
        <tr>
            <th>ID</th>
            <th>姓名</th>
            <th>年龄</th>
        </tr>
        <c:forEach items="${students }" var="stu">
            <tr>
                <td>${stu.studentId }</td>
                <td>${stu.studentName }</td>
                <td>${stu.studentAge }</td>
            </tr>
        </c:forEach>
    </table>
</body>
</html>

fileupload.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>文件上传</title>
</head>
<body>
    <form action="upload" method="post" enctype="multipart/form-data">
        <input type="file" name="myFile"/><br>
        <button type="submit">上传</button>
    </form>
    <hr>
    ${message }
</body>
</html>

json.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Json请求和响应</title>
<script type="text/javascript" src="../static/js/jquery-1.12.4.min.js"></script>
</head>
<body>
    ID:<input type="text" id="studentId"/><br>
    姓名:<input type="text" id="studentName"/><br>
    年龄:<input type="text" id="studentAge"/><br>
    <button type="button" onclick="doSent();">发送</button>
<script type="text/javascript">
    function doSent(){
        var studentId=document.getElementById("studentId").value;
        var studentName=document.getElementById("studentName").value;
        var studentAge=document.getElementById("studentAge").value;
        $.ajax({
            url:"dealJson",
            type:"post",
            contentType:"application/json;charset=utf-8",
            data:JSON.stringify({"studentId":studentId,"studentName":studentName,"studentAge":studentAge}),
            success:function(data){
                alert(data.studentId+"---"+data.studentName+"---"+data.studentAge);
            }
        });
    }
</script>
</body>
</html>

18.WebContent下新建static文件夹,在其中新建js文件夹,拷入jquery的js文件

19.数据准备

新建t_student表

USE keeper;
DROP TABLE IF EXISTS `t_student`;
CREATE TABLE `t_student`  (
  `student_id` int(11) NOT NULL AUTO_INCREMENT COMMENT '学生ID',
  `student_name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '学生姓名',
  `student_age` int(11) NULL DEFAULT NULL COMMENT '学生年龄',
  PRIMARY KEY (`student_id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 11 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;

导入数据

USE keeper;
INSERT INTO `t_student` VALUES (2, '李逵', 24);
INSERT INTO `t_student` VALUES (3, '王五', 25);
INSERT INTO `t_student` VALUES (4, '赵六', 26);
INSERT INTO `t_student` VALUES (5, '韩七', 27);
INSERT INTO `t_student` VALUES (6, '小明', 10);
INSERT INTO `t_student` VALUES (7, '张无忌', 25);
INSERT INTO `t_student` VALUES (8, '张三丰', 100);
INSERT INTO `t_student` VALUES (9, '赵云', 27);
INSERT INTO `t_student` VALUES (10, '赵三', 24);

20.启动项目,访问index.jsp页面,可以进行三项操作

 

posted @ 2020-04-10 17:57  安徒生敲代码  阅读(1514)  评论(0编辑  收藏  举报