3框架搭建,实现简单的登录和注册

Posted by

1.创建一个动态的web工程

基于全注解的SpringMVC+Spring4.2+hibernate4.3框架搭建,

本文为博主辛苦总结,希望自己以后返回来看的时候理解更深刻,也希望可以起到帮助初学者的作用.

转载请注明 出自 : luogg的博客园 谢谢配合!

2.导入springMvc所需要的jar包(这里可以去网上找,资源有很多)

概述

从0到1教你搭建spring+springMVC+hibernate整合框架,基于注解。
本教程框架为基于全注解的SpringMVC+Spring4.2+hibernate4.3,开发工具为myEclipse.

SpringMVC学习笔记

前两部就不详细描述了,后面才是正经代码~

详细

一.HelloWorld SpringMVC

图片 1

前端请求request,通过DispatcherServlet前端核心处理器,到达handlerMapping处理器映射,然后进入控制器Controller,将用户处理的业务封装到一个Bean(ModelAndView)中,然后通过试图解析器ViewResolver返回给前台页面.

  • 1.在web.xml中配置前端核心处理器DispatcherServlet

    <servlet>
        <servlet-name>action</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!-- 启动容器时初始化该Servlet -->
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>action</servlet-name>
        <!-- 表示那些请求交给spring mvc 处理 -->
        <url-pattern>*.do</url-pattern>
    </servlet-mapping>
    
  • 2.编写Controller

    public class HomeController extends AbstractController{

    @Override
    protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception {
        // TODO Auto-generated method stub
        System.out.println(request.getRequestURI());//springmvc/home.do
        System.out.println(request.getRequestURL());//http://localhost/springmvc/home.do
        return new ModelAndView("index");
    }
    

    }

首先有一个web.xml文件,这个属于大配置文件,由于只要写login,里面简单配置一下基本环境就可以

代码下载:

本教程框架为基于全注解的SpringMVC+Spring4.2+hibernate4.3,开发工具为myEclipse.

整体目录结构如下图:

图片 2

最近在鼓捣SpringMVC框架,现将成果都记录下来,免得前学后忘。之前用的框架一直是S2SH,一直苦于要配置一堆的配置文件,自从接触SpringMVC,发现这才是我一直想要的框架,基于全注解,开发过程中零配置,实在快哉。此教程非常适合零基础的人学习回归正题,基于全注解驱动的SpringMVC+Spring4.2+hibernate4.3框架搭建(整合)过程如下,:

开发工具为myEclipse

二.常用的HandlerMapping处理器映射

  • 1.BeanNameUrlHandlerMapping(默认)

  • 2.SimpleUrlHandlerMapping

    a.action,b.action,c.action访问的是一个controller

    <bean class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
        <!-- 支持多个url,访问同一个Controller,按id属性访问 -->
        <property name="mappings">
            <props>
                <prop key="/a.action">hiController</prop>
                <prop key="/b.action">hiController</prop>
                <prop key="/c.action">hiController</prop>
            </props>
        </property>
    </bean>
    

 

第一步:新建一个web项目

在eclipse中新建一个web项目,略。

 

三.注解方式(springmvc3.0之后全面支持注解方式)

  • 1.创建一个web工程
  • 2.加入jar包
  • 3.创建一个Controller,注解方式

    @Controller//标示这 个 类为一个控制器
    public class HomeController {

    @RequestMapping("/home.do")//访问的url
    public String hello(HttpServletRequest request){
        System.out.println(request.getRequestURL());
        return "hello";//返回到指定页面
    }
    

    }

  • 4.配置它的核心配置文件,包自动扫描.

    <context:component-scan base-package="com.luogg.controller"/>
    
    <!-- 内部资源视图解析器 -->
    <bean id="jspViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/pages/"/>
        <property name="suffix" value=".jsp"/>
    

  • 5.配置web.xml

    <servlet>
        <servlet-name>springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:com/luogg/resources/springmvc-servlet.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    
    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>*.do</url-pattern>
    </servlet-mapping>
    
  • 6.发布,测试.

在浏览器输入
http://localhost/springmvc_new/home.do时候会调到pages目录下的hello.jsp页面

