在IntelliJ IDEA上使用Maven搭建SSM框架(三)

1.Spring的Service配置


在src/main/java下创建service包

在src/main/resources/spring下创建spring-service.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"
       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">
    <!-- 扫描service包下所有使用注解的类型 -->
    <context:component-scan base-package="org.first.service"/>

    <!-- 配置事务管理器 -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>

    <!-- 配置基于注解的声明式事务,默认使用注解 -->
    <tx:annotation-driven transaction-manager="transactionManager"/>

</beans>

使用注解实现自动装填

在service包下创建UserService.java接口:

public interface UserService {

    List<User> getAll();

    int addUser(User user);

}

在service包下创建impl包,再在impl包下实现UserService接口

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;

    public List<User> getAll() {
        return userDao.queryAll(0,4);
    }

    public int addUser(User user) {
        return userDao.insertUser(user);
    }
}

上面实现类使用@Service与@Autowired注解

使用Junit4测试Service接口

测试之前需要先配置logback配置文件,先进入logback官网  点击打开链接 ,在这里我们选择最简单的配置

在scr/maim/resources下新建logback.xml配置文件:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <!-- encoders are assigned the type
             ch.qos.logback.classic.encoder.PatternLayoutEncoder by default -->
        <encoder>
            <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
        </encoder>
    </appender>
    <root level="debug">
        <appender-ref ref="STDOUT" />
    </root>
</configuration>

Junit测试

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({
        "classpath:spring/spring-dao.xml",
        "classpath:spring/spring-service.xml"})
public class UserServiceTest {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private UserService userService;

    @Test
    public void getAll() throws Exception {
        List<User> list = userService.getAll();
        logger.info("list={}", list);
    }

    @Test
    public void addUser() throws Exception {
        User user = new User();
        user.setName("小强");
        user.setSex(1);
        int result = userService.addUser(user);
        logger.info("" + result);
    }
}

2.Spring的Web配置

在配置web之前,我们需要知道Restful:一种URI表述方式

Restful规范

GET -> 查询操作
POST -> 添加 / 修改操作
PUT -> 修改操作
DELETE- -> 删除操作

URL设计: /模块/资源/{标示}/集合1/...

接下来开始配置SpringMVC框架

1)配置src/main/webapp/WEB-INF/web.xml

<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"
         version="3.1"
         metadata-complete="true">
    <servlet>
        <servlet-name>first-dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:spring/spring-*.xml</param-value>
        </init-param>
    </servlet>
    <servlet-mapping>
        <servlet-name>first-dispatcher</servlet-name>
        <!-- 默认匹配所有的请求 -->
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>

2)在src/main/resources/spring下创建spring-web.xml配置文件

<?xml version="1.0" encoding="UTF-8"?>
<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="http://www.springframework.org/schema/beans"
       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">

    <!-- 配置SpringMVC -->
    <!-- 1:开启SpringMVC注解模式 -->
    <mvc:annotation-driven/>

    <!-- 2:静态资源默认servlet配置 -->
    <mvc:default-servlet-handler/>

    <!-- 3:配置jsp 显示ViewResolver -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>

    <!-- 4:扫描web相关的bean -->
    <context:component-scan base-package="org.first.web"/>
</beans>

配置完成后,在src/main/java下创建web包

创建UserController.java

@Controller
//URL设计:	/模块/资源/{标示}/集合1/...
@RequestMapping("/user") //url:/模块
public class UserController {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private UserService userService;

    @RequestMapping(value = "/list",method = RequestMethod.GET) // /资源
    public String list(Model model){
        List<User> list=userService.getAll();
        model.addAttribute("list",list);
        return "list";// /WEB-IBF/jsp/"list".jsp
    }

    @RequestMapping(value = "/addUser",method = RequestMethod.POST)
    public String addUser(User user,Model model){
        int result=userService.addUser(user);
        model.addAttribute("result",result);
        return "redirect:list";
    }
}

