3,从零开始搭建SSHM开发框架(集成Spring MVC)

来源:互联网 发布:python 数据分析包 编辑:程序博客网 时间:2024/05/17 04:56

目录

本专题博客已共享在(这个可能会更新的稍微一些)

https://code.csdn.net/yangwei19680827/maven_sshm_blog

1,从零开始搭建SSHM开发框架(环境准备)

2,从零开始搭建SSHM开发框架(集成Spring+JPA)

3,从零开始搭建SSHM开发框架(集成Spring MVC)

(还在写呢。。。)4,从零开始搭建SSHM开发框架(集成DWZ+Spring Security)

(还在写呢。。。)5,从零开始搭建SSHM开发框架(DWZ的使用)

(还在写呢。。。)6,从零开始搭建SSHM开发框架(集成Ehcache)

(还在写呢。。。)7,从零开始搭建SSHM开发框架(集成activemq)

(还在写呢。。。)8,从零开始搭建SSHM开发框架(集成Mybatis)

(还在写呢。。。)9,从零开始搭建SSHM开发框架(集成Redis)

1.修改pom.xml,增加spring-mvc 的依赖

<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/maven-v4_0_0.xsd">    <modelVersion>4.0.0</modelVersion>    <groupId>com.wiker</groupId>    <artifactId>sshm</artifactId>    <packaging>war</packaging>    <version>1.0-SNAPSHOT</version>    <name>sshm Maven Webapp</name>    <url>http://maven.apache.org</url>    <properties>        <hibernate-version>5.1.0.Final</hibernate-version>        <spring-version>4.2.5.RELEASE</spring-version>        <log4j-version>1.2.17</log4j-version>        <jack-json-version>2.7.3</jack-json-version>        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>        <jdk.version>1.8</jdk.version>    </properties>    <dependencies>        <!-- Hibernate -->        <dependency>            <groupId>org.hibernate</groupId>            <artifactId>hibernate-core</artifactId>            <version>${hibernate-version}</version>        </dependency>        <dependency>            <groupId>org.hibernate</groupId>            <artifactId>hibernate-entitymanager</artifactId>            <version>${hibernate-version}</version>        </dependency>        <!-- mysql 驱动 -->        <dependency>            <groupId>mysql</groupId>            <artifactId>mysql-connector-java</artifactId>            <version>5.1.38</version>        </dependency>        <!-- Spring,JPA start -->        <dependency>            <groupId>org.springframework</groupId>            <artifactId>spring-context</artifactId>            <version>${spring-version}</version>        </dependency>        <dependency>            <groupId>org.springframework</groupId>            <artifactId>spring-aop</artifactId>            <version>${spring-version}</version>        </dependency>        <dependency>            <groupId>org.springframework</groupId>            <artifactId>spring-context-support</artifactId>            <version>${spring-version}</version>        </dependency>        <dependency>            <groupId>org.springframework</groupId>            <artifactId>spring-jdbc</artifactId>            <version>${spring-version}</version>        </dependency>        <dependency>            <groupId>org.springframework.data</groupId>            <artifactId>spring-data-jpa</artifactId>            <version>1.9.4.RELEASE</version>        </dependency>        <dependency>            <groupId>org.springframework</groupId>            <artifactId>spring-orm</artifactId>            <version>${spring-version}</version>        </dependency>        <dependency>            <groupId>org.springframework</groupId>            <artifactId>spring-web</artifactId>            <version>${spring-version}</version>        </dependency>        <!-- Spring MVC -->        <dependency>            <groupId>org.springframework</groupId>            <artifactId>spring-webmvc</artifactId>            <version>${spring-version}</version>        </dependency>        <!-- 阿里的数据源 -->        <dependency>            <groupId>com.alibaba</groupId>            <artifactId>druid</artifactId>            <version>1.0.22</version>        </dependency>        <dependency>            <groupId>log4j</groupId>            <artifactId>log4j</artifactId>            <version>${log4j-version}</version>        </dependency>        <!-- jackson -->        <dependency>            <groupId>com.fasterxml.jackson.core</groupId>            <artifactId>jackson-databind</artifactId>            <version>${jack-json-version}</version>        </dependency>        <dependency>            <groupId>com.fasterxml.jackson.core</groupId>            <artifactId>jackson-core</artifactId>            <version>${jack-json-version}</version>        </dependency>        <dependency>            <groupId>com.fasterxml.jackson.core</groupId>            <artifactId>jackson-annotations</artifactId>            <version>${jack-json-version}</version>        </dependency>        <dependency>            <groupId>commons-fileupload</groupId>            <artifactId>commons-fileupload</artifactId>            <version>1.3.1</version>        </dependency>        <!-- JSP /Servlet -->        <dependency>            <groupId>javax.servlet</groupId>            <artifactId>jstl</artifactId>            <version>1.2</version>        </dependency>        <dependency>            <groupId>javax.servlet</groupId>            <artifactId>jsp-api</artifactId>            <version>2.0</version>            <scope>provided</scope>        </dependency>        <dependency>            <groupId>javax.servlet</groupId>            <artifactId>servlet-api</artifactId>            <version>2.5</version>            <scope>provided</scope>        </dependency>        <dependency>            <groupId>javax.servlet</groupId>            <artifactId>javax.servlet-api</artifactId>            <version>4.0.0-b01</version>            <scope>provided</scope>        </dependency>        <dependency>            <groupId>javax.servlet</groupId>            <artifactId>servlet-api</artifactId>            <version>2.5</version>            <scope>provided</scope>        </dependency>        <dependency>            <groupId>org.springframework</groupId>            <artifactId>spring-test</artifactId>            <version>${spring-version}</version>            <scope>test</scope>        </dependency>        <dependency>            <groupId>junit</groupId>            <artifactId>junit</artifactId>            <version>4.11</version>            <scope>test</scope>        </dependency>    </dependencies>    <build>        <finalName>sshm</finalName>    </build></project>

