SpringMVC进阶操作【SSM整合】

文章目录

  • SpringMVC进阶操作
    • 1 请求转发和重定向
    • 2 SpringMVC响应JSON格式
    • 3 SSM整合【*】
      • 3.1 创建数据库表
      • 3.2 创建maven工程,导入jar包
      • 3.3 创建和完善功能模块
      • 注意:此处项目结构少写了service实现层,大家补上即可【service层是接口,serviceImpl是类】
      • 3.4 创建对应配置文件
        • 3.4.1 【jdbc.properties】
        • 3.4.2 【log4j2】
        • 3.4.2 【springmvc.xml】
        • 3.4.3 applicationContext.xml
        • 3.4.4 web.xml
      • 3.5 创建相关层代码
        • 3.5.1【pojo层】
        • 3.5.2 【mapper层】
        • 3.5.3 【service层及实现类】
        • 3.5.4 【controller】
        • 3.5.4 【mapper.xml】
  • 拓展:

SpringMVC进阶操作

1 请求转发和重定向

包括使用传统的方式和使用SpringMVC的方式

/**
     * 使用传统的request和response【ServletAPI方式】
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping("/test01")
    public void test01(HttpServletRequest request, HttpServletResponse response) throws Exception {
        //请求转发
//        request.getRequestDispatcher("/forwardPage.jsp").forward(request, response);
        //响应重定向【响应重定向如果前面加了/需要从项目上下文路径算起】
        response.sendRedirect(request.getContextPath() + "/redirectPage.jsp");
    }

    /**
     * SpringMVC中依赖DispatcherServlet
     * 通过redirect关键字和forward关键字来实现【forward关键字可以省略】
     * @return
     */
    @RequestMapping("/test02")
    public String test02(){
//        return "forward:/forwardPage.jsp";[forward关键字可以省略]
//        return "/forwardPage.jsp";
        return "redirect:/redirectPage.jsp";
    }

	//view方式
    @RequestMapping("/test03")
    public View test03(HttpServletRequest request){
        View view = null;
//        view = new InternalResourceView("/forwardPage.jsp");
        view = new RedirectView(request.getContextPath() + "/redirectPage.jsp");
        return view;
    }

我们也可以使用ModelAndView方式,mv.setViewName()/mv.setView()

2 SpringMVC响应JSON格式

①导入jackson

<dependency>
  <groupId>com.fasterxml.jackson.core</groupId>
  <artifactId>jackson-databind</artifactId>
  <version>2.13.2.2</version>
</dependency>

②导入jquery并在springmvc.xml中配置静态资源放行:

<mvc:resources mapping="js/**" location="/js/"/>

③编写testAjaxController:

@RestController
public class TestAjaxController {

    @RequestMapping("/testAjax")
    public Pet testAjax(Person p){
        System.out.println(p);
        Pet pet = new Pet("xiaohuang", "dog");
        return pet;
    }
}

④编写testAjax.jsp页面:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Titletitle>
    <script src="js/jquery-3.4.1.js">script>
    <script>
        $(function (){
            $("#btn").click(function (){
                $.get("testAjax", {name:"zhangsan", age:"21"}, function (data){
                    console.log(data.name)
                    console.log(data.type)
                })
            })
        })
    script>
head>
<body>
    <input type="button" id="btn" value="testAjax">
body>
html>

拓展:
【1】Controller返回值是void:如果配置了视图解析器,那么SpringMVC会根据controller的RequestMapping找到对应的页面;如果没有配置,那么会报500异常,但是控制单元仍然可以正常进行

@Controller
public class TestVoidController {
    @RequestMapping("/testVoid")
    public void testVoid(){
        System.out.println("void controller....");
    }
}

3 SSM整合【*】

3.1 创建数据库表

SpringMVC进阶操作【SSM整合】_第1张图片

3.2 创建maven工程,导入jar包

<?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.0</modelVersion>

    <groupId>org.example</groupId>
    <artifactId>ssm_01</artifactId>
    <version>1.0-SNAPSHOT</version>

    <dependencies>
        <!--spring核心容器-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.3.21</version>
        </dependency>
        <!--spring aop-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aop</artifactId>
            <version>5.3.21</version>
        </dependency>
        <!--aop联盟包-->
        <dependency>
            <groupId>aopalliance</groupId>
            <artifactId>aopalliance</artifactId>
            <version>1.0</version>
        </dependency>
        <!--druid连接池-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.2.6</version>
        </dependency>
        <!--mysql驱动-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.28</version>
        </dependency>
        <!--springJDBC包-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.3.21</version>
        </dependency>
        <!--spring orm映射依赖-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>5.3.16</version>
        </dependency>
        <!--apache commons 第三方 日志包-->
        <dependency>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
            <version>1.2</version>
        </dependency>
        <!--log4j2日志-->
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-slf4j-impl</artifactId>
            <version>2.14.0</version>
        </dependency>
        <!--lombok-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.22</version>
        </dependency>
        <!--spring-test-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>5.3.21</version>
        </dependency>
        <!--junit5-->
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-api</artifactId>
            <version>5.8.2</version>
            <scope>test</scope>
        </dependency>
        <!--springMVC核心组件-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>5.3.21</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.3.21</version>
        </dependency>
        <!--jsp 和 servlet依赖-->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>4.0.1</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>4.0.1</version>
        </dependency>
        <!--json依赖-->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.13.2.2</version>
        </dependency>
        <!--myBatis的核心jar包-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.9</version>
        </dependency>
        <!--spring 与 mybatis 整合包-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>2.0.7</version>
        </dependency>
    </dependencies>


    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.8.1</version>
                <configuration>
                    <source>8</source>
                    <target>8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