<servlet>
    <servlet-name>springmvc</servlet-name>
    <servlet-class>
        org.springframework.web.servlet.DispatcherServlet
    </servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
     <servlet-name>springmvc</servlet-name>
     <url-pattern>/</url-pattern>
  </servlet-mapping>

第二步:加入所需的jar包

 

图片 3

jar包下载地址:

四.与Spring进行整合

spring负责管理service,dao,并加入自动扫描
@Service表示这个类是Service类

springmvc负责controller,并自动扫描controller层
@Controller表示这个类是controller
@RequestMapping表示用户敲入的url
在controller中,将集合给前台页面,这个集合是model对象,也是map集合,页面就会以jstl的方式来访问.
return表示返回到的前台页面

加入的这个叫Dispatcher
Servlet,可以根据servlet-name找到对应的小配置文件,也就是配置spring
MVC的文件

第三步:接下来我们开始SpringMVC容器的配置

 

为了分工明确,我们将SpringMVC的配置单独写在spring-servlet.xml里,Spring的配置写在spring-common.xml(事务、数据源、sessionFactory等等)里。

spring-common.xml和spring-servlet.xml先加入如下schemal

<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:tx="http://www.springframework.org/schema/tx"  
    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:mvc="http://www.springframework.org/schema/mvc"  
    xmlns:task="http://www.springframework.org/schema/task" xmlns:cache="http://www.springframework.org/schema/cache"  
    xmlns:util="http://www.springframework.org/schema/util"  
    xmlns:websocket="http://www.springframework.org/schema/websocket"  
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd  
                    http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.1.xsd  
                    http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd  
                    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd  
                    http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd  
                    http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.1.xsd  
                    http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache-4.1.xsd  
                    http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.1.xsd">

 

然后spring容器的配置先放下,先来配置springMVC(spring-servlet.xml)的配置

在schemal的结尾处加入这一句:default-autowire=”byName”
,依赖注入将根据name自动装配。

接下来启动注解驱动的SpringMVC功能:

<mvc:annotation-driven />

 

扫描注解包(在SpringMVC的容器里,只扫描Controller注解就行了)

<context:component-scan base-package="com.mvc.rest"  
        use-default-filters="false">  
        <context:include-filter type="annotation"  
            expression="org.springframework.stereotype.Controller" />  
</context:component-scan>

use-default-filters默认为true,默认会扫描@Component、@Controller、@Repository、@Service的注解,在这里只扫描@Controller注解是因为,SpringMVC的容器没有事务的能力,所以扫描@Repository、@Service的注解只能放在Spring的容器。也正因为如此,事务的配置要写在Spring的容器。

然后是对模型视图名称的解析,在请求时模型视图名称添加前后缀(前缀是从控制器里返回的视图的父目录,此处配置的是让容器在WEB-INF/view/下找寻对应的视图;后缀是给视图名称追加后缀名,此处配置的是jsp后缀)

<bean  class="org.springframework.web.servlet.view.InternalResourceViewResolver"  p:prefix="/WEB-INF/view/" p:suffix=".jsp" />

配置CommonsMultpartResolver,上传文件的时候要用到CommonsMultpartResolver,maxUploadSize设置上传文件的大小限制,上传文件必须先配置此解析器。

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">  
     <property name="maxUploadSize" value="10485760" />  
</bean>

配置login视图解析,在登录拦截器里,校验未登录的话,要跳转到登录页面,然后由于login页面放在WEB-INF目录下,所以设置跳转到login.jsp会跳转不过去,在此处设置如下,在返回此view-name的地方,容器便不会当作Controller的路径,当作视图的路径跳转,在拦截器里便可以跳转到login页面(此配置告诉容器,这不是一个controller的方法的路径,而是一个视图的名称,请当作视图处理)。

<mvc:view-controller path="/" view-name="login" />

拦截器的配置也是放在SpringMVC的容器里,拦截器以后的文章里再详细解说。

到此spring-servlet.xml的配置就告一段落了,spring-servlet.xml的全文如下:

<?xml version="1.0" encoding="UTF-8"?>  
<!--suppress ALL -->  
<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:tx="http://www.springframework.org/schema/tx"  
    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:mvc="http://www.springframework.org/schema/mvc"  
    xmlns:task="http://www.springframework.org/schema/task" xmlns:cache="http://www.springframework.org/schema/cache"  
    xmlns:util="http://www.springframework.org/schema/util"  
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd  
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.1.xsd  
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd  
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd  
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd  
        http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.1.xsd  
        http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache-4.1.xsd  
        http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.1.xsd"  
    default-autowire="byName">  
    <mvc:annotation-driven />  
    <!-- controller包(自动注入) -->  
    <context:component-scan base-package="com.mvc.rest" use-default-filters="false">  
      <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller" />  
    </context:component-scan>  
    <!-- 对模型视图名称的解析,在请求时模型视图名称添加前后缀 -->  
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"  
        p:prefix="/WEB-INF/view/" p:suffix=".jsp" />  
    <mvc:view-controller path="/" view-name="login" />  
    <bean id="multipartResolver"  
        class="org.springframework.web.multipart.commons.CommonsMultipartResolver">  
        <property name="maxUploadSize" value="10485760" />  
    </bean>  
    <!-- 配置拦截器, 多个拦截器,顺序执行  
        <mvc:interceptors>  
           <mvc:interceptor>  
            <mvc:mapping path="/*" />  
           <bean class="com.mvc.rest.interceptor.CommonInterceptor"></bean>   
     </mvc:interceptor> </mvc:interceptors> -->  
</beans>

 

五.springMVC于spring整合的小demo

  • 1.com.luogg.entity表示实体包,创建person类,写入id,name,sex,age属性并加入set,get,toString方法.
  • 2.com.luogg.service表示业务层,创建PersonService类,在类的前边用@Service标注,并且在com.luogg.resource包中添加appliacationContext.xml表示spring的配置文件,加入自动扫描包注解.
  • 3.在service中写一个查询所有用户的方法

    /**

     * 查询所有用户信息
     * @return
     */
    public List<Person> querryAll(){
        List<Person> list = new ArrayList<Person>(map.values());
        return list;
    }
    
  • 4.编写controller层,前后端控制器,用@Resource注解表示注入Service层的类,在springmvc-servlet.xml中配置自动扫描controller注解,并加入内部资源视图解析器

    <bean id="jspViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/pages/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
    
  • 5.编写controller中的方法,@RequestMapping(“/person/querryAll.do”)表示前端页面中点击querryAll.do链接之后进入这个方法,然后将数据返回到view.jsp页面

    /**
     * 展示所有用户信息
     * @param model
     * @return
     */
    @RequestMapping("/person/querryAll.do")
    public String querryAll(Map<String,Object> model){
        List<Person> list = personService.querryAll();
        model.put("list", list);
        return "/person/view";
    }
    
  • 6.编写view.jsp页面,循环展示数据,引入jstl<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>


    选择 用户ID 用户姓名 用户年龄 修改 删除
    ${p.id} ${p.name} ${p.age} 修改 删除

    前端链接跳转后端处理的代码
    批量删除

${pageContext.request.contextPath}

在web.xml文件同级目录下新建springmvc-servlet.xml文件,下面是springmvc-servlet.xml文件中的内容

第四步:我们配置web.xml

 

先配置CharacterEncodingFilter编码过滤器,此过滤器必须放在配置文件的最上面,有多个过滤器的时候,也应该放在第一位。encoding目标编码,forceEncoding设为true,会忽略请求来源的编码,强制使用encoding设置的编码。