主要新增了如下选项

        <dependency>            <groupId>org.springframework</groupId>            <artifactId>spring-webmvc</artifactId>            <version>${spring-version}</version>        </dependency>       <dependency>            <groupId>com.fasterxml.jackson.core</groupId>            <artifactId>jackson-databind</artifactId>            <version>${jack-json-version}</version>        </dependency>        <dependency>            <groupId>com.fasterxml.jackson.core</groupId>            <artifactId>jackson-core</artifactId>            <version>${jack-json-version}</version>        </dependency>        <dependency>            <groupId>com.fasterxml.jackson.core</groupId>            <artifactId>jackson-annotations</artifactId>            <version>${jack-json-version}</version>        </dependency>        <dependency>            <groupId>commons-fileupload</groupId>            <artifactId>commons-fileupload</artifactId>            <version>1.3.1</version>        </dependency>

2.增加spring-mvc.xml

文件放到WEB-INF/下,如果你的包名和我的不一样,需要修改一下base-package="com.wiker" 中的包名

<?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:mvc="http://www.springframework.org/schema/mvc"    xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd">    <!-- 自动扫描且只扫描@Controller且包名是:com.wiker下的class -->    <context:component-scan base-package="com.wiker"        use-default-filters="false">        <context:include-filter type="annotation"            expression="org.springframework.stereotype.Controller" />    </context:component-scan>    <context:property-placeholder location="classpath*:/*.properties" />    <!-- Application Message Bundle -->    <bean id="messageSource"        class="org.springframework.context.support.ResourceBundleMessageSource">        <property name="basename" value="messages" />    </bean>    <!-- Json返回 乱码处理 -->    <bean        class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">        <property name="messageConverters">            <list>                <bean                    class="org.springframework.http.converter.ByteArrayHttpMessageConverter" />                <bean                    class="org.springframework.http.converter.StringHttpMessageConverter">                    <property name="supportedMediaTypes">                        <list>                            <value>text/plain;charset=UTF-8</value>                        </list>                    </property>                </bean>                <!-- Controller 自动转JSON -->                <bean                    class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">                    <property name="supportedMediaTypes">                        <list>                            <value>text/json;charset=UTF-8</value>                        </list>                    </property>                </bean>                <bean                    class="org.springframework.http.converter.ResourceHttpMessageConverter" />                <bean                    class="org.springframework.http.converter.xml.SourceHttpMessageConverter" />                <bean                    class="org.springframework.http.converter.xml.XmlAwareFormHttpMessageConverter" />                <bean                    class="org.springframework.http.converter.xml.Jaxb2RootElementHttpMessageConverter" />            </list>        </property>    </bean>    <mvc:annotation-driven />    <!-- 将无法mapping到Controller的path交给default servlet handler处理 -->    <mvc:default-servlet-handler />    <!-- 定义JSP文件的位置 -->    <bean        class="org.springframework.web.servlet.view.InternalResourceViewResolver">        <!-- JSP 映射路径,有些为了安全也可以配置成/WEB-INF/,这样jsp是无法直接访问的 -->        <property name="prefix" value="/" />        <property name="suffix" value=".jsp" />    </bean>    <!-- 定义无Controller的path<->view直接映射,可以当作欢迎页使用,这里就直接映射到test了 -->    <mvc:view-controller path="/" view-name="redirect:/test" /></beans>

3.修改web.xml

<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd" ><web-app>    <context-param>        <param-name>javax.servlet.jsp.jstl.fmt.localizationContext</param-name>        <param-value>messages</param-value>    </context-param>    <context-param>        <param-name>contextConfigLocation</param-name>        <param-value>            classpath:/applicationContext-service.xml        </param-value>    </context-param>    <context-param>        <param-name>spring.profiles.default</param-name>        <param-value>production</param-value>    </context-param>    <listener>        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>    </listener>    <!-- 解决乱码的问题 -->    <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>    <!-- Spring mvc的配置 -->    <servlet>        <servlet-name>springServlet</servlet-name>        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>        <init-param>            <param-name>contextConfigLocation</param-name>            <param-value>/WEB-INF/spring-mvc.xml</param-value>        </init-param>        <load-on-startup>1</load-on-startup>    </servlet>    <servlet-mapping>        <servlet-name>springServlet</servlet-name>        <url-pattern>/</url-pattern>    </servlet-mapping>  <display-name>Archetype Created Web Application</display-name></web-app>

4.给Service加一个删除的方法

package com.wiker.service;import java.util.List;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;import org.springframework.transaction.annotation.Transactional;import com.wiker.entity.TestEntity;import com.wiker.repository.TestDao;@Service@Transactional(readOnly = true)public class TestService {    @Autowired    private TestDao testDao;    @Transactional(readOnly=false)    public TestEntity add(TestEntity t){        return testDao.save(t);    }    @Transactional(readOnly=false)    public void del(long id){        testDao.delete(id);    }    public List<TestEntity> getAll(){        return (List<TestEntity>) testDao.findAll();    }}

5.测试Controller

TestController.java

package com.wiker.controller;import java.util.HashMap;import java.util.List;import java.util.Map;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Controller;import org.springframework.ui.Model;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;import org.springframework.web.bind.annotation.ResponseBody;import com.wiker.entity.TestEntity;import com.wiker.service.TestService;//要使用Controller 必须加@Controller注解也可以用@Controller("path")这里面的path相当于本Controller的根路径//如果配置成@Controller("path"),那么访问的地址应该是:http://localhost:8080/path/test@Controllerpublic class TestController {    //映射JSP测试    @RequestMapping(value = "test", method = {            RequestMethod.GET, RequestMethod.POST        })    public String test(Model model,String name) {        model.addAttribute("name", name);        return "index";    }    //测试自动转JSON    @RequestMapping(value = "test.json", method = {            RequestMethod.GET, RequestMethod.POST        })    @ResponseBody    public Map<String,Object> testJson(Model model,String name) {        Map<String,Object> map = new HashMap<String,Object>();        map.put("name", name);        return map;    }    //和Service结合,实现数据库操作。这里是注入的Service,其实直接注入Dao也是可以的    //TIPS:Service使用了事务,所以不要直接try catch,不然事务会失效    @Autowired    private TestService testService;    //获取列表    @RequestMapping(value = "testGetAll", method = {            RequestMethod.GET, RequestMethod.POST        })    public String testGetAll(Model model,String name) {        List<TestEntity> list = testService.getAll();        model.addAttribute("list", list);        return "testList";    }    //添加操作,添加后返回列表页面,这里为了简单演示就直接通过redirect的方式    //真实情况应该是根据业务需求来是重定向还是直接刷新页面等    @RequestMapping(value = "testAdd", method = {            RequestMethod.GET, RequestMethod.POST        })    public String testGetAll(Model model,TestEntity entity) {        testService.add(entity);        List<TestEntity> list = testService.getAll();        model.addAttribute("list", list);        return "redirect:/testGetAll";    }    //添加操作,添加后返回列表页面,这里为了简单演示就直接通过redirect的方式    //真实情况应该是根据业务需求来是重定向还是直接刷新页面等    @RequestMapping(value = "testDel", method = {            RequestMethod.GET, RequestMethod.POST        })    public String testDel(Model model,long id) {        testService.del(id);        return "redirect:/testGetAll";    }}

6.新增测试的JSP

testList.jsp

<%@ page contentType="text/html;charset=UTF-8" isELIgnored="false" %><%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %><c:set var="ctx" value="${pageContext.request.contextPath }"/><html><body><h2>测试数据库操作</h2><form action="${ctx }/testAdd" method="post"><input type="text" name="content"><input type="submit" value="提交"></input></form><table style="width:500px;" border="1"><tr><td>ID</td><td>Content</td><td>操作</td><tr><c:forEach var="item" items="${list }"><tr><td>${item.id }</td><td>${item.content }</td><td><a href="${ctx }/testDel?id=${item.id}">删除</a></td><tr></c:forEach></table></body></html>

7.来几张效果图

Controller测试

测试返回JSON

数据库中的记录

和service结合

8.Spring mvc扩展用法

上面已经介绍了@ResponseBody,还有其它注解如:

  • @PathVariable 用于REST风格
@RequestMapping(value = "test/{name}", method = {            RequestMethod.GET, RequestMethod.POST        })public String test(Model model,@PathVariable String name) {    model.addAttribute("name", name);    return "index";}

那么访问的url就是:http://localhost:8080/test/wiker

  • @RequestParam 用于参数绑定
@RequestMapping(value = "test", method = {            RequestMethod.GET, RequestMethod.POST        })public String test(Model model,@RequestParam("testName")String name) {    model.addAttribute("name", name);    return "index";}

那么访问URL就必须改成:http://localhost:8080/test?testName=test

  • @RequestMapping 中也有很多高级的用法,比如多个URL映射同一个URL,而且支持正则等。注解中的method属性表示用哪些方法可以方法,GET,POST,DELETE,PUT等都支持,还有一些其它属性,如图:

RequestMapping属性

eclipse 上的maven这点比较方便,想看某个类的源码,Ctrl+点击进去便可以看到,如果没有下载,会自动下载源到到本地的仓库,而且是有注释的源码。IDEA虽然也能下源码,但是点进去看没有注释,不知道是不是我设置的不对~~~

  • @InitBinder 可以用于数据精确的绑定

日期转换,这样如果数据提交的是yyyy–MM-dd格式的将自动转换为Date类型。例:

    @InitBinder    protected void initBinder(WebDataBinder binder) {        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");        CustomDateEditor editor = new CustomDateEditor(dateFormat, true);        binder.registerCustomEditor(Date.class, editor);    }

也可以手动自编写其它的类型,只需要继承PropertyEditorSupport类便可。需要的同学可以网上搜索一下使用方法

本章程序源码下载地址

http://download.csdn.net/detail/yangwei19680827/9593646

欢迎关注微信公众号(小妞妞程序员):

1 0
原创粉丝点击