3.3 创建和完善功能模块

【基于webapp模板构建出来的项目结构并不完成】
整个项目的结构如下:
SpringMVC进阶操作【SSM整合】_第2张图片

注意:此处项目结构少写了service实现层,大家补上即可【service层是接口,serviceImpl是类】

3.4 创建对应配置文件

3.4.1 【jdbc.properties】
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mp?serverTimezone=UTC
jdbc.username=root
jdbc.password=123456
3.4.2 【log4j2】
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="INFO">
    <Appenders>
        <Console name="Console" target="SYSTEM_ERR">
            <PatternLayout pattern="%d{YYYY-MM-dd HH:mm:ss}
[%t] %-5p %c{1}:%L - %msg%n"/>
        </Console>
    </Appenders>
    <Loggers>
        <Root level="DEBUG">
            <AppenderRef ref="Console"/>
        </Root>
    </Loggers>
</Configuration>

3.4.2 【springmvc.xml】

<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:mvc="http://www.springframework.org/schema/mvc"
       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
">

    
    <context:component-scan base-package="com.zi.controller">context:component-scan>
    
    
    <mvc:annotation-driven/>
    
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="suffix" value=".jsp">property>
    bean>
    
    <mvc:resources mapping="/js/**" location="/js/">mvc:resources>
    <mvc:resources mapping="/css/**" location="/css/">mvc:resources>
    <mvc:resources mapping="/static/**" location="/static/">mvc:resources>


beans>
3.4.3 applicationContext.xml

<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: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/tx
       http://www.springframework.org/schema/tx/spring-tx.xsd
       ">
    
    <context:property-placeholder location="classpath:jdbc.properties">context:property-placeholder>
    
    <context:component-scan base-package="com.zi.service">context:component-scan>
    
    <bean class="com.alibaba.druid.pool.DruidDataSource" id="dataSource">
        <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 class="org.mybatis.spring.SqlSessionFactoryBean" id="factory">
        <property name="dataSource" ref="dataSource">property>
        
        <property name="typeAliasesPackage" value="com.zi.pojo">property>
    bean>

    
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        
        <property name="sqlSessionFactoryBeanName" value="factory">property>
        
        <property name="basePackage" value="com.zi.mapper">property>
    bean>
    
    <bean class="org.springframework.jdbc.datasource.DataSourceTransactionManager" id="transactionManager">
        <property name="dataSource" ref="dataSource">property>
    bean>
    
    <tx:annotation-driven transaction-manager="transactionManager"/>

beans>
3.4.4 web.xml

<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         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">

    
    <context-param>
        <param-name>contextConfigLocationparam-name>
        <param-value>classpath:applicationContext.xmlparam-value>
    context-param>
    
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>
    listener>
    
    <filter>
        <filter-name>encodingFilterfilter-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>encodingFilterfilter-name>
        <url-pattern>/*url-pattern>
    filter-mapping>

    
    <servlet>
        <servlet-name>dispatcherServletservlet-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>dispatcherServletservlet-name>
        <url-pattern>/url-pattern>
    servlet-mapping>
web-app>

3.5 创建相关层代码

3.5.1【pojo层】

user.java

@Data
@AllArgsConstructor
@NoArgsConstructor
public class User implements Serializable {
    private Integer uid;
    private String uname;
    private String upwd;
}

3.5.2 【mapper层】

UserMapper

public interface UserMapper {
    /**
     * 根据用户名、密码查询用户
     * @param uname
     * @param upwd
     * @return
     */
    User findUser(String uname, String upwd);

    List<User> findAllUser();
}
3.5.3 【service层及实现类】

UserService:

public interface UserService {
    public User findUser(String uname, String upwd);

    public List<User> findAllUser();
}

UserServiceImpl:

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    public User findUser(String uname, String upwd) {
        User user = null;
        user = userMapper.findUser(uname, upwd);
        return user;
    }

    public List<User> findAllUser() {
        return userMapper.findAllUser();
    }
}

3.5.4 【controller】

UserController:

@Controller
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping("/findUser")
    private String findUser(String uname, String upwd){
        User user = userService.findUser(uname, upwd);
        if(user != null){
            return "success";
        } else{
            return "fail";
        }
    }

    //以json格式返回所有用户信息
    @ResponseBody
    @RequestMapping("/findAll")
    public List<User> findAllUser(){
        return userService.findAllUser();
    }
}
3.5.4 【mapper.xml】

UserMapper.xml


DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.zi.mapper.UserMapper">
    
    <select id="findUser" resultType="user">
        select * from user where uname = #{param1} and upwd = #{param2}
    select>

    
    <select id="findAllUser" resultType="user">
        select * from user
    select>
mapper>

拓展:

war模式:将web工程以war包的形式上传到服务器
war exploed模式:将web工程以当前文件夹的位置关系上传到服务器

你可能感兴趣的:(框架,servlet,java,开发语言)