<filter>  
       <filter-name>CharacterEncodingFilter</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>CharacterEncodingFilter</filter-name>  
       <url-pattern>/*</url-pattern>  
</filter-mapping>

然后配置ContextLoaderListener,此监听用来加载我们写的配置文件

<listener>  
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>  
</listener>

然后加载Spring配置文件

<context-param>  
    <param-name>contextConfigLocation</param-name>  
    <param-value>  
        classpath*:/spring/spring-common.xml  
    </param-value>  
</context-param>

接下来就是配置SpringMVC的核心Servlet,所有请求都要先经过DispatcherServlet,然后进行分发到对应的控制器。该Servlet须第一个被加载,且在初始化的时候去加载SpringMVC的配置文件——spring-servlet.xml

<servlet>  
    <servlet-name>spring-mvc</servlet-name>  
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>  
    <init-param>  
        <description>spring mvc</description>  
        <param-name>contextConfigLocation</param-name>  
        <param-value>classpath*:/spring/spring-servlet.xml</param-value>  
    </init-param>  
    <load-on-startup>1</load-on-startup>  
</servlet>

然后设置DispatcherServlet拦截的请求,此处的servlet-name,即是上面配置的DispatcherServlet的name,url-pattern设置为斜杠,则会拦截所有请求,也即静态资源html、css、js也直接请求。

<servlet-mapping>  
<servlet-name>spring-mvc</servlet-name>  
<url-pattern>/</url-pattern>  
</servlet-mapping>

为此,我们需要设置,哪些资源不进行拦截

<servlet-mapping>  
      <servlet-name>default</servlet-name>  
      <url-pattern>/html/*</url-pattern>  
</servlet-mapping>  
<servlet-mapping>  
      <servlet-name>default</servlet-name>  
      <url-pattern>/js/*</url-pattern>  
</servlet-mapping>  
<servlet-mapping>  
       <servlet-name>default</servlet-name>  
      <url-pattern>/css/*</url-pattern>  
</servlet-mapping>  
     <servlet-mapping>  
<servlet-name>default</servlet-name>  
      <url-pattern>/images/*</url-pattern>  
</servlet-mapping>

 

到此,SpringMVC就可以正常使用了。

欢迎页面的设置,原本此处只能设置视图名,*.jsp或者*.html,因为在spring-servlet.xml里设置了视图解析:<mvc:view-controller
path=”/” view-name=”login”
/>,所以,此处设置为welcome-file设置为login,容器便会将其解析为视图login.jsp,绕过WEB-INFO下的资源无法直接访问的限制。

<welcome-file-list>  
     <welcome-file>login</welcome-file>  
</welcome-file-list>

我们还可以设置error-page的页面

<error-page>  
   <error-code>404</error-code>  
   <location>/html/error/404.html</location>  
</error-page>  
<error-page>  
   <error-code>500</error-code>  
   <location>/html/error/500.html</location>  
</error-page>

为了集成hibernate,我们还要配置OpenSessionInViewFilter,此过滤器会将Hibernate的Session和一次完整的请求过程绑定起来,事务控制,必须配置此过滤器。

<filter>  
    <filter-name>openSession</filter-name>  
    <filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class>  
 </filter>  
 <filter-mapping>  
<filter-name>openSession</filter-name>  
<url-pattern>/*</url-pattern>  
 </filter-mapping>

完整的web.xml的配置如下:

<?xml version="1.0" encoding="UTF-8"?>  
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
    xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"  
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"  
    id="WebApp_ID" version="3.0">  
    <filter>  
        <filter-name>CharacterEncodingFilter</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>CharacterEncodingFilter</filter-name>  
        <url-pattern>/*</url-pattern>  
    </filter-mapping>  
    <listener>  
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>  
    </listener>  
    <context-param>  
        <param-name>contextConfigLocation</param-name>  
        <param-value>  
            classpath*:/spring/spring-common.xml  
        </param-value>  
    </context-param>  
    <servlet>  
        <servlet-name>spring-mvc</servlet-name>  
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>  
        <init-param>  
            <description>spring mvc</description>  
            <param-name>contextConfigLocation</param-name>  
            <param-value>classpath*:/spring/spring-servlet.xml</param-value>  
        </init-param>  
        <load-on-startup>1</load-on-startup>  
    </servlet>  
    <filter>  
        <filter-name>openSession</filter-name>  
        <filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class>  
    </filter>  
    <filter-mapping>  
        <filter-name>openSession</filter-name>  
        <url-pattern>/*</url-pattern>  
    </filter-mapping>  
    <servlet-mapping>  
        <servlet-name>spring-mvc</servlet-name>  
        <url-pattern>/</url-pattern>  
    </servlet-mapping>  
    <welcome-file-list>  
        <welcome-file>login</welcome-file>  
    </welcome-file-list>  
    <servlet-mapping>  
        <servlet-name>default</servlet-name>  
        <url-pattern>/html/*</url-pattern>  
    </servlet-mapping>  
    <servlet-mapping>  
        <servlet-name>default</servlet-name>  
        <url-pattern>/js/*</url-pattern>  
    </servlet-mapping>  
    <servlet-mapping>  
        <servlet-name>default</servlet-name>  
        <url-pattern>/css/*</url-pattern>  
    </servlet-mapping>  
    <servlet-mapping>  
        <servlet-name>default</servlet-name>  
        <url-pattern>/images/*</url-pattern>  
    </servlet-mapping>  
    <error-page>  
        <error-code>404</error-code>  
        <location>/html/error/404.html</location>  
    </error-page>  
    <error-page>  
        <error-code>500</error-code>  
        <location>/html/error/500.html</location>  
    </error-page>  
</web-app>

六.SpringMVC增强

 

第五步:配置spring-common.xml(数据源、事务、sessionFactory)

配置数据源jdbc.properties:

jdbc.driverClassName=com.mysql.jdbc.Driver  
jdbc.url=jdbc\:mysql\://121.40.90.125\:3306/test  
jdbc.username=root  
jdbc.password=exceptoin882465\[email protected]\#

解析properties:

<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">  
<bean id="dataSource" destroy-method="close"<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">  
<property name="dataSource" ref="dataSource" />  
<property name="hibernateProperties">  
    <props>  
            <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>  
            <prop key="hibernate.hbm2ddl.auto">update</prop>  
            <prop key="hibernate.show_sql">true</prop>  
            <prop key="hibernate.format_sql">true</prop>  
    </props>  
</property>  
<!-- 注解方式配置 -->  
<property name="packagesToScan">  
  <list>  
    <value>com.mvc.rest.entity</value>  
 </list>  
</property>  
 </bean>

packagesToScan扫描我们的hibernate实体文件。

最后配置事务

<bean id="txManager"  
        class="org.springframework.orm.hibernate4.HibernateTransactionManager">  
        <property name="sessionFactory" ref="sessionFactory" />  
    </bean>  
    <tx:advice id="txAdvice" transaction-manager="txManager">  
        <tx:attributes>  
            <tx:method name="save*" propagation="REQUIRED" />  
            <tx:method name="add*" propagation="REQUIRED" />  
            <tx:method name="edit*" propagation="REQUIRED" />  
            <tx:method name="update*" propagation="REQUIRED" />  
            <tx:method name="delete*" propagation="REQUIRED" />  
            <tx:method name="register*" propagation="REQUIRED" />  
            <tx:method name="all" propagation="REQUIRED" />  
            <tx:method name="changePassword*" propagation="REQUIRED" />  
            <tx:method name="restPassword*" propagation="REQUIRED" />  
            <tx:method name="authorize*" propagation="REQUIRED" />  
            <tx:method name="send*" propagation="REQUIRED" />  
            <tx:method name="init*" propagation="REQUIRED" />  
            <!-- <tx:method name="*" read-only="true"/> -->  
        </tx:attributes>  
    </tx:advice>  
    <aop:config>  
        <aop:pointcut id="serviceOperation"  
            expression="execution(* com.mvc.rest.service.impl.*.*(..))" />  
        <aop:advisor advice-ref="txAdvice" pointcut-ref="serviceOperation" />  
</aop:config>

完整的spring-common.xml的配置如下:

<?xml version="1.0" encoding="UTF-8"?>  
<!--suppress ALL -->  
<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:tx="http://www.springframework.org/schema/tx"  
    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:mvc="http://www.springframework.org/schema/mvc"  
    xmlns:task="http://www.springframework.org/schema/task" xmlns:cache="http://www.springframework.org/schema/cache"  
    xmlns:util="http://www.springframework.org/schema/util"  
    xmlns:websocket="http://www.springframework.org/schema/websocket"  
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd  
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.1.xsd  
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd  
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd  
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd  
        http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.1.xsd  
        http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache-4.1.xsd  
        http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.1.xsd">  
    <context:component-scan base-package="com.mvc.rest" />  
    <!-- properties文件解析器 -->  
    <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">  
        <property name="locations">  
            <value>classpath:jdbc.properties</value>  
        </property>  
    </bean>  
    <!-- 配置数据源 -->  
    <bean id="dataSource" destroy-method="close"  
        class="org.apache.commons.dbcp.BasicDataSource">  
        <property name="driverClassName" value="${jdbc.driverClassName}" />  
        <property name="url" value="${jdbc.url}" />  
        <property name="username" value="${jdbc.username}" />  
        <property name="password" value="${jdbc.password}" />  
    </bean>  
    <bean id="sessionFactory"  
        class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">  
        <property name="dataSource" ref="dataSource" />  
        <property name="hibernateProperties">  
            <props>  
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>  
                <prop key="hibernate.hbm2ddl.auto">update</prop>  
                <prop key="hibernate.show_sql">true</prop>  
                <prop key="hibernate.format_sql">true</prop>  
            </props>  
        </property>  
        <!-- 注解方式配置 -->  
        <property name="packagesToScan">  
            <list>  
                <value>com.mvc.rest.entity</value>  
            </list>  
        </property>  
    </bean>  
    <bean id="txManager"  
        class="org.springframework.orm.hibernate4.HibernateTransactionManager">  
        <property name="sessionFactory" ref="sessionFactory" />  
    </bean>  
    <tx:advice id="txAdvice" transaction-manager="txManager">  
        <tx:attributes>  
            <tx:method name="save*" propagation="REQUIRED" />  
            <tx:method name="add*" propagation="REQUIRED" />  
            <tx:method name="edit*" propagation="REQUIRED" />  
            <tx:method name="update*" propagation="REQUIRED" />  
            <tx:method name="delete*" propagation="REQUIRED" />  
            <tx:method name="register*" propagation="REQUIRED" />  
            <tx:method name="all" propagation="REQUIRED" />  
            <tx:method name="changePassword*" propagation="REQUIRED" />  
            <tx:method name="restPassword*" propagation="REQUIRED" />  
            <tx:method name="authorize*" propagation="REQUIRED" />  
            <tx:method name="send*" propagation="REQUIRED" />  
            <tx:method name="init*" propagation="REQUIRED" />  
            <!-- <tx:method name="*" read-only="true"/> -->  
        </tx:attributes>  
    </tx:advice>  
    <aop:config>  
        <aop:pointcut id="serviceOperation"  
            expression="execution(* com.mvc.rest.service.impl.*.*(..))" />  
        <aop:advisor advice-ref="txAdvice" pointcut-ref="serviceOperation" />  
    </aop:config>  
</beans>

到此,基于全注解的SpringMVC+Spring4.2+hibernate4.3框架搭建大功告成。

6.1日期的处理

当新增用户,输入日期时候,会400,报错,在controller中加入如下代码,就会不抱错.

@InitBinder
    //此方法用于日期的转换,如果未加,当页面日期格式转换错误,将报400错误,实际是因为此方法
    public void initBinder(WebDataBinder binder) {
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        dateFormat.setLenient(true);
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
    }
<?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"
    xsi:schemaLocation="
    http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-3.0.xsd
    http://www.springframework.org/schema/mvc 
    http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
    <!--默认的注解映射的支持 -->
    <mvc:annotation-driven/>
    <!--启用自动扫描 -->
    <context:component-scan base-package="controller"/>
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
</beans>

第六步:运行

DB安装:

图片 4

当然,你不安装也是可以的,本项目可以通过hibernate反向创建db和表,但数据没法创建,而且密码我们采用MD5加密,所以,为了省事,建议执行以下脚本,这个脚本是已经包含了创建DB的了。

 

DB安装后,需要配置下项目的jdbc连接:

图片 5

配置如下:

图片 6

请根据自己的实际情况修改。

 

然后是运行起来:

图片 7

6.2springMVC自定义标签(输入框回显)

在edit.jsp页面加入springmvc自定义标签

<%@ taglib uri="http://www.springframework.org/tags/form" prefix="sf"%>

form标签用自定义标签代替,modelAttribute表示controller中的对象
<sf:form action="${pageContext.request.contextPath}/person/update.do" method="post" modelAttribute="p">

<td>用户名 :</td>
<sf:input path="name"/></td>

</sf:form>

注意说明的是,启动自动扫描,spring会在指定的包下(例如我这里是controller包),自动扫描标注@Controller的类

代码下载:

6.3文件上传
  • 1.在jsp页面form标签添加属性enctype,在table中添加input type=file.

    method="post" modelAttribute="p"
    enctype="multipart/form-data">
    
    <tr>
        <td>图片上传 :</td>
        <td><input type="file" name="fileUpload"/>
    </tr>
    
  • 2.在springmvc的xml中配置文件上传视图解析器

    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="maxUploadSize" value="10485760"></property>
    </bean>
    
  • 3.修改controller层,添加MultipartFile参数,并导包commons-fileupload.jar和commons-io.jar

    /**
     * 修改并展示
     * @throws IOException 
     */
    @RequestMapping("/person/update.do")
    public String update(Person p,@RequestParam(required=true)MultipartFile fileUpload) throws IOException{
        /**
         * 上传文件写入磁盘
         */
        //从字节到文件
        FileUtils.writeByteArrayToFile(new File("D:\\1.jpg"), fileUpload.getBytes());
    
        personService.updatePerson(p);
        return "redirect:/person/querryAll.do";
    }
    

