spring MVC +Spring + Hibernate + PostgreSQL框架的集成和多租户( 二)

  • 11. 引入Spring MVC
    编写配置文件:spring-mvc.xm
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"  
    xmlns:mvc="http://www.springframework.org/schema/mvc" 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"  
    xsi:schemaLocation="http://www.springframework.org/schema/beans   
        http://www.springframework.org/schema/beans/spring-beans-4.2.xsd   
        http://www.springframework.org/schema/context   
        http://www.springframework.org/schema/context/spring-context-4.2.xsd   
        http://www.springframework.org/schema/mvc   
        http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd">                          
    <mvc:annotation-driven />
    <!--资源映射-->
    <!--
    <mvc:resources mapping="/_includes/**" location="/_includes/" /> 
    <mvc:resources mapping="/scripts/**" location="/scripts/" />
    <mvc:resources mapping="/fonts/**" location="/fonts/" />
    <mvc:resources mapping="/images/**" location="/images/" />
    <mvc:resources mapping="/pages/**" location="/pages/" />
    <mvc:resources mapping="/styles/**" location="/styles/" />
-->        

    <!-- 自动扫描该包,使SpringMVC认为包下用了@controller注解的类是控制器 -->
    <context:component-scan base-package="cn.ac.bcc.maque.controller" />
    <!--避免IE执行AJAX时,返回JSON出现下载文件 -->
    <bean id="mappingJacksonHttpMessageConverter"
        class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
        <property name="supportedMediaTypes">
            <list>
                <value>text/html;charset=UTF-8</value>
            </list>
        </property>
    </bean>
    <!-- 启动SpringMVC的注解功能,完成请求和注解POJO的映射 -->
    <bean
        class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
        <property name="messageConverters">
            <list>
                <ref bean="mappingJacksonHttpMessageConverter" />   <!-- JSON转换器 -->
            </list>
        </property>
    </bean>
    <!-- 定义跳转的文件的前后缀 ,视图模式配置 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!-- 这里的配置我的理解是自动给后面action的方法return的字符串加上前缀和后缀,变成一个 可用的url地址 -->
        <property name="prefix" value="/views/" />
        <property name="suffix" value=".jsp" />
    </bean>

    <!-- 配置文件上传,如果没有使用文件上传可以不用配置,当然如果不配,那么配置文件中也不必引入上传组件包 -->
    <bean id="multipartResolver"  
        class="org.springframework.web.multipart.commons.CommonsMultipartResolver">  
        <!-- 默认编码 -->
        <property name="defaultEncoding" value="utf-8" />  
        <!-- 文件大小最大值 -->
        <property name="maxUploadSize" value="2000000" />  
        <!-- 内存中的最大值 -->
        <property name="maxInMemorySize" value="2000000" />

    </bean> 

    <!--拦截器-->
    <!-- 
    <mvc:interceptors>
        <mvc:interceptor>
            <mvc:mapping path="/**"/>-->

             <!-- 需排除拦截的地址   -->
            <!--
            <mvc:exclude-mapping path="/scripts/**"/>
            <mvc:exclude-mapping path="/fonts/**"/>
            <mvc:exclude-mapping path="/images/**"/>
            <mvc:exclude-mapping path="/pages/**"/>
            <mvc:exclude-mapping path="/styles/**"/>

            <mvc:exclude-mapping path="/views/index.jsp"/>
            <mvc:exclude-mapping path="/userinfo/signin"/>            
            <mvc:exclude-mapping path="/userinfo/signup"/>
            <mvc:exclude-mapping path="/userinfo/signup-freetrial"/>
            <mvc:exclude-mapping path="/userinfo/login"/>
            <mvc:exclude-mapping path="/userinfo/addTenant"/>
            <mvc:exclude-mapping path="/userinfo/checkPhone"/>

            <bean id="commonIntercepter" class="cn.ac.bcc.maque.controller.CommonInterceptor"/>

        </mvc:interceptor>
    </mvc:interceptors> 
    -->

