码迷,mamicode.com
首页 > 其他好文 > 详细

配置等模版

时间:2021-02-24 12:59:05      阅读:0      评论:0      收藏:0      [点我收藏+]

标签:nsa   连接池   没有   定义   自定义   函数   ping   prepare   prope   

  • 页面引入BootStrap和JQuery

    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css"
              integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
    <script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
    
  • SSM配置文件:pom.xml

    	<dependencies>
             <dependency>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
                <version>4.11</version>
            </dependency>
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>5.1.47</version>
            </dependency>
            <!-- 数据库连接池:c3p0 -->
    		<dependency>
       			<groupId>com.mchange</groupId>
       			<artifactId>c3p0</artifactId>
        		<version>0.9.5.2</version>
    		</dependency>
            <!-- Servlet Jsp Jstl-->
    		<dependency>
        		<groupId>javax.servlet</groupId>
        		<artifactId>javax.servlet-api</artifactId>
        		<version>3.1.0</version>
        		<scope>provided</scope>
    		</dependency>
            <dependency>
                <groupId>javax.servlet.jsp</groupId>
                <artifactId>jsp-api</artifactId>
                <version>2.2</version>
            </dependency>
            <dependency>
                <groupId>javax.servlet</groupId>
                <artifactId>jstl</artifactId>
                <version>1.2</version>
            </dependency>
            
            <!-- mybatis -->
            <dependency>
                <groupId>org.mybatis</groupId>
                <artifactId>mybatis</artifactId>
                <version>3.5.2</version>
            </dependency>
            <dependency>
                <groupId>org.mybatis</groupId>
                <artifactId>mybatis-spring</artifactId>
                <version>2.0.6</version>
            </dependency>
            
            <!-- spring -->
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-webmvc</artifactId>
                <version>5.2.12.RELEASE</version>
            </dependency>
            <!-- Spring操作数据库,需要spring-jdbc -->
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-jdbc</artifactId>
                <version>5.2.12.RELEASE</version>
            </dependency>
            <!-- AspectJ Weaver -->
    		<dependency>
        		<groupId>org.aspectj</groupId>
        		<artifactId>aspectjweaver</artifactId>
        		<version>1.9.6</version>
    		</dependency>
            
            <!--lombok -->
            <dependency>
                <groupId>org.projectlombok</groupId>
                <artifactId>lombok</artifactId>
                <version>1.18.12</version>
                <scope>provided</scope>
            </dependency>
        </dependencies>
    
    
    	<!--在build中配置resources,防止资源导出失败的问题-->
        <build>
            <resources>
                <resource>
                    <directory>src/main/resources</directory>
                    <includes>
                        <include>**/*.properties</include>
                        <include>**/*.xml</include>
                    </includes>
                    <filtering>false</filtering>
                </resource>
                <resource>
                    <directory>src/main/java</directory>
                    <includes>
                        <include>**/*.properties</include>
                        <include>**/*.xml</include>
                    </includes>
                    <filtering>false</filtering>
                </resource>
            </resources>
        </build>
    
  • SSM的配置文件:

    web.xml:注册DispatcherServlet

    <?xml version="1.0" encoding="UTF-8"?>
    <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">
    
        <!--1. 注册DispatcherServlet-->
        <servlet>
            <servlet-name>springmvc</servlet-name>
            <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
            <!--关联一个springmvc的配置文件:【servlet-name】-servlet.xml -->
            <init-param>
                <param-name>contextConfigLocation</param-name>
                <param-value>classpath:springmvc-servlet.xml</param-value>
            </init-param>
            <!--启动级别-1-->
            <load-on-startup>1</load-on-startup>
        </servlet>
    
    	<!-- / 和/* 的区别-->
        <!-- / 匹配所有的请求:(不包括.jsp)-->
        <!-- /* 匹配所有的请求:(包括.jsp)-->
        <servlet-mapping>
            <servlet-name>springmvc</servlet-name>
            <url-pattern>/</url-pattern>
        </servlet-mapping>
        
        
        <!--SpringMVC提供的乱码过滤器-->
        <filter>
            <filter-name>encoding</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>
        </filter>
        <filter-mapping>
            <filter-name>encoding</filter-name>
            <url-pattern>/*</url-pattern>
        </filter-mapping>
    </web-app>
    

    SpringMVC的配置文件springmvc-serlvet.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: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
           https://www.springframework.org/schema/context/spring-context.xsd
           http://www.springframework.org/schema/mvc
           https://www.springframework.org/schema/mvc/spring-mvc.xsd">
    
        <!--自动扫描包,让指定包下的注解生效,由IOC容器统一管理-->
        <context:component-scan base-package="com.musecho.controller"/>
    
        <!--视图解析器ViewResolver:解析DispatcherServlet传递来的ModelAndView-->
        <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="InternalResourceViewResolver">
            <!--前缀-->
            <property name="prefix" value="/WEB-INF/jsp/" />
            <!--后缀-->
            <property name="suffix" value=".jsp" />
        </bean>
    
    
        <!--JSON乱码问题配置-->
        <mvc:annotation-driven>
            <mvc:message-converters register-defaults="true">
                <bean class="org.springframework.http.converter.StringHttpMessageConverter">
                    <constructor-arg value="UTF-8"/>
                </bean>
                <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
                    <property name="objectMapper">
                        <bean class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean">
                            <property name="failOnEmptyBeans" value="false"/>
                        </bean>
                    </property>
                </bean>
            </mvc:message-converters>
        </mvc:annotation-driven>
    
    
        <!--Handler-->
        <!-- <bean id="/hello" class="com.musecho.controller.HelloController" /> -->
    
    </beans>
    

    applicationContext.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:aop="http://www.springframework.org/schema/aop"
           xsi:schemaLocation="http://www.springframework.org/schema/beans
            https://www.springframework.org/schema/beans/spring-beans.xsd
            http://www.springframework.org/schema/aop
            https://www.springframework.org/schema/aop/spring-aop.xsd">
    
        <import resource="spring-dao.xml" />
    
        <!--注册bean-->
        <bean id="userMapper" class="mapper.UserMapperImpl">
            <property name="sqlSession" ref="sqlSession" />
        </bean>
    
    </beans>
    

    spring-dao.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:aop="http://www.springframework.org/schema/aop"
           xsi:schemaLocation="http://www.springframework.org/schema/beans
            https://www.springframework.org/schema/beans/spring-beans.xsd
            http://www.springframework.org/schema/aop
            https://www.springframework.org/schema/aop/spring-aop.xsd">
    
        <!--DataSource:使用Spring的数据源替换Mybatis的配置  c3p0  dbcp  druid
        这里使用Spring提供的JDBC: org.springframework.jdbc.datasource -->
        <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
            <property name="driverClassName" value="com.mysql.jdbc.Driver" />
            <property name="url" value="jdbc:mysql://localhost:3306/mybatiss?useSSL=true&amp;useUnicode=true&amp;characterEncoding=UTF-8" />
            <property name="username" value="root" />
            <property name="password" value="root" />
        </bean>
    
        <!--SqlSessionFactory-->
        <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
            <property name="dataSource" ref="dataSource" />
    
            <!--绑定Mybatis核心配置文件-->
            <property name="configLocation" value="classpath:mybatis-config.xml"/>
            <property name="mapperLocations" value="classpath:mapper/*.xml" />
        </bean>
    
        <!--SqlSessionTemplate:相当于我们之前使用的sqlSession-->
        <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
            <!--只能使用构造器注入sqlSessionFactory,因为没有set方法-->
            <constructor-arg index="0" ref="sqlSessionFactory" />
        </bean>
    
        
        	<!--配置声明式事务-->
        <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
            <constructor-arg ref="dataSource" />
        </bean>
    
        <!--结合AOP实现事务的织入-->
        <!--配置事务通知-->
        <tx:advice id="txAdvice" transaction-manager="transactionManager">
            <!--给哪些方法配置事务-->
            <!--配置事务的传播特性:new propagation -->
            <tx:attributes>
                <tx:method name="add*" propagation="REQUIRED"/>
                <tx:method name="delete*" propagation="REQUIRED"/>
                <tx:method name="update*" propagation="REQUIRED"/>
                <tx:method name="select*" read-only="true" />
    <!--            <tx:method name="*" propagation="REQUIRED" />-->
            </tx:attributes>
        </tx:advice>
    
        <!--配置事务切入-->
        <aop:config>
            <aop:pointcut id="txPointCut" expression="execution(* mapper.*.*(..))" />
            <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointCut" />
        </aop:config>
    
    </beans>
    

    mybatis-config.xml

    <?xml version="1.0" encoding="UTF-8" ?>
    <!DOCTYPE configuration
            PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
            "http://mybatis.org/dtd/mybatis-3-config.dtd">
    <configuration>
        <typeAliases>
            <package name="pojo"/>
        </typeAliases>
    
    </configuration>
    
  • 只用mybatis 的核心配置文件:mybatis-config.xml

    <?xml version="1.0" encoding="UTF-8" ?>
    <!DOCTYPE configuration
            PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
            "http://mybatis.org/dtd/mybatis-3-config.dtd">
    <configuration>
        <environments default="development">
            <environment id="development">
                <transactionManager type="JDBC"/>
                <dataSource type="POOLED">
                    <property name="driver" value="com.mysql.jdbc.Driver"/>
                    <property name="url" value="jdbc:mysql://localhost:3306/MyBatiss?useSSL=true&amp;useUnicode=true&amp;characterEncoding=UTF-8"/>
                    <property name="username" value="root"/>
                    <property name="password" value="root"/>
                </dataSource>
            </environment>
        </environments>
        
         <!--每一个Mapper.xml都需要在Mybatis核心配置文件中注册!-->
        <mappers>
            <!--<mapper resource="dao/UserMapper.xml"/>-->
        </mappers>
    </configuration>
    
  • pojo类中的lombok注解

    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    
  • 日志:log4j.properties 配置文件

    #将等级为DEBUG的日志信息输出到console和file这两个目的地,console和file的定义在下面的代码
    log4j.rootLogger=DEBUG,console,file
    
    #控制台输出的相关设置
    log4j.appender.console = org.apache.log4j.ConsoleAppender
    log4j.appender.console.Target = System.out
    log4j.appender.console.Threshold=DEBUG
    log4j.appender.console.layout = org.apache.log4j.PatternLayout
    log4j.appender.console.layout.ConversionPattern=[%c]-%m%n
    
    #文件输出的相关设置
    log4j.appender.file = org.apache.log4j.RollingFileAppender
    log4j.appender.file.File=./log/musecho.log
    log4j.appender.file.MaxFileSize=10mb
    log4j.appender.file.Threshold=DEBUG
    log4j.appender.file.layout=org.apache.log4j.PatternLayout
    log4j.appender.file.layout.ConversionPattern=[%p][%d{yy-MM-dd}][%c]%m%n
    
    #日志输出级别
    log4j.logger.org.mybatis=DEBUG
    log4j.logger.java.sql=DEBUG
    log4j.logger.java.sql.Statement=DEBUG
    log4j.logger.java.sql.ResultSet=DEBUG
    log4j.logger.java.sq1.PreparedStatement=DEBUG
    
  • 乱码问题:一般SpringMVC自带的乱码过滤器就够了,不行就用终极自定义过滤器

    GenericEncodingFilter.java

    public class GenericEncodingFilter implements Filter {
    
        public void init(FilterConfig filterConfig) throws ServletException {
    
        }
    
        public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
            //处理response的字符编码
            HttpServletResponse myResponse = (HttpServletResponse) servletResponse;
            myResponse.setContentType("text/html;charset=UTF-8");
    
            //转型为与协议相关对象
            HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
            //对request包装增强
            HttpServletRequest myRequest = new MyRequest(httpServletRequest);
    
            filterChain.doFilter(myRequest, servletResponse);
    
        }
    
        public void destroy() {
    
        }
    }
    
    //自定义request对象,HttpServletRequest的包装类
    class MyRequest extends HttpServletRequestWrapper {
    
        private HttpServletRequest request;
    
        //是否编码的标记
        private boolean hasEncode;
    
        //定义一个可以传入HttpServletRequest对象的构造函数,以便对其进行装饰
        public MyRequest(HttpServletRequest request) {
            super(request);
            this.request = request;
        }
    
        //对需要增强方法 进行覆盖
        public Map getParameterMap() {
            //先获得请求方法
            String method = request.getMethod();
            if (method.equalsIgnoreCase("post")) {
                //post请求
                try {
                    //处理post乱码
                    request.setCharacterEncoding("utf-8");
                    return request.getParameterMap();
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            } else if (method.equalsIgnoreCase("get")) {
                //get请求
                Map<String, String[]> parameterMap = request.getParameterMap();
                if (!hasEncode) {
                    for (String parameterName : parameterMap.keySet()) {
                        String[] values = parameterMap.get(parameterName);
                        if (values != null) {
                            for (int i = 0; i < values.length; i++) {
                                try {
                                    //处理get乱码
                                    values[i] = new String(values[i]
                                            .getBytes("ISO-8859-1"), "utf-8");
                                } catch (UnsupportedEncodingException e) {
                                    e.printStackTrace();
                                }
                            }
                        }
                    }
                    hasEncode = true;
    
                }
                return parameterMap;
            }
    
            return super.getParameterMap();
        }
    
        //取一个值
        public String getParameter(String name) {
            Map<String, String[]> parameterMap = getParameterMap();
            String[] values = parameterMap.get(name);
            if (values == null) {
                return null;
            }
    
            return values[0];//取回参数的第一个值
        }
    
        //取所有值
        public String[] getParameterValues(String name) {
            Map<String, String[]> parameterMap = getParameterMap();
            String[] values = parameterMap.get(name);
            return values;
        }
    
    }
    

    web.xml增加配置

    	<!--配置SpringMVC的乱码过滤-->
        <filter>
            <filter-name>encoding</filter-name>
            <filter-class>com.musecho.filter.GenericEncodingFilter</filter-class>
        </filter>
        <filter-mapping>
            <filter-name>encoding</filter-name>
            <url-pattern>/*</url-pattern>
        </filter-mapping>
    
  • Spring的注解

    • @Autowired:自动装配

    • @Nullable(字段)

    • @Qualifier(value="xx"):指定一个唯一的bean对象注入

    • @Component:代替配置文件中bean的注册

      • @Repository:dao层
  • @Service

    • @Controller

    • @RestController:类上方加这个注解,该类里所有的方法都不会走视图解析器,直接返回字符串。

    • @Value:代替配置文件中bean的简单属性值的注入

    • @Scope("xx"):作用域,默认singleton

      JavaConfig中使用

    • @Configuration:代表这是一个配置类,代替applicationConfig.xml

    • @ComponentScan("pojo"):代替<context:component-scan base-package="pojo"/>

    • @Bean:注册一个bean,就相当于配置文件中的一个bean标签

    • @Import:若出现多个配置类,可以使用@Import导入

  • javax自带注解:

    • @Resource:自动装配
  • SpringMVC的注解:

    • @RequestMapping:用于映射url到控制器类或一个特定的处理方法。@RequestMapping默认是GET方法,在url中传参。

    • @RequestParam:前端提交的域名称和处理方法的参数名不一致。一致一般也会加。

    • @ResponseBody:方法上加上这个注解,就不会走视图解析器,直接返回一个字符串。(json用)

    • @PathVariable:方法中传参要加这个注解

    • @RequestMapping的参数method=RequestMethod.xxx

    • @GetMapping //默认请求方式
      @PostMapping //相当于@RequestMapping(。。。,method = RequestMethod.POST)
      @PutMapping
      @DeleteMapping
      @PatchMapping

配置等模版

标签:nsa   连接池   没有   定义   自定义   函数   ping   prepare   prope   

原文地址:https://www.cnblogs.com/musecho/p/14436403.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!