prefix指的是返回的值给自动加一个前缀,同理suffix指的就是后缀

注:本文著作权归作者,由demo大师发表,拒绝转载,转载需要作者授权

 

概述 从0到1教你搭建spring+springMVC+hibernate整合框架,基于注解。
本教程框架为基于全注解…

6.4服务器端检验(不重要)

图片 8

 

 图片 9

看到这里也是够辛苦了,上面是给出的完整目录,下面开始写逻辑代码,先从loginController开始

@Controller
public class LoginController {
    @RequestMapping(value="/",method=RequestMethod.GET)
    public String sayHello(){
        //model.addAttribute("msg", "Hello,World!");
        return "login";
    }

解释上面代码,@Controller,标注这个类是Controller类,spring会自动进行扫描,@Request
Mapping中的value指的是url中的地址后缀,设置成/的目的当然是为了方便啊,

比如启动工程时,url只需要输入什么localhost:8080/项目名,它就会自动跳转到login页面;method指的是来的url是post请求还是get请求

return的是login字符串,大家还记得上面说的prefix了吧,它就会把你的url自动拼接上,完整路径就是下面这个

/WEB-INF/jsp/login.jsp

 接下来看login.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>login</title>
</head>
<body>
    <form action="login" method="post">
        用户名:<input type="text" name="username"/><br/>
        密&nbsp;&nbsp;码:<input type="password" name="password"/>
        <input type="submit" value="登陆"/>
        <a href="regist">注册</a>
    </form>
</body>
</html>

这里的action返回的是login,Controller会自动捕获到这个请求,于是在login
Controller中要有一个方法来捕获这个请求

@RequestMapping(value="login",method=RequestMethod.POST)
    public String login(Model model, // 向前台页面传的值放入model中
            HttpServletRequest request){ // 从前台页面取得的值
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String user_name = LoginCheck.check(username, password);
        if(user_name != null && user_name != ""){
            model.addAttribute("msg", user_name);
            return "success";
        }else{
            return "login2";
        }
    }

登陆嘛,当然要有验证,于是就有了LoginCheck,不多说,上代码

package logic;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import dao.Dao;

public class LoginCheck {