</beans>
  • 12. 配置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"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
    version="3.0">
  <display-name>Archetype Created Web Application</display-name>
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:spring*.xml</param-value>
    </context-param>
    <!-- 编码过滤器 -->
    <filter>
        <filter-name>encodingFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <async-supported>true</async-supported>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>encodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    <!-- openSessionInView配置 作用是延迟session关闭到view层 -->  
    <filter>  
        <filter-name>openSessionInViewFilter</filter-name>  
        <filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class>  
        <init-param>  
            <param-name>singleSession</param-name>  
            <param-value>true</param-value>  
        </init-param>  
    </filter>
    <filter-mapping>  
        <filter-name>openSessionInViewFilter</filter-name>  
        <url-pattern>/</url-pattern>  
    </filter-mapping>    
    <!-- Spring监听器 -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <!-- 防止Spring内存溢出监听器 -->
    <listener>
        <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
    </listener>

    <!-- Spring MVC servlet -->
    <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:spring-mvc.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
        <async-supported>true</async-supported>
    </servlet>
    <servlet-mapping>
        <servlet-name>SpringMVC</servlet-name>
        <!-- 此处可以可以配置成*.do,对应struts的后缀习惯 -->
        <url-pattern>/</url-pattern>
    </servlet-mapping>
    <welcome-file-list>
        <welcome-file>/views/index.jsp</welcome-file>
    </welcome-file-list>
</web-app>
  • 13. 创建控制层controller
    UserController.java
package cn.ac.bcc.maque.controller;

import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.ac.bcc.maque.model.Login;
import cn.ac.bcc.maque.model.User;
import cn.ac.bcc.maque.service.UserService;

@Controller
@RequestMapping("/user")
public class UserController {
    private static final Logger LOGGER = Logger.getLogger(UserController.class);

    @Autowired
    private UserService userService;

    @RequestMapping("/showInfo/{userId}")
    public String showUserInfo(ModelMap modelMap, @PathVariable String userId){
        LOGGER.info("查询用户:"  + userId);
        Login.setTenantId("myschema");
        User user = userService.get(userId);
        modelMap.addAttribute("userInfo", user);
        return "/user/showInfo";
    }

    @RequestMapping("/showInfos")
    @ResponseBody
    public List<User> showUserInfos(){
        LOGGER.info("查询全部用户");
        Login.setTenantId("myschema");
        List<User> users = userService.findAll();
        return users;
    }
}
  • 14. 创建视图层
    在webapp/views/user/下创建showInfo.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>  
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>  
<%@taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>  

<%  
    String path = request.getContextPath();  
    String basePath = request.getScheme() + "://"  
            + request.getServerName() + ":" + request.getServerPort()  
            + path + "/";  
%>  
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  
<html>  
<head>  
<base href="<%=basePath%>" />  
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">  
<script type="text/javascript" src="scripts/jquery-1.9.1.min.js"></script>  
<title>userInfo</title>  
</head>  
<body>  
    用户信息 昵称: ${userInfo.name} 用户id:${userInfo.id}  注册时间:  
    <fmt:formatDate value="${userInfo.signupDate }" pattern="yyyy-MM-dd HH:mm:ss" />  



    <br /> ajax显示全部用户信息:  
    <div id="show_all_user"></div>  
</body>  
<script type="text/javascript">  
    $.ajax({  
        type : "get",  
        url : "user/showInfos.htmls",  
        dataType : "json",  
        success : function(data) {  
            $(data).each(  
                    function(i, user) {  
                        var p = "<p>昵称:" + user.name +  "    注册时间:"  
                                + user.signupDate + "    id:" + user.id +  
                        "</p>";  
                        $("#show_all_user").append(p);  
                    });  
        },  
        async : true  
    });  
</script>  
</html> 

至此,框架配置完成。如有问题可以给我留言。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值