3.JSP页面显示

我们使用BootStrap来写jsp

在src\main\webapp\WEB-INF\jsp\common下创建两个jsp,分别放我们的用到的jsp头与标签

head.jsp

<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- 引入 Bootstrap -->
<link href="http://cdn.static.runoob.com/libs/bootstrap/3.3.7/css/bootstrap.min.css"
      rel="stylesheet">

<!-- HTML5 Shim 和 Respond.js 用于让 IE8 支持 HTML5元素和媒体查询 -->
<!-- 注意: 如果通过 file:// 引入 Respond.js 文件,则该文件无法起效果 -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.3.0/respond.min.js"></script>
<![endif]-->

tag.jsp

<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>

在src\main\webapp\WEB-INF\jsp\下创建list.jsp

<%@page contentType="text/html; charset=UTF-8" language="java" %>
<%-- 引入jstl--%>
<%@include file="common/tag.jsp" %>
<!DOCTYPE html>
<html>
<head>
    <title>用户列表页</title>
    <%@include file="common/head.jsp" %>
</head>
<body style="margin-top: 10px">
<form action="/user/addUser" method="post" class="form-inline" role="form">
    <div class="container">
        <div class="panel panel-default">
            <div class="panel-heading text-left">
                <h4>新增用户</h4>
            </div>
            <div class="form-group">
                <label for="name" class="control-label">用户名:</label>
                <input type="text" class="form-control" id="name" name="name" placeholder="请输入名称">
            </div>
            <div class="form-group">
                <label class="control-label">性别:</label>
                <label class="checkbox-inline">
                    <input type="radio" name="sex" value="1" checked>男
                </label>
                <label class="checkbox-inline">
                    <input type="radio" name="sex" value="0">女
                </label>
            </div>
            <div class="form-group">
                <div class="col-sm-offset-2 col-sm-10">
                    <button type="submit" class="btn btn-default">提交</button>
                </div>
            </div>
        </div>
    </div>
</form>

<%--页面显示部分--%>
<div class="container">
    <div class="panel panel-default">
        <div class="panel-heading text-center">
            <h2>用户列表</h2>
        </div>
        <div class="panel-body">
            <table class="table table-hover">
                <thead>
                <tr>
                    <th>id</th>
                    <th>名称</th>
                    <th>性别</th>
                    <th>创建时间</th>
                </tr>
                </thead>
                <tbody>
                <c:forEach var="list" items="${list}">
                    <tr>
                        <td>${list.id}</td>
                        <td>${list.name}</td>
                        <td>
                            <c:if test="${1==list.sex}">男生</c:if>
                            <c:if test="${0==list.sex}">女生</c:if>
                        </td>
                        <td>
                            <fmt:formatDate value="${list.createTime}" pattern="yyyy-MM-dd HH:mm:ss"/>
                        </td>
                    </tr>
                </c:forEach>
                </tbody>
            </table>
        </div>
    </div>
</div>
</body>

<!-- jQuery文件。务必在bootstrap.min.js 之前引入 -->
<script src="http://cdn.static.runoob.com/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- 最新的 Bootstrap 核心 JavaScript 文件 -->
<script src="http://cdn.static.runoob.com/libs/bootstrap/3.3.7/js/bootstrap.min.js"></script>

</html>

注:我在调试的时候发现插入数据库的数据发生中文乱码问题

解决方法:在web.xml中加入以下代码

<!-- 强制页面utf-8 -->
    <filter>
        <filter-name>encodingFilter</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>
        <init-param>
            <param-name>forceEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>encodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>



至此,所有配置已经完成,这篇《在IntelliJ IDEA上使用Maven搭建SSM框架》是我在看了慕课网的maven管理利器和秒杀案例再加上自己百度,一字一句打出来的,把自己所学梳理了一遍,各种相关的配置还是略为简单,还是要多看看框架源码

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值