    public static String check(String username,String password){
        try {
            Connection conn = Dao.getConnection();
            PreparedStatement p = conn.prepareStatement("select * from user_t where user_name=? and password=?");
            p.setString(1, username);
            p.setString(2, password);
            ResultSet rs = p.executeQuery();
            if(rs.next()){
                String user_name = rs.getString("user_name");
                Dao.close(rs, p, conn);
                return user_name;
            }
            Dao.close(rs, p, conn);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }
}

向数据库查询就要有DAO啦,Dao网上都有,我的就是在网上随便找一个改改就用了~

package dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class Dao {
    // 获取数据库连接
    public static Connection getConnection(){

        Connection conn = null;
        String url = "jdbc:mysql://127.0.0.1:3306/test?characterEncoding=utf8&useSSL=false&serverTimezone=Hongkong";
        try
        {
            Class.forName("com.mysql.cj.jdbc.Driver");
            conn = DriverManager.getConnection(url,"root","数据库密码");//大家分享代码的时候也不要暴露自己的数据库密码,这样是非常不安全的
        }
        catch(ClassNotFoundException e)
        {
            e.printStackTrace();
            System.out.println("数据库驱动加载出错");
        }
        catch(SQLException e)
        {
            e.printStackTrace();
            System.out.println("数据库出错");
        }
        return conn;
    }
     //关闭相关通道
    public static void close(ResultSet rs,PreparedStatement p,Connection conn)
    {
        try
        {
            if(!rs.isClosed()){
                rs.close();
            }
            if(!p.isClosed()){
                p.close();
            }
            if(!conn.isClosed()){
                conn.close();
            }
        }
        catch(SQLException e)
        {
            e.printStackTrace();
            System.out.println("数据关闭出错");
        }
    }
    //关闭相关通道
    public static void close(PreparedStatement p,Connection conn)
    {
        try
        {
            if(!p.isClosed()){
                p.close();
            }
            if(!conn.isClosed()){
                conn.close();
            }
        }
        catch(SQLException e)
        {
            e.printStackTrace();
            System.out.println("数据关闭出错");
        }
    }
}

好了,如果查询的结果匹配上数据库中查询到的值了,那么就可以跳转到success页面了,success.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>
    登陆成功!
    欢迎~${msg};
</body>
</html>

login大功告成,接下来的注册页面和这个道理相似,我不多废话了,把代码附上供大家参考

首先是regist.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="registSuccess" method="Post">
        用户名:<input type="text" name="username"/>
        密&nbsp;&nbsp;码<input type="text" name="password"/>
        年&nbsp;&nbsp;龄<input type="number" name="age"/>
        <input type="submit" value="提交"/>
    </form>
</body>
</html>

接下来是RegistController

package controller;

import javax.servlet.http.HttpServletRequest;

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 logic.RegistCheck;

@Controller
public class RegistController {
    @RequestMapping(value="regist",method=RequestMethod.GET)
    public String regist(){
        return "regist";
    }

    @RequestMapping(value="registSuccess",method=RequestMethod.POST)
    public String registSuccess(HttpServletRequest request,Model model){
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String age = request.getParameter("age");

        if(RegistCheck.registCheck(username, password,age)){
            model.addAttribute("username", username);
            return "login";
        }else{
            return "regist2";
        }
    }
}

接下来是RegistCheck

 

package logic;

import java.sql.Connection;
import java.sql.PreparedStatement;

import dao.Dao;

public class RegistCheck {

    public static boolean registCheck(String username,String password,String age){
        String user_name = LoginCheck.check(username, password);
        if(user_name == null || user_name == ""){
            try {
                Connection conn = Dao.getConnection();
                PreparedStatement p = conn.prepareStatement("insert user_t(user_name,password,age) VALUES (?,?,?);");
                p.setString(1, username);
                p.setString(2, password);
                p.setString(3, age);
                p.executeUpdate();
                System.out.println("注册成功");
                Dao.close(p, conn);
                return true;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return false;
    }
}

还有一个registSuccess.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>
    注册成功!
</body>
</html>

好了,现在为止login和注册页面都写好了,新人刚到公司的时候非常容易碰到这样的小练习,哈哈哈说多了,喜欢就点赞哈

欢迎转载,转载请注明出处~

Java从学习到放弃,MySQL从删库到跑路,哈哈哈

 

相关文章

Leave a Reply

电子邮件地址不会被公开。 必填项已用*标注