关于spring框架当取消bean标签默认的单例模式时多创建出来的对象是怎么来的?

今天本来在测试spel spring表达式赋值的,但是突然发现了一些问题,想请教一下大家,

这是我在测试时观察表达式传值时方便查看用this显示对象地址,区分到底是那个对象进入了方法,类名就是Users,就是一个普通的get/set方法

public String getName() {
        System.out.println("getname"+"="+this);
        return name;
    }

    public void setName(String name) {
        System.out.println("setname"+"="+this);
        this.name = name;
    }

但是当我使用spring框架在spring.xml文件中做spel spring表达式赋值练习时为了确认是否传值,把默认的单例模式取消掉了,为如下代码:

<bean id="u1" class="com.qf.bean.Users" scope="prototype">
        <property name="name" value="张三"></property>
        <property name="age" value="15"></property>
    </bean>
    <bean id="u2" class="com.qf.bean.Users">
        <property name="name" value="#{u1.name}"></property>
        <property name="age" value="#{u1.age}"></property>
    </bean>
    <bean id="u3" class="com.qf.bean.Users">
        <property name="name" value="#{u1.name}"></property>
        <property name="age" value="#{u1.age}"></property>
    </bean>

u3是为了测试u1改为了多例后u2和u3的地址是否相同用的,可以不看,然后我在测试类中准备打印对象的属性观察是否成功赋值,写了如下代码,怎么看都是没有问题的

ApplicationContext app = new ClassPathXmlApplicationContext("spring.xml");
        Users u1 = (Users) app.getBean("u1");
        Users u2 = (Users) app.getBean("u2");
        Users u3 = (Users) app.getBean("u3");
        System.out.println("================");
        System.out.println("u1 = " + u1);
        System.out.println(u1.getName() + "\t" + u1.getAge());
        System.out.println("================");
        System.out.println("u2 = " + u2);
        System.out.println(u2.getName() + "\t" + u2.getAge());
        System.out.println("================");
        System.out.println("u3 = " + u3);
        System.out.println(u3.getName() + "\t" + u3.getAge());

但是打印结果让我想不通为什么:结果为下述情况:

/*疑问
  没有此对象      setname=com.qf.bean.Users@5c5a1b69
                 getname=com.qf.bean.Users@5c5a1b69
  没有此对象      setname=com.qf.bean.Users@cd2dae5
  u2      setname=com.qf.bean.Users@3a883ce7
  没有此对象      setname=com.qf.bean.Users@79be0360
                 getname=com.qf.bean.Users@79be0360
  没有此对象      setname=com.qf.bean.Users@22a67b4
  u3      setname=com.qf.bean.Users@57855c9a
  u1      setname=com.qf.bean.Users@d44fc21
        ================
        u1 = com.qf.bean.Users@d44fc21
        getname=com.qf.bean.Users@d44fc21
        张三  15
        ================
        u2 = com.qf.bean.Users@3a883ce7
        getname=com.qf.bean.Users@3a883ce7
        张三  15
        ================
        u3 = com.qf.bean.Users@57855c9a
        getname=com.qf.bean.Users@57855c9a
        张三  15
    */

我是想问的我只有三个对象,走的也应该是取一次值赋一次值,走一次get走一次set啊,为什么控制台输出的this地址会出来四个没用到也没出现的对象地址,
正常我三个对象,第一个应该直接走set赋值,第二个对象通过get获取第一个对象的值再set给自己,第三个也一样,那应该是走两次get方法,三次set方法,那么另外那么多次的getset方法是谁调用的?this的地址与我的三个对象地址完全不一样,那些地址是谁的?另外那四个我标注的看地址本应该不存在的地址对应的对象是怎么出来的?哪位大神能帮我说明一下,另外那四个对象是怎么来的?

1个回答

很简单的呀,因为你的 bean id 不一样,单例的 key 是 bean id 的。
你应该两次获取同一个 bean id 的再对比:

Users u2_instance01 = (Users) app.getBean("u2");
Users u2_instance02 = (Users) app.getBean("u2");
此时 u2_instance01 == u2_instance02 就是 true
wojiushiwo945you
毕小宝 回复zwdzdy: 为什么会产生四个对象,是因为你定义了四个 bean ,虽然类型都是同一个类,但是 beanId 是不同的,那么获取每个 bean id 对应的实例都会得到一个新的。这要跟踪 Spring 单例管理的源码的,有兴趣的话可以看我博客主页左侧的文章链接的《Java 开发中的设计模式》那篇。
5 个月之前 回复
wojiushiwo945you
毕小宝 回复zwdzdy: id 为 u2 的实体定义的就是单例模式,所以获取一个 beanName 为 u2 的实例是一个单例,取两次都是同一个对象。
5 个月之前 回复
zwdzdy
zwdzdy 刚才突然想明白你说的意思了,因为我已经设置了不是单例模式,那么即使我取得是一个id值,也是不同的对象,如果我想要正确测试传值应该是开启单例模式,创建两个类的对象来传值,是这个意思吧?因为如果单例的话我取哪个id都是一个对象,不能测试传值,如果开启多例,则每次取得是一个id,依然测试不了从id1传值到id2,是这个意思吧?那我这个情况的另外四个对象是怎么来的呢?能否解答一下?
5 个月之前 回复
zwdzdy
zwdzdy 我就是要bean的id不一样啊!我就是要三个对象,不然我怎么知道我的表达式成功从第一个对象将属性值赋给了其他对象了,我是想问的我只有三个对象,走的<property name="name" value="#{u1.name}"></property>也应该是取一次值付一次,走一次get走一次set啊,为什么控制台输出的this地址会出来四个没用到也没出现的对象地址,正常我三个对象,第一个应该直接走set赋值,第二个对象通过get获取第一个对象的值再set给自己,第三个也一样,那应该是走两次get方法,三次set方法,那么另外那么多次的getset方法是谁调用的?this的地址与我的三个对象地址完全不一样,那些地址是谁的?
5 个月之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
Spring框架中的Autowired注解,默认真的是按照ByType方式实现自动注入的吗?
在学习spring IOC的过程中,接触到@Autowired注解,资料上都是说默认是按照Bytype类型实现自动注入,但我的实际操作却发现是:先使用ByName,如果失败,再使用ByType。贴代码,求指点: Student类: ``` @Component public class Student { @Value("12") int age; @Value("lisa") String name; @Autowired School school; public Student(){} public Student(int age, String name, School school) { this.age = age; this.name = name; this.school = school; } @Override public String toString() { return "Student{" + "age=" + age + ", name='" + name + '\'' + ", school=" + school + '}'; } } ``` School类: ``` public class School { String name; String address; public School() { } public School(String name, String address) { this.name = name; this.address = address; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } ``` 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" 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"> <!--配置注解扫描器,base-package表示注解所在的包,目的是告诉spring框架去扫描指定包的注解--> <context:component-scan base-package="com.aipande.bao1"/> <bean id="school" class="com.aipande.bao1.School"> <property name="name" value="武汉大学21"/> </bean> <bean id="school03" class="com.aipande.bao1.School"> <property name="name" value="武汉大学21"/> </bean> <bean id="school02" class="com.aipande.bao1.School"> <property name="name" value="武汉大学"/> </bean> </beans> ``` 测试类: ``` public class AppTest01 { public static void main(String[] args) { /* * 创建spring容器对象 * spring框架在加载xml文件并创建spring容器对象的同时, * 就会将xml文件中配置的bean对象(作用域为singleton)一同创建,并将这些对象放置在spring容器中。 * */ String config = "applicationContext.xml"; ApplicationContext ctx = new ClassPathXmlApplicationContext(config); //使用getBean()方法获取bean对象 Student stu = (Student) ctx.getBean("student"); System.out.println(stu); } } ``` 结果输出: ``` Student{age=12, name='lisa', school=School{name='武汉大学21', address='null'}} ``` 问题: 如果按照Bytype方式获取bean对象,那上面就应该报错啊,因为sprig容器中存在多个同源bean对象,但是没有报错,说明是按照byName的方式注入。后来我将xml文件中id为school的bean对象删除,就出现了错误提示,说明此时是按照byType的方式注入。因此我有上面的疑问,求解
ssm框架demo遇到的问题
各位老哥们大家好,我是一名大二学生,自学Java一年半了,进步很慢,在ssm框架上遇到了问题,认识的人少,这个问题没人指点我,我很难再往后学习。 下面描述一下我遇到的问题吧:我比较抵触写jsp,所以从javaweb开始就尝试前后端分离,在学习ssm框架时,讲师用的都是jsp,我以为只要把springmvc的视图解析器中suffix配置成.html就行了,事情却没那么简单,项目一运行就报404,按理应该默认去找index.html,但是却直接报错,希望老哥们给我分析一下我哪里有错误。希望前辈能指导一下,谢谢了 ## 1:创建项目,我用的是IDEA,创建时选择的是Maven的webapp骨架。 ## 2:导入pom依赖 ``` <?xml version="1.0" encoding="UTF-8"?> <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> <packaging>war</packaging> <name>register</name> <groupId>xyz.peterparker</groupId> <artifactId>register</artifactId> <version>1.0-SNAPSHOT</version> <build> <plugins> <plugin> <groupId>org.mortbay.jetty</groupId> <artifactId>maven-jetty-plugin</artifactId> <version>6.1.7</version> <configuration> <connectors> <connector implementation="org.mortbay.jetty.nio.SelectChannelConnector"> <port>8888</port> <maxIdleTime>30000</maxIdleTime> </connector> </connectors> <webAppSourceDirectory>${project.build.directory}/${pom.artifactId}-${pom.version} </webAppSourceDirectory> <contextPath>/</contextPath> </configuration> </plugin> </plugins> </build> <properties> <spring.version>5.2.1.RELEASE</spring.version> <slf4j.version>1.6.6</slf4j.version> <log4j.version>1.2.12</log4j.version> <mybatis.version>3.4.5</mybatis.version> </properties> <dependencies> <!--dependency> <groupId>xyz.peterparker</groupId> <artifactId>[the artifact id of the block to be mounted]</artifactId> <version>1.0-SNAPSHOT</version> </dependency--> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.6.8</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</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-web</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> <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.0</version> <scope>provided</scope> </dependency> <dependency> <groupId>jstl</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <!-- log start --> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>${log4j.version}</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>${slf4j.version}</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>${slf4j.version}</version> </dependency> <!-- log end --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.3.0</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>${mybatis.version}</version> </dependency> <dependency> <groupId>c3p0</groupId> <artifactId>c3p0</artifactId> <version>0.9.1.2</version> <type>jar</type> <scope>compile</scope> </dependency> <dependency> <groupId>javax.annotation</groupId> <artifactId>jsr250-api</artifactId> <version>1.0</version> </dependency> <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.16</version> </dependency> </dependencies> </project> ``` ## 3:创建包结构 ![图片说明](https://img-ask.csdn.net/upload/202002/19/1582083667_469404.png) ## 4:编写web.xml ``` <?xml version="1.0" encoding="UTF-8"?> <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"> <!-- 更改applicationContext的默认位置 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </context-param> <!-- 配置监听器 --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <listener> <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class> </listener> <!-- 配置前端控制器 --> <servlet> <servlet-name>dispatcherServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:springmvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>dispatcherServlet</servlet-name> <url-pattern>/*</url-pattern> </servlet-mapping> <!-- 配置解决中文乱码的过滤器 --> <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> </filter> <filter-mapping> <filter-name>characterEncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file>index.htm</welcome-file> <welcome-file>index.jsp</welcome-file> <welcome-file>default.html</welcome-file> <welcome-file>default.htm</welcome-file> <welcome-file>default.jsp</welcome-file> </welcome-file-list> </web-app> ``` ## 5:编写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:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" 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/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"> <!-- 扫描service和dao --> <context:component-scan base-package="dao" /> <context:component-scan base-package="service" /> <!-- 引入dataSource.properties --> <context:property-placeholder location="classpath:dataSource.properties" /> <!-- 配置数据库连接池 --> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="driverClass" value="${driverClass}" /> <property name="jdbcUrl" value="${jdbcUrl}" /> <property name="user" value="${user}" /> <property name="password" value="${password}" /> </bean> <!-- 配置SqlSessionFactoryBean --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> </bean> <!-- 配置扫描dao --> <bean id="mapperScannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="dao" /> </bean> <!-- 配置声明式事务管理 --> <bean id="dataSourceTransactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean> <tx:annotation-driven transaction-manager="dataSourceTransactionManager" /> </beans> ``` ## 6:编写dataSource.properties ``` driverClass=com.mysql.cj.jdbc.Driver jdbcUrl=jdbc:mysql://localhost/user?useSSL=false&serverTimezone=Asia/Shanghai user=root password=rhw19990625 ``` ## 7:编写springmvc.xml ``` <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context" 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 http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"> <!-- 配置扫描controller --> <context:component-scan base-package="controller" /> <!-- 配置视图解析器 --> <bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="pages" /> <property name="suffix" value=".html" /> <property name="contentType" value="text/html" /> </bean> <mvc:annotation-driven /> <mvc:default-servlet-handler /> <aop:aspectj-autoproxy proxy-target-class="true"/> </beans> ``` ## 8:编写User实体类 ``` package domain; import java.io.Serializable; public class User implements Serializable { private String username; private Integer tel; private String password; public User() { } public User(String username, Integer tel, String password) { this.username = username; this.tel = tel; this.password = password; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public Integer getTel() { return tel; } public void setTel(Integer tel) { this.tel = tel; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } } ``` ## 9:编写dao层接口UserDao ``` package dao; import domain.User; import org.apache.ibatis.annotations.Insert; import org.springframework.stereotype.Repository; @Repository public interface UserDao { @Insert("insert into user values(#{username},#{tel},#{password})") void insert(User user); } ``` ## 10:编写service层接口UserService ``` package service; import domain.User; public interface UserService { void insert(User user); } ``` ## 11:编写service层实现类UserServiceImpl ``` package service.impl; import dao.UserDao; import domain.User; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import service.UserService; @Service public class UserServiceImpl implements UserService { @Autowired private UserDao userDao; public void insert(User user) { userDao.insert(user); } } ``` ## 12:编写Controller类UserController ``` package controller; import com.sun.codemodel.internal.JMethod; import domain.User; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import service.UserService; @Controller @RequestMapping("user") public class UserController { @Autowired private UserService userService; @ResponseBody @RequestMapping(value = "register" ,method = RequestMethod.POST) public String insert(User user){ userService.insert(user); return "success"; } } ``` ## 13:编写index.html ``` <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Register</title> </head> <body> <form action="/user/register" method="post"> <input type="text" name="username"> <input type="text" name="tel"> <input type="password" name="password"> <input type="submit"> </form> </body> </html> ``` ## 14:编写pages文件夹下的success.html ``` <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Success</title> </head> <body> <h3>Success!...</h3> </body> </html> ```
spring data jpa 使用注解(AbstractRoutingDataSource)实现多数据源,定时任务和新建线程的方法,却无法进行数据库操作?
Spring boot2.X项目,使用data jpa 框架,普通方法可以实现数据源的切换,但是新建线程和定时任务里面执行方法,却不能插入和修改数据库,并且控制端无日志输出。可以查询数据。 相同的多数据源配置,使用mybatis框架不存在这样的情况。 ``` /** * 数据源配置 */ @Configuration public class DataSourceConfig { @Autowired private DBProperties properties; @Bean(name = "dataSource") public DataSource dataSource() { //按照目标数据源名称和目标数据源对象的映射存放在Map中 Map<Object, Object> targetDataSources = new HashMap<>(); targetDataSources.put("first", properties.getFirst()); targetDataSources.put("second", properties.getSecond()); targetDataSources.put("third", properties.getThird()); //采用是想AbstractRoutingDataSource的对象包装多数据源 DynamicDataSource dataSource = new DynamicDataSource(); dataSource.setTargetDataSources(targetDataSources); //设置默认的数据源,当拿不到数据源时,使用此配置 dataSource.setDefaultTargetDataSource(properties.getFirst()); return dataSource; } @Bean public PlatformTransactionManager transactionManager() { return new DataSourceTransactionManager(dataSource()); } } ``` 补充: ``` @Scheduled(cron = "0 0/1 * * * ?") public void aioCallMethod() { System.out.println("timer start"); Calendar calendar = Calendar.getInstance(); int hour = calendar.get(Calendar.HOUR_OF_DAY); if (hour == 21) { calendar.set(Calendar.HOUR_OF_DAY, 9); } else { calendar.set(Calendar.HOUR_OF_DAY, 21); calendar.add(Calendar.DATE, -1); } calendar.set(Calendar.MINUTE, 30); calendar.set(Calendar.SECOND, 0); calendar.set(Calendar.MILLISECOND, 0); Date date1 = calendar.getTime(); calendar.add(Calendar.HOUR_OF_DAY, 12); Date date2 = calendar.getTime(); Date date = DateUtil.toDate(new Date(), "yyyy-MM-dd"); List<DiamondWireRecord> diamondWireRecords = new ArrayList<>(); DiamondWireRecord diamondWireRecord; String deviceNo; List<EquipmentAccessory> equipmentAccessories = equipmentAccessoryService.findAll(); for (EquipmentAccessory equipmentAccessory : equipmentAccessories) { //设备编号 deviceNo = equipmentAccessory.getDeviceNo(); diamondWireRecord = new DiamondWireRecord(); //记录时间 diamondWireRecord.setCreateDate(date); diamondWireRecord.setDeviceNo(deviceNo); diamondWireRecords.add(diamondWireRecord); } System.out.println("update start"); if (diamondWireRecords.size() > 0) { diamondWireRecordService.saveAll(diamondWireRecords); } System.out.println("update end"); } ```
springmvc在一个index.jsp页面调用一个result.jsp页面报错“源服务器未能找到目标资源的表示或者是不愿公开一个已经存在的资源表示。”
我在springMVC框架搭建是用了一个网上找的demo,现在index.jsp页面可以打开,但是通过servlet调用result.jsp页面总是报错。 index.jsp页面截图如下: ![图片说明](https://img-ask.csdn.net/upload/202002/28/1582885267_906800.jpg) 打开result.jsp页面是报错截图如下: ![图片说明](https://img-ask.csdn.net/upload/202002/28/1582885322_302177.jpg) 整个demo在eclipse中目录结构为: ![图片说明](https://img-ask.csdn.net/upload/202002/28/1582885563_217315.jpg) 整个demo项目名称为springMvcDemo,其中web.xml、Main-servlet.xml、index.jsp、result.jsp文件都在WEB-INF目录,java代码文件helloworld.java在Java Resources\src下面的包com.spring.handlers中。 1、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_2_5.xsd" id="WebApp_ID" version="2.5"> <!-- 配置DispatchcerServlet --> <servlet> <servlet-name>Main</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!-- load-on-startup:表示启动容器时初始化该Servlet; --> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>Main</servlet-name> <!-- url-pattern:表示哪些请求交给Spring Web MVC处理, “/” 是用来定义默认servlet映射的。 --> <!-- 也可以如“*.html”表示拦截所有以html为扩展名的请求。 --> <url-pattern>/</url-pattern> </servlet-mapping> <!-- 至此请求已交给Spring Web MVC框架处理,因此我们需要配置Spring的配置文件, --> <!-- 默认DispatcherServlet会加载WEB-INF/[DispatcherServlet的Servlet名字,也就是上面的Main]-servlet.xml配置文件。 --> <!-- 即Main-servlet.xml --> </web-app> ``` 2、Main-servlet.xml文件代码为: ``` <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 http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"> <!-- 配置自动扫描的包 --> <context:component-scan base-package="com.spring.handlers"></context:component-scan> <!-- 配置视图解析器 如何把handler 方法返回值解析为实际的物理视图 --> <!--prefix和suffix:查找视图页面的前缀和后缀(前缀[逻辑视图名]后缀), --> <!-- 比如传进来的逻辑视图名为result,则该该jsp视图页面应该存放在“/WEB-INF/result.jsp” --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name = "prefix" value="/"></property> <property name = "suffix" value = ".jsp"></property> </bean> </beans> ``` 3、index.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>Insert title here</title> </head> <body> <a href="click">什么东西?点击这里!!!</a> </body> </html> ``` 4、result.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>Insert title here</title> </head> <body> <a>成功!</a> </body> </html> ``` 我电脑环境为: 1、操作系统win10专业版 2、Tomcat9.0 3、Eclipse2019-12 4、spring的jar包版本是5.2.3 其中Tomcat在Eclipse中的配置为: ![图片说明](https://img-ask.csdn.net/upload/202002/28/1582888505_680047.jpg) 曾经出现过启动Tomcat服务报错的情况,在网上找了一些方法,把Tomcat中的server.xml文件中的 ``` <Context docBase="springMvcDemo" path="/springMvcDemo" reloadable="true" source="org.eclipse.jst.jee.server:springMvcDemo"/> ``` 修改为: ``` <Context docBase="" path="" reloadable="true" source="org.eclipse.jst.jee.server:springMvcDemo"/> ``` 这样启动不再报错,虽不是长久之计,但是再没有更好的办法之前先这么用,不知道这个是否是造成这个问题的原因。
关于Spring boot + SpringSecurity +jwt token失效的问题
比如我登abc的用户,然后我在另一个地点也登abc的用户,那前一个登陆的在刷新或者请求接口的时候要登出, 或者是我后台改了abc的密码,那abc这个账户在刷新请求接口的时候要登出。 框架我搭好了 代码如下: 生成token工具类: ``` public class JwtTokenUtil { private static InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("jwt.jks"); // 寻找证书文件 private static PrivateKey privateKey = null; private static PublicKey publicKey = null; static { // 将证书文件里边的私钥公钥拿出来 try { KeyStore keyStore = KeyStore.getInstance("JKS"); // java key store 固定常量 keyStore.load(inputStream, "123456".toCharArray()); privateKey = (PrivateKey) keyStore.getKey("jwt", "123456".toCharArray()); // jwt 为 命令生成整数文件时的别名 publicKey = keyStore.getCertificate("jwt").getPublicKey(); } catch (Exception e) { e.printStackTrace(); } } public static String generateToken(String subject, int expirationSeconds, String salt) { return Jwts.builder() .setClaims(null) .setSubject(subject) .setExpiration(new Date(System.currentTimeMillis() + expirationSeconds * 1000)) // .signWith(SignatureAlgorithm.HS512, salt) // 不使用公钥私钥 .signWith(SignatureAlgorithm.RS256, privateKey) .compact(); } public static String parseToken(String token, String salt) { String subject = null; try { Claims claims = Jwts.parser() // .setSigningKey(salt) // 不使用公钥私钥 .setSigningKey(publicKey) .parseClaimsJws(token).getBody(); subject = claims.getSubject(); } catch (Exception e) { } return subject; } } ``` 登陆成功后生成JTWtoken : ``` @Component public class AjaxAuthenticationSuccessHandler implements AuthenticationSuccessHandler { @Override public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException { ResponseBase responseBase = new ResponseBase(); responseBase.setCode("200"); responseBase.setMassage("Login Success!"); String jwtToken = JwtTokenUtil.generateToken(String.valueOf(authentication.getPrincipal()), 300, "_secret"); responseBase.setJwtToken(jwtToken); httpServletResponse.getWriter().write(JSON.toJSONString(responseBase)); } } ``` 监听器: ``` @Component public class JwtAuthenticationTokenFilter extends OncePerRequestFilter { @Autowired AdminSysUserSecurityService adminSysUserSecurityService; @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException { String authHeader = request.getHeader("Authorization"); if (authHeader != null && authHeader.startsWith("Bearer ")) { final String authToken = authHeader.substring("Bearer ".length()); String username = JwtTokenUtil.parseToken(authToken, "_secret"); if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) { UserDetails userDetails = adminSysUserSecurityService.loadUserByUsername(username); if (userDetails != null) { UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities()); authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request)); SecurityContextHolder.getContext().setAuthentication(authentication); } } } chain.doFilter(request, response); } } ``` ``` @Component("rbacauthorityservice") public class RbacAuthorityService { public boolean hasPermission(HttpServletRequest request, Authentication authentication) { Object userInfo = authentication.getPrincipal(); boolean hasPermission = false; if (userInfo instanceof UserDetails) { String username = ((UserDetails) userInfo).getUsername(); //获取资源 Set<String> urls = new HashSet(); urls.add("/**/**"); // 这些 url 都是要登录后才能访问,且其他的 url 都不能访问! Set set2 = new HashSet(); Set set3 = new HashSet(); AntPathMatcher antPathMatcher = new AntPathMatcher(); for (String url : urls) { if (antPathMatcher.match(url, request.getRequestURI())) { hasPermission = true; break; } } return hasPermission; } else { return false; } } } ``` 配置: ``` @Configuration public class AdminWebSecurityConfig extends WebSecurityConfigurerAdapter { @Value("${pay.strength}") private int strength; @Autowired private AdminSysUserSecurityService adminSysUserSecurityService; @Bean public PasswordEncoder passwordEncoder(){ // return NoOpPasswordEncoder.getInstance();//不对密码加密 return new BCryptPasswordEncoder(strength);//秘钥迭代次数为 2^strength,strength取值在 4-31 之间,默认10 } @Autowired AjaxAuthenticationEntryPoint authenticationEntryPoint; // 未登陆时返回 JSON 格式的数据给前端(否则为 html) @Autowired AjaxAuthenticationSuccessHandler authenticationSuccessHandler; // 登录成功返回的 JSON 格式数据给前端(否则为 html) @Autowired AjaxAuthenticationFailureHandler authenticationFailureHandler; // 登录失败返回的 JSON 格式数据给前端(否则为 html) @Autowired AjaxLogoutSuccessHandler logoutSuccessHandler; // 注销成功返回的 JSON 格式数据给前端(否则为 登录时的 html) @Autowired AjaxAccessDeniedHandler accessDeniedHandler; // 无权访问返回的 JSON 格式数据给前端(否则为 403 html 页面) @Autowired JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter; // JWT 拦截器 @Autowired SelfAuthenticationProvider provider; // 自定义安全认证 @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { // 加入自定义的安全认证 auth.authenticationProvider(provider); } @Override public void configure(HttpSecurity http)throws Exception{ //开启HttpSecurity配置 http.csrf().disable() .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS) // 使用 JWT,关闭token .and() .httpBasic().authenticationEntryPoint(authenticationEntryPoint) .and() .authorizeRequests() // .antMatchers("/db/**").hasRole("DB") // .antMatchers("/user/**").hasRole("USER") // .antMatchers("/admin/**").hasRole("ADMIN") // .antMatchers("/user/**").access("hasAnyRole('ADMIN','ROOT')") // .antMatchers("/db/**").access("hasAnyRole('ADMIN') and hasRole('DBA')") //除了前面路径,用户访问其他URL都必须认证后访问 .anyRequest() .access("@rbacauthorityservice.hasPermission(request,authentication)") // RBAC 动态 url 认证 .and() //开启表单登录,同事配置了登入接口为/login .formLogin() /* //该接口主要方便ajax或者移动端登入 .loginProcessingUrl("/login") //设置登录成功跳转页面,error=true控制页面错误信息的展示 .successForwardUrl("/index").failureUrl("/login?error=true") */ //登入接口都不需要认证 .successHandler(authenticationSuccessHandler) // 登录成功 .failureHandler(authenticationFailureHandler) // 登录失败 .permitAll() .and() //开启注销登入配置 .logout() .logoutSuccessHandler(logoutSuccessHandler) .permitAll(); http.rememberMe().rememberMeParameter("remember-me") .userDetailsService(adminSysUserSecurityService).tokenValiditySeconds(300); http.exceptionHandling().accessDeniedHandler(accessDeniedHandler); // 无权访问 JSON 格式的数据 http.addFilterBefore(jwtAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class); // JWT Filter } ``` 登陆成功后获取token,postman测试: ![图片说明](https://img-ask.csdn.net/upload/201912/11/1576056718_177252.png) 可以 但是我重新调用新的登陆接口,相同用户名获取新的token后,原来的token依旧可以请求。 所以要在哪边配置 用户其它地方登陆,或者用户密码变更,jtwtoken失效
springboot2.x引入spring-boot-starter-data-redis依赖,启动报错
springboot2.x引入spring-boot-starter-data-redis依赖,启动报错,redis框架用的jedis就没问题,2.x默认用的是lettuce却出现了以下错误,为什么会这样,这个问题折腾了两三天了,快点来个大神拯救我吧 pom: ![图片说明](https://img-ask.csdn.net/upload/201910/10/1570679165_510992.png) 报错: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'application': Unsatisfied dependency expressed through field 'stringredistemplate'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'stringRedisTemplate' defined in class path resource [org/springframework/boot/autoconfigure/data/redis/RedisAutoConfiguration.class]: Unsatisfied dependency expressed through method 'stringRedisTemplate' parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'redisConnectionFactory' defined in class path resource [org/springframework/boot/autoconfigure/data/redis/LettuceConnectionConfiguration.class]: Unsatisfied dependency expressed through method 'redisConnectionFactory' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'lettuceClientResources' defined in class path resource [org/springframework/boot/autoconfigure/data/redis/LettuceConnectionConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [io.lettuce.core.resource.DefaultClientResources]: Factory method 'lettuceClientResources' threw exception; nested exception is java.lang.NoClassDefFoundError: io/netty/util/internal/logging/InternalLoggerFactory at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:596) at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:90) at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:374) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1395) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:592) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:515) at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320) at org.springframework.beans.factory.support.AbstractBeanFactory$$Lambda$112/464064894.getObject(Unknown Source) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199) at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:849) at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:877) at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:549) at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:142) at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:775) at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:397) at org.springframework.boot.SpringApplication.run(SpringApplication.java:316) at org.springframework.boot.SpringApplication.run(SpringApplication.java:1260) at org.springframework.boot.SpringApplication.run(SpringApplication.java:1248) at com.xxx.demo.Application.main(Application.java:50) Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'stringRedisTemplate' defined in class path resource [org/springframework/boot/autoconfigure/data/redis/RedisAutoConfiguration.class]: Unsatisfied dependency expressed through method 'stringRedisTemplate' parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'redisConnectionFactory' defined in class path resource [org/springframework/boot/autoconfigure/data/redis/LettuceConnectionConfiguration.class]: Unsatisfied dependency expressed through method 'redisConnectionFactory' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'lettuceClientResources' defined in class path resource [org/springframework/boot/autoconfigure/data/redis/LettuceConnectionConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [io.lettuce.core.resource.DefaultClientResources]: Factory method 'lettuceClientResources' threw exception; nested exception is java.lang.NoClassDefFoundError: io/netty/util/internal/logging/InternalLoggerFactory at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:769) at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:509) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1305) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1144) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:515) at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320) at org.springframework.beans.factory.support.AbstractBeanFactory$$Lambda$117/509891820.getObject(Unknown Source) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199) at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:277) at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1247) at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1167) at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:593) ... 20 common frames omitted Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'redisConnectionFactory' defined in class path resource [org/springframework/boot/autoconfigure/data/redis/LettuceConnectionConfiguration.class]: Unsatisfied dependency expressed through method 'redisConnectionFactory' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'lettuceClientResources' defined in class path resource [org/springframework/boot/autoconfigure/data/redis/LettuceConnectionConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [io.lettuce.core.resource.DefaultClientResources]: Factory method 'lettuceClientResources' threw exception; nested exception is java.lang.NoClassDefFoundError: io/netty/util/internal/logging/InternalLoggerFactory at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:769) at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:509) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1305) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1144) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:515) at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320) at org.springframework.beans.factory.support.AbstractBeanFactory$$Lambda$117/509891820.getObject(Unknown Source) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199) at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:277) at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1247) at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1167) at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:857) at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:760) ... 34 common frames omitted Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'lettuceClientResources' defined in class path resource [org/springframework/boot/autoconfigure/data/redis/LettuceConnectionConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [io.lettuce.core.resource.DefaultClientResources]: Factory method 'lettuceClientResources' threw exception; nested exception is java.lang.NoClassDefFoundError: io/netty/util/internal/logging/InternalLoggerFactory at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:627) at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:456) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1305) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1144) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:515) at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320) at org.springframework.beans.factory.support.AbstractBeanFactory$$Lambda$117/509891820.getObject(Unknown Source) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199) at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:277) at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1247) at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1167) at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:857) at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:760) ... 49 common frames omitted Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [io.lettuce.core.resource.DefaultClientResources]: Factory method 'lettuceClientResources' threw exception; nested exception is java.lang.NoClassDefFoundError: io/netty/util/internal/logging/InternalLoggerFactory at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:185) at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:622) ... 64 common frames omitted Caused by: java.lang.NoClassDefFoundError: io/netty/util/internal/logging/InternalLoggerFactory at io.lettuce.core.resource.DefaultClientResources.<clinit>(DefaultClientResources.java:74) at org.springframework.boot.autoconfigure.data.redis.LettuceConnectionConfiguration.lettuceClientResources(LettuceConnectionConfiguration.java:67) at org.springframework.boot.autoconfigure.data.redis.LettuceConnectionConfiguration$$EnhancerBySpringCGLIB$$6bcc0637.CGLIB$lettuceClientResources$1(<generated>) at org.springframework.boot.autoconfigure.data.redis.LettuceConnectionConfiguration$$EnhancerBySpringCGLIB$$6bcc0637$$FastClassBySpringCGLIB$$ef2b1aca.invoke(<generated>) at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:244) at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:363) at org.springframework.boot.autoconfigure.data.redis.LettuceConnectionConfiguration$$EnhancerBySpringCGLIB$$6bcc0637.lettuceClientResources(<generated>) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:154) ... 65 common frames omitted Caused by: java.lang.ClassNotFoundException: io.netty.util.internal.logging.InternalLoggerFactory at java.net.URLClassLoader$1.run(Unknown Source) at java.net.URLClassLoader$1.run(Unknown Source) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(Unknown Source) at java.lang.ClassLoader.loadClass(Unknown Source) at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source) at java.lang.ClassLoader.loadClass(Unknown Source) ... 77 common frames omitted
Java ssm 框架 访问报错500
报错如下: ``` HTTP Status 500 – Internal Server Error Type Exception Report Message Servlet.init() for servlet SpringMVC threw exception Description The server encountered an unexpected condition that prevented it from fulfilling the request. Exception javax.servlet.ServletException: Servlet.init() for servlet SpringMVC threw exception org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:478) org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:80) org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:341) org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:783) org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:798) org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1441) org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) java.lang.Thread.run(Thread.java:745) Root Cause org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.context.annotation.internalAsyncAnnotationProcessor': Initialization of bean failed; nested exception is java.lang.NoSuchMethodError: org.springframework.aop.interceptor.AsyncExecutionInterceptor.<init>(Ljava/util/concurrent/Executor;Lorg/springframework/aop/interceptor/AsyncUncaughtExceptionHandler;)V org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:547) org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476) org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303) org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299) org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199) org.springframework.context.support.PostProcessorRegistrationDelegate.registerBeanPostProcessors(PostProcessorRegistrationDelegate.java:220) org.springframework.context.support.AbstractApplicationContext.registerBeanPostProcessors(AbstractApplicationContext.java:615) org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:465) org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:663) org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:629) org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:677) org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:548) org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:489) org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:136) javax.servlet.GenericServlet.init(GenericServlet.java:158) org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:478) org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:80) org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:341) org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:783) org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:798) org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1441) org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) java.lang.Thread.run(Thread.java:745) Root Cause java.lang.NoSuchMethodError: org.springframework.aop.interceptor.AsyncExecutionInterceptor.<init>(Ljava/util/concurrent/Executor;Lorg/springframework/aop/interceptor/AsyncUncaughtExceptionHandler;)V org.springframework.scheduling.annotation.AnnotationAsyncExecutionInterceptor.<init>(AnnotationAsyncExecutionInterceptor.java:60) org.springframework.scheduling.annotation.AsyncAnnotationAdvisor.buildAdvice(AsyncAnnotationAdvisor.java:150) org.springframework.scheduling.annotation.AsyncAnnotationAdvisor.<init>(AsyncAnnotationAdvisor.java:99) org.springframework.scheduling.annotation.AsyncAnnotationBeanPostProcessor.setBeanFactory(AsyncAnnotationBeanPostProcessor.java:105) org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeAwareMethods(AbstractAutowireCapableBeanFactory.java:1585) org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1553) org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:539) org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476) org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303) org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299) org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199) org.springframework.context.support.PostProcessorRegistrationDelegate.registerBeanPostProcessors(PostProcessorRegistrationDelegate.java:220) org.springframework.context.support.AbstractApplicationContext.registerBeanPostProcessors(AbstractApplicationContext.java:615) org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:465) org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:663) org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:629) org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:677) org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:548) org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:489) org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:136) javax.servlet.GenericServlet.init(GenericServlet.java:158) org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:478) org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:80) org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:341) org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:783) org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:798) org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1441) org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) java.lang.Thread.run(Thread.java:745) Note The full stack trace of the root cause is available in the server logs. Apache Tomcat/8.5.12 ``` 一搭到服务器上就出现这个错误,但是本地window没问题;卡了一天了,脑瓜子呼呼的,第一次用这个玩意,实在看不出来啥问题了,有没有大佬帮忙指点指点,给条明路呀!! 下面是几个基础配置: 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-mybatis.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> <filter> <filter-name>CORSFilter</filter-name> <filter-class>com.bls.mp.common.MyFilter</filter-class> <init-param> <param-name>excludedPages</param-name> <param-value>/UserAuthServlet</param-value> </init-param> </filter> <filter-mapping> <filter-name>CORSFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <listener> <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class> </listener> <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> <url-pattern>/</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>/index.jsp</welcome-file> </welcome-file-list> </web-app> ``` spring-mvc.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:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:task="http://www.springframework.org/schema/task" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.0.xsd" > <!-- 自动扫描该包,使SpringMVC认为包下用了@controller注解的类是控制器 --> <context:component-scan base-package="com.bls.mp.controller"/> <!--避免IE执行AJAX时,返回JSON出现下载文件 --> <bean id="mappingJacksonHttpMessageConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"> <property name="supportedMediaTypes"> <list> <value>text/html;charset=UTF-8</value> </list> </property> </bean> <!-- <bean id="thirdDataService" class="com.bls.mp.service.impl.ThirdDataServiceImpl"/>--> <bean class="com.bls.mp.common.SpringTool"/> <!-- 启动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="/WEB-INF/resources/jsp/" /> <property name="suffix" value=".jsp" /> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"></property> </bean> <!-- 配置文件上传,如果没有使用文件上传可以不用配置,当然如果不配,那么配置文件中也不必引入上传组件包 --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!-- 默认编码 --> <property name="defaultEncoding" value="utf-8" /> <!-- 文件大小最大值 --> <property name="maxUploadSize" value="10485760000" /> <!-- 内存中的最大值 --> <property name="maxInMemorySize" value="40960" /> </bean> <!-- 全局异常处理器 --> <bean class="com.bls.mp.common.exception.CustomExceptionResolver"></bean> <mvc:annotation-driven/> <!-- 拦截器配置 --> <mvc:interceptors> <mvc:interceptor> <mvc:mapping path="/setadmin"/> <!--<mvc:mapping path="/user/userList"/> --> <mvc:mapping path="/Blocker"/> <mvc:mapping path="/goods/goods"/> <bean class="com.bls.mp.interceptor.AuthInterceptor"></bean> </mvc:interceptor> </mvc:interceptors> <task:annotation-driven/> <!-- 配置访问静态文件 --> <mvc:default-servlet-handler/> <mvc:resources location="/images/" mapping="/images/**"/> <mvc:resources location="/WEB-INF/js/" mapping="/js/**"/> <mvc:resources location="/WEB-INF/resources/jsp/" mapping="/jsp/**"/> <mvc:resources location="/WEB-INF/resources/css/" mapping="/css/**"/> </beans> ``` spring-mybatis.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: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-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd"> <!-- 自动扫描 --> <context:component-scan base-package="com.bls.mp"/> <!-- 引入配置文件 --> <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="location" value="classpath:jdbc.properties" /> </bean> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="${jdbc.driver}" /> <property name="url" value="${jdbc.url}" /> <property name="username" value="${jdbc.username}" /> <property name="password" value="${jdbc.password}" /> <!-- 初始化连接大小 --> <property name="initialSize" value="${initialSize}"></property> <!-- 连接池最大数量 --> <property name="maxActive" value="${maxActive}"></property> <!-- 连接池最大空闲 --> <property name="maxIdle" value="${maxIdle}"></property> <!-- 连接池最小空闲 --> <property name="minIdle" value="${minIdle}"></property> <!-- 获取连接最大等待时间 --> <property name="maxWait" value="${maxWait}"></property> </bean> <!-- spring和MyBatis完美整合,不需要mybatis的配置映射文件 --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <!-- 自动扫描mapping.xml文件 --> <property name="mapperLocations" value="classpath:com/bls/mp/mapping/*.xml"></property> </bean> <!-- DAO接口所在包名,Spring会自动查找其下的类 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.bls.mp.dao" /> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property> </bean> <!-- (事务管理)transaction manager, use JtaTransactionManager for global tx --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean> </beans> ``` jdk版本: 1.8.0_222 tomcat 版本:8.0 有没有大佬来给看看呀0.0
@EnableTransactionManagement开启事务注解驱动
> Spring Boot 使用事务非常简单,首先使用注解 @EnableTransactionManagement 开启事务支持后,然后在访问数据库的Service方法上添加注解 @Transactional 便可。 > > 关于事务管理器,不管是JPA还是JDBC等都实现自接口 PlatformTransactionManager 如果你添加的是 spring-boot-starter-jdbc 依赖,框架会默认注入 DataSourceTransactionManager 实例。如果你添加的是 spring-boot-starter-data-jpa 依赖,框架会默认注入 JpaTransactionManager 实例。 这是其他博主给的结论,但是为什么我用了@EnableTransactionManagement注解,运行时,却报错“ No qualifying bean of type 'org.springframework.transaction.PlatformTransactionManager' available”,需要我手动注入TransactionManager,不是说会自动注入的嘛? ![图片说明](https://img-ask.csdn.net/upload/201907/11/1562807775_812625.png)
关于spring+hibernate配置多数据源的问题
我的项目是个webservice项目,使用了hibernate+spring框架,由于项目中要用到两个数据库(都是oracle数据库),我在网上查了一些资料,但是在我的项目中做数据源切换的时候总是切换不过去,也就是说只能连接默认的数据源,一下是我的spring配置文件: <?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:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd" default-autowire="byName"> <context:annotation-config /> <!-- AXIS2通过该对象加载spring中的bean 固定配置 --> <bean id="applicationContext" class="org.apache.axis2.extensions.spring.receivers.ApplicationContextHolder" /> <!-- end --> <!-- AXIS2本地业务配置 --> <bean id="PAPWebService" class="com.pap.ws.PAPWebService" /> <!-- end --> <context:component-scan base-package="com.pap"> <context:include-filter type="regex" expression=".dao.impl.*" /> <context:include-filter type="regex" expression=".serviec.impl.*" /> <context:include-filter type="regex" expression=".entity.*" /> </context:component-scan> <bean id="tmsDataSource" class="org.logicalcobwebs.proxool.ProxoolDataSource"> <property name="driver" value="oracle.jdbc.driver.OracleDriver" /> <property name="driverUrl" value="jdbc:oracle:thin:@172.17.30.80:1521:tms" /> <property name="user" value="SELFSERVICE" /> <property name="password" value="Password123" /> <!-- 最大数据库连接数 --> <property name="maximumConnectionCount" value="100" /> <!-- 最小数据库连接数 --> <property name="minimumConnectionCount" value="3" /> <!-- 最少保持的空闲连接数(默认2个) --> <property name="prototypeCount" value="3" /> <!-- 没有空闲连接可以分配而在队列中等候的最大请求数,超过这个请求数的用户连接就不会被接受 --> <!-- <property name="maximumNewConnections" value="20"/> --> <!-- 最大的并发连接数 --> <property name="simultaneousBuildThrottle" value="50" /> <!-- proxool自动侦察各个连接状态的时间间隔(毫秒),侦察到空闲的连接就马上回收,超时的销毁 默认30秒 --> <property name="houseKeepingSleepTime" value="10000" /> <!-- 用于保持连接的测试语句 --> <property name="houseKeepingTestSql" value="select sysdate from dual" /> <!-- 在使用之前测试 --> <property name="testBeforeUse" value="true" /> </bean> <bean id="hisDataSource" class="org.logicalcobwebs.proxool.ProxoolDataSource"> <property name="driver" value="oracle.jdbc.driver.OracleDriver" /> <property name="driverUrl" value="jdbc:oracle:thin:@172.17.1.252:1521:ORCL" /> <property name="user" value="system" /> <property name="password" value="aaaaaa" /> <!-- 最大数据库连接数 --> <property name="maximumConnectionCount" value="100" /> <!-- 最小数据库连接数 --> <property name="minimumConnectionCount" value="3" /> <!-- 最少保持的空闲连接数(默认2个) --> <property name="prototypeCount" value="3" /> <!-- 没有空闲连接可以分配而在队列中等候的最大请求数,超过这个请求数的用户连接就不会被接受 --> <!-- <property name="maximumNewConnections" value="20"/> --> <!-- 最大的并发连接数 --> <property name="simultaneousBuildThrottle" value="50" /> <!-- proxool自动侦察各个连接状态的时间间隔(毫秒),侦察到空闲的连接就马上回收,超时的销毁 默认30秒 --> <property name="houseKeepingSleepTime" value="10000" /> <!-- 用于保持连接的测试语句 --> <property name="houseKeepingTestSql" value="select sysdate from dual" /> <!-- 在使用之前测试 --> <property name="testBeforeUse" value="true" /> </bean> <bean id="dynamicDataSource" class="com.pap.datasource.DynamicDataSource"> <!-- 通过key-value的形式来关联数据源 --> <property name="targetDataSources"> <map key-type="java.lang.String"> <entry value-ref="tmsDataSource" key="tmsDataSource"></entry> <entry value-ref="hisDataSource" key="hisDataSource"></entry> </map> </property> <property name="defaultTargetDataSource" ref="tmsDataSource"> </property> </bean> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"> <property name="dataSource" ref="dynamicDataSource" /> <property name="packagesToScan"> <list> <value>com.pap.entity</value> </list> </property> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">org.hibernate.dialect.Oracle9Dialect</prop> <prop key="hibernate.show_sql">true</prop> <prop key="hibernate.format_sql">true</prop> <!-- <prop key="hibernate.hbm2ddl.auto">update</prop> --> </props> </property> </bean> <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory" /> </bean> <tx:annotation-driven transaction-manager="transactionManager" /> </beans> 下面是我写的两个用于切换数据源的类: DataSourceContextHolder.java package com.pap.datasource; public class DataSourceContextHolder { public static final String DATA_SOURCE_TMS = "tmsDataSource"; public static final String DATA_SOURCE_HIS = "hisDataSource"; private static final ThreadLocal<String> contextHolder = new ThreadLocal<String>(); public static void setDataSourceType(String customerType) { contextHolder.set(customerType); } public static String getDataSourceType() { return contextHolder.get(); } public static void clearDataSourceType() { contextHolder.remove(); } } DynamicDataSource.java package com.pap.datasource; import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource; public class DynamicDataSource extends AbstractRoutingDataSource { @Override protected Object determineCurrentLookupKey() { return DataSourceContextHolder.getDataSourceType(); } } dao层代码 package com.pap.dao.impl; import java.io.Serializable; import java.util.List; import org.hibernate.criterion.DetachedCriteria; import org.springframework.orm.hibernate3.support.HibernateDaoSupport; import org.springframework.stereotype.Repository; import com.pap.dao.BaseDao; @Repository("baseDao") public class BaseDaoImpl extends HibernateDaoSupport implements BaseDao{ @Override public <T> Serializable save(T entity) throws Exception { Serializable s = this.getHibernateTemplate().save(entity); return s; } @Override public <T> void update(T entity) throws Exception { this.getHibernateTemplate().update(entity); } @SuppressWarnings("unchecked") @Override public <T> List<T> query(String hql,Object[] values) throws Exception { return this.getHibernateTemplate().find(hql, values); } @Override public <T> List<T> query(String hql, Object value) throws Exception { return query(hql, new Object[]{value}); } @Override public <T>T getEntity(Class<T> entityClass, Serializable id) throws Exception { return this.getHibernateTemplate().get(entityClass, id); } @SuppressWarnings("unchecked") @Override public <T> List<T> find(DetachedCriteria detachedCriteria, int firstResult, int maxResults) throws Exception { return getHibernateTemplate().findByCriteria(detachedCriteria, firstResult, maxResults); } @Override @SuppressWarnings("unchecked") public <T> List<T> find(DetachedCriteria criteria) throws Exception { return getHibernateTemplate().findByCriteria(criteria); } } service层代码,我是在这里做的数据源切换 package com.pap.service.impl; import java.util.ArrayList; import java.util.Date; import java.util.List; import javax.annotation.Resource; import org.hibernate.criterion.DetachedCriteria; import org.hibernate.criterion.Restrictions; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import com.pap.dao.BaseDao; import com.pap.datasource.DataSourceContextHolder; import com.pap.entity.ChargeTypeDict; import com.pap.entity.ClinicForRegist; import com.pap.entity.MedicalCard; import com.pap.entity.Patient; import com.pap.entity.SelfTerminal; import com.pap.entity.TransactionRecord; import com.pap.entity.User; import com.pap.service.BaseService; @Service @Transactional(propagation = Propagation.REQUIRED) public class BaseServiceImpl implements BaseService { @Resource private BaseDao baseDao; /** * 查询排号信息 */ @Override public List<ClinicForRegist> queryClinicForRegist(java.sql.Date clinicDate, Object[] timeDesc, int firstResult, int maxResults) throws Exception { DataSourceContextHolder.setDataSourceType(DataSourceContextHolder.DATA_SOURCE_HIS); DetachedCriteria detachedCriteria = DetachedCriteria.forClass(ClinicForRegist.class); detachedCriteria.add(Restrictions.eq("clinicDate", clinicDate)); detachedCriteria.add(Restrictions.in("timeDesc", timeDesc)); List<ClinicForRegist> list = baseDao.find(detachedCriteria, firstResult, maxResults); DataSourceContextHolder.clearDataSourceType(); return list; } } webservice接口类 package com.pap.ws; import java.sql.Timestamp; import java.util.Calendar; import java.util.Date; import java.util.List; import javax.annotation.Resource; import org.apache.log4j.Logger; import com.pap.entity.ChargeTypeDict; import com.pap.entity.ClinicForRegist; import com.pap.entity.ClinicIndex; import com.pap.entity.DeptDict; import com.pap.entity.MedicalCard; import com.pap.entity.Patient; import com.pap.entity.Privileges; import com.pap.entity.Response; import com.pap.entity.SelfTerminal; import com.pap.entity.TransactionRecord; import com.pap.entity.User; import com.pap.service.BaseService; import com.pap.util.MD5Util; public class PAPWebService { @Resource BaseService baseService; /** * 查询可挂号信息 * @param firstResult 起始条数 * @param maxResults 最大条数 * @return */ public Response queryClinicRegist(int firstResult, int maxResults) { Response response = new Response(); try { Calendar calendar = Calendar.getInstance(); int hour = calendar.get(Calendar.HOUR_OF_DAY); String[] timeDesc = null; if (8 < hour && hour < 12) { timeDesc = new String[] { "白天", "上午", "下午", "昼夜" }; } else if (hour > 11 && hour < 18) { timeDesc = new String[] { "白天", "下午", "昼夜" }; } else { timeDesc = new String[] {"昼夜" }; } List<ClinicForRegist> list = baseService.queryClinicForRegist(new java.sql.Date(calendar.getTimeInMillis()), timeDesc, firstResult, maxResults); if(list.size() > 0){ response.setResult("S"); response.setArrayData(list); }else{ response.setResult("F"); response.setResult("没有查询到记录"); } } catch (Exception e) { e.printStackTrace(); response.setResult("F"); response.setErrorInfo(e.getMessage()); } return response; } public void setClinicForRegist(ClinicForRegist clinicForRegist){ } public void setClinicIndex(ClinicIndex clinicIndex){ } public void setDeptDict(DeptDict deptDict){ } }
ssm 框架,在本地环境下完美运行,在服务器上定时器执行两次
## 此处为 spring-mybatis.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:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd"> <!-- 自动扫描 --> <!-- 激活自动代理功能 --> <!-- 引入配置文件 --> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="${jdbc.driver}" /> <property name="url" value="${jdbc.url}" /> <property name="username" value="${jdbc.username}" /> <property name="password" value="${jdbc.password}" /> <!-- 初始化连接大小 --> <property name="initialSize" value="${initialSize}"></property> <!-- 连接池最大数量 --> <property name="maxActive" value="${maxActive}"></property> <!-- 连接池最大空闲 --> <property name="maxIdle" value="${maxIdle}"></property> <!-- 连接池最小空闲 --> <property name="minIdle" value="${minIdle}"></property> <!-- 获取连接最大等待时间 --> <property name="maxWait" value="${maxWait}"></property> </bean> <!-- spring和MyBatis完美整合,不需要mybatis的配置映射文件 --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <!-- 自动扫描mapping.xml文件 --> <property name="mapperLocations" value="classpath:com/bls/mp/mapping/*.xml"></property> </bean> <!-- DAO接口所在包名,Spring会自动查找其下的类 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.bls.mp.dao" /> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property> </bean> <!-- (事务管理)transaction manager, use JtaTransactionManager for global tx --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean> </beans> ``` ## 此处为 spring-mvc.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:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:task="http://www.springframework.org/schema/task" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.0.xsd" > <!-- 自动扫描该包,使SpringMVC认为包下用了@controller注解的类是控制器 --> <context:component-scan base-package="com.bls.mp.*"/> <!--避免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> <!-- <bean id="thirdDataService" class="com.bls.mp.service.impl.ThirdDataServiceImpl"/>--> <bean class="com.bls.mp.common.SpringTool"/> <!-- 启动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="/WEB-INF/resources/jsp/" /> <property name="suffix" value=".jsp" /> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"></property> </bean> <!-- 配置文件上传,如果没有使用文件上传可以不用配置,当然如果不配,那么配置文件中也不必引入上传组件包 --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!-- 默认编码 --> <property name="defaultEncoding" value="utf-8" /> <!-- 文件大小最大值 --> <property name="maxUploadSize" value="10485760000" /> <!-- 内存中的最大值 --> <property name="maxInMemorySize" value="40960" /> </bean> <!-- 全局异常处理器 --> <bean class="com.bls.mp.common.exception.CustomExceptionResolver"></bean> <mvc:annotation-driven/> <!-- 拦截器配置 --> <mvc:interceptors> <mvc:interceptor> <mvc:mapping path="/setadmin"/> <!--<mvc:mapping path="/user/userList"/> --> <mvc:mapping path="/Blocker"/> <mvc:mapping path="/grouponteam/grouponRanking"/> <mvc:mapping path="/grouponteam/arriverTime"/> <mvc:mapping path="/grouponteam/paging"/> <mvc:mapping path="/grouponteam/conditionGrouponT"/> <mvc:mapping path="/hospital/hospitalInfo"/> <mvc:mapping path="/hospital/setting"/> <mvc:mapping path="/hospital/orderdetails"/> <mvc:mapping path="/grouponteam/grouponTeamCountAndMoney"/> <mvc:mapping path="/grouponteam/OrderRefundList"/> <mvc:mapping path="/grouponteam/orderdetails"/> <mvc:mapping path="/grouponteam/paging"/> <mvc:mapping path="/grouponteam/conditionGrouponT"/> <mvc:mapping path="/grouponteam/grouponRanking"/> <mvc:mapping path="/grouponteam/arriverTime"/> <mvc:mapping path="/grouponteam/grouponTeamCountAndMoney"/> <mvc:mapping path="/imguoload"/> <mvc:mapping path="/imguoloads"/> <mvc:mapping path="/uploadFile"/> <mvc:mapping path="/uploadCenter"/> <mvc:mapping path="/onTheShelves"/> <mvc:mapping path="/updateTheRecommended"/> <mvc:mapping path="/deleteByGoods"/> <mvc:mapping path="/restoreGoods"/> <mvc:mapping path="/goods/goodslist"/> <mvc:mapping path="/goods/hasBeenOn"/> <mvc:mapping path="/goods/NotOn"/> <mvc:mapping path="/goods/RecycleBin"/> <mvc:mapping path="/goods/searchName"/> <mvc:mapping path="/goods/goodsdiy"/> <mvc:mapping path="/upload/uploadFile"/> <mvc:mapping path="/CreateClassImg"/> <mvc:mapping path="/imglist"/> <mvc:mapping path="/up_img"/> <mvc:mapping path="/moveImg"/> <mvc:mapping path="/deleteImg"/> <mvc:mapping path="/template/templateURL"/> <mvc:mapping path="/template/templateParentAll"/> <mvc:mapping path="/template/templatAll"/> <mvc:mapping path="/template/changeT"/> <mvc:mapping path="/template/deleteT"/> <mvc:mapping path="/TemplateMsg/addTemplateMsg"/> <mvc:mapping path="/TemplateMsg/templateMsgList"/> <mvc:mapping path="/TemplateMsg/templateSendlist"/> <mvc:mapping path="/TemplateMsg/TemplateSendMsg"/> <mvc:mapping path="/TemplateMsg/updataPTID"/> <mvc:mapping path="/TemplateMsg/deleteMB"/> <mvc:mapping path="/ThirdData/getdata"/> <mvc:mapping path="/ThirdData/updata"/> <mvc:mapping path="/setMoney/setMoneyList"/> <mvc:mapping path="/setMoney/setArriveMoney"/> <mvc:mapping path="/setMoney/checkfileCert"/> <mvc:mapping path="/setMoney/SetMoneyType"/> <mvc:mapping path="/user/userlists"/> <mvc:mapping path="/user/uOpenId"/> <mvc:mapping path="/visitor/theAlmostMoon"/> <mvc:mapping path="/visitor/SixAlmostMoon"/> <mvc:mapping path="/visitor/tops"/> <mvc:mapping path="/weixin/REFUND"/> <bean class="com.bls.mp.interceptor.AuthInterceptor"></bean> </mvc:interceptor> </mvc:interceptors> <task:annotation-driven/> <!-- 配置访问静态文件 --> <mvc:default-servlet-handler/> <mvc:resources location="/images/" mapping="/images/**"/> <mvc:resources location="/WEB-INF/js/" mapping="/js/**"/> <mvc:resources location="/WEB-INF/resources/jsp/" mapping="/jsp/**"/> <mvc:resources location="/WEB-INF/resources/css/" mapping="/css/**"/> </beans> ``` ## 此处为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-redis.xml,classpath:spring-mybatis.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> <filter> <filter-name>CORSFilter</filter-name> <filter-class>com.bls.mp.common.MyFilter</filter-class> <init-param> <param-name>excludedPages</param-name> <param-value>/UserAuthServlet</param-value> </init-param> </filter> <filter-mapping> <filter-name>CORSFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <listener> <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class> </listener> <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> <url-pattern>/</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>/index.jsp</welcome-file> </welcome-file-list> </web-app> ``` ## 此处为tomcat 配置 ``` <Server port="8005" shutdown="SHUTDOWN"> <Listener className="org.apache.catalina.startup.VersionLoggerListener" /> <Listener SSLEngine="on" className="org.apache.catalina.core.AprLifecycleListener" /> <Listener className="org.apache.catalina.core.JreMemoryLeakPreventionListener" /> <Listener className="org.apache.catalina.mbeans.GlobalResourcesLifecycleListener" /> <Listener className="org.apache.catalina.core.ThreadLocalLeakPreventionListener" /> <GlobalNamingResources> <Resource auth="Container" description="User database that can be updated and saved" factory="org.apache.catalina.users.MemoryUserDatabaseFactory" name="UserDatabase" pathname="conf/tomcat-users.xml" type="org.apache.catalina.UserDatabase" /> </GlobalNamingResources> <Service name="Catalina"> <Connector connectionTimeout="20000" maxPostSize="0" port="8080" protocol="HTTP/1.1" redirectPort="8443" /> <Connector maxPostSize="0" port="8009" protocol="AJP/1.3" redirectPort="8443" /> <Engine defaultHost="localhost" name="Catalina"> <Realm className="org.apache.catalina.realm.LockOutRealm"> <Realm className="org.apache.catalina.realm.UserDatabaseRealm" resourceName="UserDatabase" /> </Realm> <Host autoDeploy="true" name="yuming.cn" appBase="" unpackWARs="true" xmlNamespaceAware="false" xmlValidation="false"> <Context crossContext="true" docBase="/www/server/tomcat/webapps/xiangmu" path="" reloadable="true" /> </Host> </Engine> </Service> </Server> ``` ## spring-radis.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:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> <context:property-placeholder location="classpath:*.properties"/> <!--设置数据池--> <bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig"> <property name="maxIdle" value="${redis.maxIdle}"></property> <property name="minIdle" value="${redis.minIdle}"></property> <property name="maxTotal" value="${redis.maxTotal}"></property> <property name="maxWaitMillis" value="${redis.maxWaitMillis}"></property> <property name="testOnBorrow" value="${redis.testOnBorrow}"></property> </bean> <!--链接redis--> <bean id="connectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"> <property name="hostName" value="${redis.host}"></property> <property name="port" value="${redis.port}"></property> <property name="password" value="${redis.password}"></property> <property name="poolConfig" ref="poolConfig"></property> </bean> <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate" p:connection-factory-ref="connectionFactory" > <!--以下针对各种数据进行序列化方式的选择--> <property name="keySerializer"> <bean class="org.springframework.data.redis.serializer.StringRedisSerializer" /> </property> <property name="valueSerializer"> <bean class="org.springframework.data.redis.serializer.StringRedisSerializer" /> </property> <property name="hashKeySerializer"> <bean class="org.springframework.data.redis.serializer.StringRedisSerializer" /> </property> <!--<property name="hashValueSerializer"> <bean class="org.springframework.data.redis.serializer.StringRedisSerializer" /> </property>--> </bean> </beans> ```
java ssm框架service接口无法注入的问题
错误信息:No qualifying bean of type 'com.ztech.gudong.service.IGDGuDongService' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)} Controller: ![图片说明](https://img-ask.csdn.net/upload/201710/23/1508742997_14680.png) 项目结构: ![图片说明](https://img-ask.csdn.net/upload/201710/23/1508743019_709169.png) ``` <?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.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd"> <!-- 自动扫描该包,使SpringMVC认为包下用了@controller注解的类是控制器 --> <context:component-scan base-package="com.ztech.gudong.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="/WEB-INF/jsp/" /> <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="10485760000" /> <!-- 内存中的最大值 --> <property name="maxInMemorySize" value="40960" /> </bean> </beans> ``` <?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.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd"> <!-- 自动扫描 --> <context:component-scan base-package="com.ztech.gudong"> </context:component-scan> <!-- 引入配置文件 --> <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="location" value="classpath:jdbc.properties" /> </bean> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="${jdbc.driver}" /> <property name="url" value="${jdbc.url}" /> <property name="username" value="${jdbc.username}" /> <property name="password" value="${jdbc.password}" /> <!-- 初始化连接大小 --> <property name="initialSize" value="${initialSize}"></property> <!-- 连接池最大数量 --> <property name="maxActive" value="${jdbc.pool.maxActive}"></property> <!-- 连接池最大空闲 --> <property name="maxIdle" value="${maxIdle}"></property> <!-- 连接池最小空闲 --> <property name="minIdle" value="${jdbc.pool.minIdle}"></property> <!-- 获取连接最大等待时间 --> <property name="maxWait" value="${maxWait}"></property> </bean> <!-- spring和MyBatis完美整合,不需要mybatis的配置映射文件 --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <!-- 自动扫描mapping.xml文件 --> <property name="mapperLocations" value="classpath:com/ztech/gudong/mapper/*.xml"></property> </bean> <!-- DAO接口所在包名,Spring会自动查找其下的类 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.ztech.gudong.dao" /> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property> </bean> <!-- (事务管理)transaction manager, use JtaTransactionManager for global tx --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean> </beans>
关于websocket在spring项目握手失败的问题
用java实现的websocket 我在不适用其他框架的时候可以正常握手访问 但是最近加在一个适用spring的项目中,一直握手不成功,这是什么原因? 以下是浏览器返回的信息 ``` Request URL:ws://127.0.0.1:8080/springDemo/websocket/roomName/roomId Request Method:GET Status Code:404 Not Found Response Headers (5) Request Headers view source Accept-Encoding:gzip, deflate, sdch Accept-Language:zh-CN,zh;q=0.8 Cache-Control:no-cache Connection:Upgrade Cookie:JSESSIONID=1FF3C077231B22FAE14E6CCD5E68FBF6 Host:127.0.0.1:8080 Origin:http://127.0.0.1:8080 Pragma:no-cache Sec-WebSocket-Extensions:permessage-deflate; client_max_window_bits Sec-WebSocket-Key:pUvNNKdq1RM3Sl7F0+rIIw== Sec-WebSocket-Version:13 Upgrade:websocket User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36 ``` 我spring配置信息是这样的 ``` <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="location" value="classpath:jdbcOracle.properties" /> </bean> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="driverClass" value="${jdbc.driver}" /> <property name="jdbcUrl" value="${jdbc.url}" /> <property name="user" value="${jdbc.username}" /> <property name="password" value="${jdbc.password}" /> <property name="autoCommitOnClose" value="true" /> <property name="checkoutTimeout" value="${cpool.checkoutTimeout}" /> <property name="initialPoolSize" value="${cpool.minPoolSize}" /> <property name="minPoolSize" value="${cpool.minPoolSize}" /> <property name="maxPoolSize" value="${cpool.maxPoolSize}" /> <property name="maxIdleTime" value="${cpool.maxIdleTime}" /> <property name="acquireIncrement" value="${cpool.acquireIncrement}" /> </bean> <!-- 数据库 事务管理器 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean> <!-- 创建SqlSessionFactory,同时指定数据源 --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource"/> <!-- 自动扫描mapping.xml文件 --> <property name="mapperLocations" > <list> <value>classpath*:com/bs/gpms/**/mapper/*.xml</value> <value>classpath*:com/bs/basic/base/dao/*.xml</value> </list> </property> </bean> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="annotationClass" value="org.springframework.stereotype.Repository"/> <property name="basePackage" value="com.bs.gpms"/> </bean> <!-- <bean id="lobHandler" class="org.springframework.jdbc.support.lob.DefaultLobHandler" /> <bean id="sqlMapClient" class="org.springframework.orm.ibatis.SqlMapClientFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="configLocation" value="classpath:SqlMapConfig.xml" /> <property name="lobHandler" ref="lobHandler" /> </bean> --> <!-- 基于注释的事务,当注释中发现@Transactional时,使用id为“transactionManager”的事务管理器 --> <!-- 如果没有设置transaction-manager的值,则spring以缺省默认的事务管理器来处理事务,默认事务管理器为第一个加载的事务管理器 --> <tx:annotation-driven transaction-manager="transactionManager"/> <!-- <bean id="sqlMapClientTemplate" class="org.springframework.orm.ibatis.SqlMapClientTemplate"> <property name="sqlMapClient" ref="sqlMapClient" /> </bean> --> <mvc:annotation-driven> <mvc:message-converters> <bean class="org.springframework.http.converter.StringHttpMessageConverter"> <property name="supportedMediaTypes"> <list> <value>application/json;charset=UTF-8</value> </list> </property> </bean> </mvc:message-converters> </mvc:annotation-driven> <context:annotation-config /> <context:component-scan base-package="com.*" /> <bean id="viewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver"> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" /> <property name="prefix" value="/" /> <property name="suffix" value=".jsp" /> </bean> ``` 一直找不到问题,因为这是旧项目,也没办法更新到spring4
ssm 报错:org.springframework.context.annotation.internalAsyncAnnotationProcessor
# ssm 框架 在本地完美运行放到Linux服务器报错 以下内容 Error creating bean with name '**org.springframework.context.annotation.internalAsyncAnnotationProcessor'**: Initialization of bean failed; nested exception is java.lang.NoSuchMethodError: org.springframework.aop.interceptor.AsyncExecutionInterceptor.<init>(Ljava/util/concurrent/Executor;Lorg/springframework/aop/interceptor/AsyncUncaughtExceptionHandler;)V ## 之前是没有加 redis,没有发现问题,这次我加了redis然后就报错,大神们帮忙看看解决解决 这是spring-mvc配置: ``` ==============spring-mvc===================== <?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" xmlns:task="http://www.springframework.org/schema/task" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.0.xsd" > <!-- 自动扫描该包,使SpringMVC认为包下用了@controller注解的类是控制器 --> <mvc:annotation-driven/> <context:component-scan base-package="com.bls.mp.*"/> <!--避免IE执行AJAX时,返回JSON出现下载文件 --> <bean id="mappingJacksonHttpMessageConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"> <property name="supportedMediaTypes"> <list> <value>text/html;charset=UTF-8</value> </list> </property> </bean> <bean class="com.bls.mp.common.SpringTool"/> <!-- 启动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="/WEB-INF/resources/jsp/" /> <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="10485760000" /> <!-- 内存中的最大值 --> <property name="maxInMemorySize" value="40960" /> </bean> <!-- 全局异常处理器 --> <bean class="com.bls.mp.common.exception.CustomExceptionResolver"></bean> <mvc:annotation-driven/> <!-- 拦截器配置 --> <mvc:interceptors> <mvc:interceptor> <mvc:mapping path="/setadmin"/> <!--<mvc:mapping path="/user/userList"/> --> <mvc:mapping path="/Blocker"/> <mvc:mapping path="/grouponteam/grouponRanking"/> <mvc:mapping path="/grouponteam/arriverTime"/> <mvc:mapping path="/grouponteam/paging"/> <mvc:mapping path="/grouponteam/conditionGrouponT"/> <mvc:mapping path="/hospital/hospitalInfo"/> <mvc:mapping path="/hospital/setting"/> <mvc:mapping path="/hospital/orderdetails"/> <mvc:mapping path="/grouponteam/grouponTeamCountAndMoney"/> <mvc:mapping path="/grouponteam/OrderRefundList"/> <mvc:mapping path="/grouponteam/orderdetails"/> <mvc:mapping path="/grouponteam/paging"/> <mvc:mapping path="/grouponteam/conditionGrouponT"/> <mvc:mapping path="/grouponteam/grouponRanking"/> <mvc:mapping path="/grouponteam/arriverTime"/> <mvc:mapping path="/grouponteam/grouponTeamCountAndMoney"/> <mvc:mapping path="/imguoload"/> <mvc:mapping path="/imguoloads"/> <mvc:mapping path="/uploadFile"/> <mvc:mapping path="/uploadCenter"/> <mvc:mapping path="/onTheShelves"/> <mvc:mapping path="/updateTheRecommended"/> <mvc:mapping path="/deleteByGoods"/> <mvc:mapping path="/restoreGoods"/> <mvc:mapping path="/goods/goodslist"/> <mvc:mapping path="/goods/hasBeenOn"/> <mvc:mapping path="/goods/NotOn"/> <mvc:mapping path="/goods/RecycleBin"/> <mvc:mapping path="/goods/searchName"/> <mvc:mapping path="/goods/goodsdiy"/> <mvc:mapping path="/upload/uploadFile"/> <mvc:mapping path="/CreateClassImg"/> <mvc:mapping path="/imglist"/> <mvc:mapping path="/up_img"/> <mvc:mapping path="/moveImg"/> <mvc:mapping path="/deleteImg"/> <mvc:mapping path="/template/templateURL"/> <mvc:mapping path="/template/templateParentAll"/> <mvc:mapping path="/template/templatAll"/> <mvc:mapping path="/template/changeT"/> <mvc:mapping path="/template/deleteT"/> <mvc:mapping path="/TemplateMsg/addTemplateMsg"/> <mvc:mapping path="/TemplateMsg/templateMsgList"/> <mvc:mapping path="/TemplateMsg/templateSendlist"/> <mvc:mapping path="/TemplateMsg/TemplateSendMsg"/> <mvc:mapping path="/TemplateMsg/updataPTID"/> <mvc:mapping path="/TemplateMsg/deleteMB"/> <mvc:mapping path="/ThirdData/getdata"/> <mvc:mapping path="/ThirdData/updata"/> <mvc:mapping path="/setMoney/setMoneyList"/> <mvc:mapping path="/setMoney/setArriveMoney"/> <mvc:mapping path="/setMoney/checkfileCert"/> <mvc:mapping path="/setMoney/SetMoneyType"/> <mvc:mapping path="/user/userlists"/> <mvc:mapping path="/user/uOpenId"/> <mvc:mapping path="/visitor/theAlmostMoon"/> <mvc:mapping path="/visitor/SixAlmostMoon"/> <mvc:mapping path="/visitor/tops"/> <mvc:mapping path="/weixin/REFUND"/> <bean class="com.bls.mp.interceptor.AuthInterceptor"></bean> </mvc:interceptor> </mvc:interceptors> <task:annotation-driven/> <!-- 配置访问静态文件 --> <mvc:default-servlet-handler/> <mvc:resources location="/images/" mapping="/images/**"/> <mvc:resources location="/WEB-INF/js/" mapping="/js/**"/> <mvc:resources location="/WEB-INF/resources/jsp/" mapping="/jsp/**"/> <mvc:resources location="/WEB-INF/resources/css/" mapping="/css/**"/> </beans> ``` 这是 web.xml ``` ==============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-mybatis.xml</param-value> <param-value>classpath:spring-redis.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> <filter> <filter-name>CORSFilter</filter-name> <filter-class>com.bls.mp.common.MyFilter</filter-class> <init-param> <param-name>excludedPages</param-name> <param-value>/UserAuthServlet</param-value> </init-param> </filter> <filter-mapping> <filter-name>CORSFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <listener> <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class> </listener> <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> <url-pattern>/</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>/index.jsp</welcome-file> </welcome-file-list> </web-app> ``` 这是spring-mybatis.xml 配置 ``` ==============spring-mybatis.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: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-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd"> <!-- 自动扫描 --> <context:component-scan base-package="com.bls.mp"/> <!-- 引入配置文件 --> <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="location" value="classpath:jdbc.properties" /> </bean> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="${jdbc.driver}" /> <property name="url" value="${jdbc.url}" /> <property name="username" value="${jdbc.username}" /> <property name="password" value="${jdbc.password}" /> <!-- 初始化连接大小 --> <property name="initialSize" value="${initialSize}"></property> <!-- 连接池最大数量 --> <property name="maxActive" value="${maxActive}"></property> <!-- 连接池最大空闲 --> <property name="maxIdle" value="${maxIdle}"></property> <!-- 连接池最小空闲 --> <property name="minIdle" value="${minIdle}"></property> <!-- 获取连接最大等待时间 --> <property name="maxWait" value="${maxWait}"></property> </bean> <!-- spring和MyBatis完美整合,不需要mybatis的配置映射文件 --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <!-- 自动扫描mapping.xml文件 --> <property name="mapperLocations" value="classpath:com/bls/mp/mapping/*.xml"></property> </bean> <!-- DAO接口所在包名,Spring会自动查找其下的类 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.bls.mp.dao" /> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property> </bean> <!-- (事务管理)transaction manager, use JtaTransactionManager for global tx --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean> </beans> ``` 这是spring-redis.xml配置 ``` ===================spring-redis.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:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> <context:property-placeholder location="classpath:*.properties"/> <!--设置数据池--> <bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig"> <property name="maxIdle" value="${redis.maxIdle}"></property> <property name="minIdle" value="${redis.minIdle}"></property> <property name="maxTotal" value="${redis.maxTotal}"></property> <property name="maxWaitMillis" value="${redis.maxWaitMillis}"></property> <property name="testOnBorrow" value="${redis.testOnBorrow}"></property> </bean> <!--链接redis--> <bean id="connectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"> <property name="hostName" value="${redis.host}"></property> <property name="port" value="${redis.port}"></property> <property name="password" value="${redis.password}"></property> <property name="timeout" value="${redis.timeout}"></property> <property name="poolConfig" ref="poolConfig"></property> </bean> <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate" p:connection-factory-ref="connectionFactory" > <!--以下针对各种数据进行序列化方式的选择--> <property name="keySerializer"> <bean class="org.springframework.data.redis.serializer.StringRedisSerializer" /> </property> <property name="valueSerializer"> <bean class="org.springframework.data.redis.serializer.StringRedisSerializer" /> </property> <property name="hashKeySerializer"> <bean class="org.springframework.data.redis.serializer.StringRedisSerializer" /> </property> <!--<property name="hashValueSerializer"> <bean class="org.springframework.data.redis.serializer.StringRedisSerializer" /> </property>--> </bean> </beans> ```
刚搭的ssm框架,不能直接通过url访问WEB-INF下的html
如下图,我不能直接通过地址栏的url去访问HTML页面. ![图片说明](https://img-ask.csdn.net/upload/201708/09/1502243574_813631.png) 以下是我的配置: # 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> <!-- Spring和mybatis的配置文件 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring-mybatis.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> <!-- 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> </web-app> # spring-mybatis.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:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="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 http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd "> <!-- <context:annotation-config /> --> <!-- 自动扫描 --> <!-- <context:component-scan base-package="com.lizhm" /> --> <context:component-scan base-package="**.*.services"/> <!-- 引入配置文件 --> <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="location" value="classpath:jdbc.properties" /> </bean> <bean id="dataSource" 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}" /> <!-- 初始化连接大小 --> <property name="initialSize" value="${initialSize}"></property> <!-- 连接池最大数量 --> <property name="maxActive" value="${maxActive}"></property> <!-- 连接池最大空闲 --> <property name="maxIdle" value="${maxIdle}"></property> <!-- 连接池最小空闲 --> <property name="minIdle" value="${minIdle}"></property> <!-- 获取连接最大等待时间 --> <property name="maxWait" value="${maxWait}"></property> </bean> <!-- spring和MyBatis完美整合,不需要mybatis的配置映射文件 --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <!-- 自动扫描mapping.xml文件 --> <property name="mapperLocations" value="classpath*:/**/*Mapper.xml"></property> </bean> <!-- DAO(services)接口所在包名,Spring会自动查找其下的类 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="**.*.mapper" /> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property> </bean> <!-- (事务管理)transaction manager, use JtaTransactionManager for global tx --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean> <!-- 配置基于注解的声明式事务 --> <tx:annotation-driven transaction-manager="transactionManager"></tx:annotation-driven> </beans> # spring-mvc.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: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.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd"> <context:annotation-config/> <!-- 自动扫描该包,使SpringMVC认为包下用了@controller注解的类是控制器 --> <context:component-scan base-package="**.*.controllers" /> <!--避免IE执行AJAX时,返回JSON出现下载文件 --> <bean id="mappingJacksonHttpMessageConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"> <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> <!-- 配置SpringMVC --> <!-- 1.开启SpringMVC注解模式 --> <!-- 简化配置: (1)自动注册DefaultAnootationHandlerMapping,AnotationMethodHandlerAdapter (2)提供一些列:数据绑定,数字和日期的format @NumberFormat, @DateTimeFormat, xml,json默认读写支持 --> <mvc:annotation-driven/> <!-- 2.静态资源默认servlet配置 (1)加入对静态资源的处理:js,gif,png (2)允许使用"/"做整体映射 --> <mvc:default-servlet-handler/> <!-- <mvc:resources mapping="/lib/**" location="/lib/" /> --> <mvc:resources mapping="/resources/**" location="/resources/" /> <!-- <mvc:resources mapping="/WEB-INF/view/**" location="/WEB-INF/view/" /> --> <!-- 定义跳转的文件的前后缀 ,视图模式配置--> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <!-- <bean class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver"> --> <!-- 这里的配置我的理解是自动给后面action的方法return的字符串加上前缀和后缀,变成一个 可用的url地址 --> <property name="prefix" value="/WEB-INF/view/" /> <property name="suffix" value=".html" /> </bean> <!-- 配置文件上传,如果没有使用文件上传可以不用配置,当然如果不配,那么配置文件中也不必引入上传组件包 --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!-- 默认编码 --> <property name="defaultEncoding" value="utf-8" /> <!-- 文件大小最大值 --> <property name="maxUploadSize" value="10485760000" /> <!-- 内存中的最大值 --> <property name="maxInMemorySize" value="40960" /> </bean> </beans>
IDEA做SSM框架整合时,出现无法加载mapper,导致无法注入。
今日学习SSM框架整合,整合以后,单独用测试类可以连接成功连接数据库,可是一加入MVC用TOMCAT启动,项目就会报错,错误内容为:Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)} 以下为项目各部分截图,有没有大佬帮我分析下,问题到底出在哪? ========================================================================================================================================== ![项目报错详细情况](https://img-ask.csdn.net/upload/201908/15/1565880941_652575.png) ## 项目报错详细情况 ![spring配置文件已经配置了mapper.xml路径和齐对应的接口扫描包](https://img-ask.csdn.net/upload/201908/15/1565880955_958792.png) ## spring配置文件已经配置了mapper.xml路径和齐对应的接口扫描包 ![编译文件夹target里已经编译出了mapper相关配置文件及接口类](https://img-ask.csdn.net/upload/201908/15/1565881099_526884.png) ## 编译文件夹target里已经编译出了mapper相关配置文件及接口类 ![mapper.xml里的namespace已经指明了接口路径](https://img-ask.csdn.net/upload/201908/15/1565881139_161198.png) ## mapper.xml里的namespace已经指明了接口路径 ![pom文件里也配置了resource源](https://img-ask.csdn.net/upload/201908/15/1565881159_416309.png) ## pom文件里也配置了resource源 ========================================================================================================================================== # 详细代码已经贴在下方,只选了几个配置文件及mapper接口类,service及controller应该没关系就没传! ============================================= # 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> <!--添加缓存 引入第三方二级缓存 --> <settings> <setting name="mapUnderscoreToCamelCase" value="true"/> <setting name="cacheEnabled" value="false"/> </settings> <!-- 配置数据源 default默认使用的数据源 --> <environments default="mysql"> <environment id="mysql"> <transactionManager type="JDBC" /> <dataSource type="POOLED"> <property name="driverClassName" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql:///orderuser"/> <property name="username" value="zhijia3278"/> <property name="password" value="0528"/> </dataSource> </environment> </environments> <!-- 映射文件 --> <mappers> <mapper resource="OrderUserMapper.xml"/> </mappers> </configuration> ``` # OrderUserMapper.java ``` package cn.tedu.mapper; import cn.tedu.domain.Order; import cn.tedu.domain.User; public interface OrderUserMapper { public User queryUser(String userId); public Order queryOrder(String orderId); public void updateUserPoints(User user); } ``` # OrderUserMapper.xml ``` <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="cn.tedu.mapper.OrderUserMapper"> <select id="queryUser" parameterType="String" resultType="User"> select * from t_user where user_id=#{userId} </select> <select id="queryOrder" parameterType="String" resultType="Order"> select * from t_order where order_id=#{orderId} </select> <update id="updateUserPoints" parameterType="User"> update t_user set points=#{points} where user_id=#{userId} </update> </mapper> ``` # spring.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" xmlns:p="http://www.springframework.org/schema/p" xmlns:util="http://www.springframework.org/schema/util" 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/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.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"> <!-- 配置内容 --> <context:component-scan base-package="cn.tedu"> </context:component-scan> <context:annotation-config></context:annotation-config> <!-- 持久层数据源 --> <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"> <!-- 4个属性 --> <property name="driverClassName" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql:///orderuser"/> <property name="username" value="zhijia3278"/> <property name="password" value="0528"/> </bean> <!-- sqlSession --> <bean id="sqlSession" class="org.mybatis.spring.SqlSessionFactoryBean"> <!-- 数据源注入 --> <property name="dataSource" ref="dataSource"/> <!-- 扫描mybatis的独立配置文件 关闭二级缓存,驼峰命名 --> <property name="configLocation" value="classpath:mybatis/mybatis-config.xml"/> <!-- 映射文件扫描 --> <property name="mapperLocations" value="classpath:mapper/OrderUserMapper.xml" /> <!-- 别名包 --> <property name="typeAliasesPackage" value="cn.tedu.domain"></property> </bean> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <!-- 扫描的接口包 cn.tedu.mapper --> <property name="basePackage" value="cn.tedu.mapper"/> </bean> <!-- 注解驱动开启,@RequestMapping @RequestParam等 --> <mvc:annotation-driven/> <!-- 防止静态文件js css html访问被dispacherServlet拦截 --> <!-- localhost静态文件根目录 /static /js /css --> <!-- mapping 满足什么样子的访问地址 http://localhost:8080/js//1.js --> <mvc:resources location="/" mapping="/**"></mvc:resources> </beans> ``` # springmvc-servlet ``` <?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" xmlns:p="http://www.springframework.org/schema/p" xmlns:util="http://www.springframework.org/schema/util" 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/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.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"> <!-- 配置内容 --> <context:component-scan base-package="cn.tedu"/> <!-- 注解驱动开启,@RequestMapping @RequestParam等 --> <mvc:annotation-driven/> <!-- 防止静态文件js css html访问被dispacherServlet拦截 --> <!-- localhost静态文件根目录 /static /js /css --> <!-- mapping 满足什么样子的访问地址 http://localhost:8080/js//1.js --> <mvc:resources location="/" mapping="/**"></mvc:resources> </beans> ``` # 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> <display-name>Archetype Created Web Application</display-name> <servlet> <servlet-name>springmvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!-- tomcat启动加载spring.xml --> <!-- <init-param>--> <!-- <param-name>contextConfigLocation</param-name>--> <!-- <param-value>classpath:springmvc/springmvc-servlet.xml</param-value>--> <!-- </init-param>--> </servlet> <servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app> ``` # pom.xml ``` <?xml version="1.0" encoding="UTF-8"?> <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/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>cn.tedu</groupId> <artifactId>SSMDemo</artifactId> <version>1.0-SNAPSHOT</version> <packaging>war</packaging> <name>SSM-DEMO01 Maven Webapp</name> <url>http://maven.apache.org</url> <dependencies> <!-- <dependency>--> <!-- <groupId>junit</groupId>--> <!-- <artifactId>junit</artifactId>--> <!-- <version>4.12</version>--> <!-- <scope>compile</scope>--> <!-- </dependency>--> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>4.3.13.RELEASE</version> </dependency> <!-- datasource --> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.0.14</version> </dependency> <!-- spring mysql --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>4.3.13.RELEASE</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.0.8</version> </dependency> <!-- mybatis --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.4.5</version> </dependency> <!-- spring mybatis --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.3.1</version> </dependency> <!-- springmvc --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>4.3.13.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>4.3.13.RELEASE</version> </dependency> <!-- jackson --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>2.8.8</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>2.8.8</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.8.8</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> <scope>provided</scope> </dependency> </dependencies> <build> <finalName>SSM-DEMO01</finalName> <plugins> <plugin> <groupId>org.apache.tomcat.maven</groupId> <artifactId>tomcat7-maven-plugin</artifactId> <version>2.2</version> <!-- 插件属性配置 --> <configuration> <!-- 端口 --> <port>8080</port> <!-- 项目访问路径 --> <path>/</path> <!-- 编解码 --> <uriEncoding>utf-8</uriEncoding> <useBodyEncodingForURI>true</useBodyEncodingForURI> </configuration> </plugin> </plugins> <resources> <resource> <directory>resource</directory> <includes> <include>**/*.xml</include> <include>mapper/*.xml</include> <include>mybatis/*.xml</include> <include>spring/*.xml</include> </includes> <!-- <filtering>true</filtering>--> </resource> </resources> </build> </project> ```
SSM框架关于js和css及静态资源无法加载问题
创建了一个ssm框架的项目,但是在运行的时候,出现了一个bug,就是在运行的时候js,css,以及一些静态资源被拦截,无法加载; web中的配置如下: <?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_2_5.xsd" id="taotao" version="2.5"> <welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file>index.htm</welcome-file> <welcome-file>index.jsp</welcome-file> <welcome-file>default.html</welcome-file> <welcome-file>default.htm</welcome-file> <welcome-file>default.jsp</welcome-file> </welcome-file-list> <!-- 加载spring容器 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring/applicationContext-*.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- springmvc的前端控制器 --> <servlet> <servlet-name>mvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!-- contextConfigLocation不是必须的, 如果不配置contextConfigLocation, springmvc的配置文件默认在:WEB-INF/servlet的name+"-servlet.xml" --> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring/springmvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <!-- 解决post乱码 --> <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> </filter> <filter-mapping> <filter-name>CharacterEncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <servlet-mapping> <servlet-name>mvc</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app> spring mvc中的配置如下: <mvc:annotation-driven/> <!--包扫描器 --> <context:component-scan base-package="com.ny.controller" /> <!--视图解析器 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/jsp/" /> <property name="suffix" value=".jsp" /> </bean> <!--配置静态资源映射,防止静态资源被拦截 --> <mvc:resources location="/WEB-INF/css/" mapping="/css/**"></mvc:resources> <mvc:resources location="/WEB-INF/js/" mapping="/js/**"></mvc:resources> <mvc:resources location="/WEB-INF/images/" mapping="/images/**"/> <mvc:resources location="/WEB-INF/lay/" mapping="/lay/**"/> <mvc:resources location="/WEB-INF/font/" mapping="/font/**"/> </beans> 配置在Tomcat插件运行时没有错误,但是在本地的Tomcat运行的时候,抛出如下信息: DEBUG [http-bio-8080-exec-3] - DispatcherServlet with name 'mvc' processing GET request for [/School/baoming] DEBUG [http-bio-8080-exec-3] - Looking up handler method for path /baoming DEBUG [http-bio-8080-exec-3] - Returning handler method [private java.lang.String com.ny.controller.BaomingController.transfer()] DEBUG [http-bio-8080-exec-3] - Returning cached instance of singleton bean 'baomingController' DEBUG [http-bio-8080-exec-3] - Last-Modified value for [/School/baoming] is: -1 DEBUG [http-bio-8080-exec-3] - Rendering view [org.springframework.web.servlet.view.JstlView: name 'baoming'; URL [/WEB-INF/jsp/baoming.jsp]] in DispatcherServlet with name 'mvc' DEBUG [http-bio-8080-exec-3] - Forwarding to resource [/WEB-INF/jsp/baoming.jsp] in InternalResourceView 'baoming' DEBUG [http-bio-8080-exec-3] - Successfully completed request 想问下各位哪错了??
SSM框架中,怎么通过controller实现页面的跳转?
今天接触SSM框架的第四天,后台Mybatis生成dao、entity和mapper后,测试成功,能够正常读写数据库了,但是,在加入页面之后,通过controller不能实现页面的跳转,特求助~~ 访问情况: ![图片说明](https://img-ask.csdn.net/upload/201811/27/1543304296_872148.png) 点击跳转后, ![图片说明](https://img-ask.csdn.net/upload/201811/27/1543304328_484707.png) 出现404的错误,个人认为,可能是没有找到controller 代码: messageController.java ``` @Controller public class messageController { @RequestMapping("/message/go") public String gotest(){ return "second"; } } ``` index.jsp ``` <%@page contentType="text/html; charset=UTF-8" language="java" %> <html> <head> <title>首页</title> </head> <body> <h2>Hello World!</h2> <a href="/message/go">点击跳转</a> <p id="test">Hello World!</p> <button type="button" onclick="selectUser()">onclick test</button> </body> </html> ``` reach.jsp ``` <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>跳到这里了</title> </head> <body> 跳转成功!!! </body> </html> ``` 文件路径: ![图片说明](https://img-ask.csdn.net/upload/201811/27/1543304458_62372.png) SpringMVC的配置 ``` <?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:beans="http://www.springframework.org/schema/beans" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd"> <!-- ①:top.xiaofeng包中的所有类进行扫描,以完成Bean创建和自动依赖注入的功能 --> <context:component-scan base-package="top.xiaofeng"/> <mvc:annotation-driven/> <!-- 静态资源访问 --> <!--如果webapp下你新建了文件夹,想访问里面的静态资源,那么就要在这配置一下--> <mvc:resources location="/img/" mapping="/img/**"/> <mvc:resources location="/css/" mapping="/css/**"/> <mvc:resources location="/js/" mapping="/js/**"/> <!-- ②:启动Spring MVC的注解功能,完成请求和注解POJO的映射 --> <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> <property name="messageConverters"> <list> <ref bean="mappingJacksonHttpMessageConverter"/> </list> </property> </bean> <bean id="mappingJacksonHttpMessageConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"> <property name="supportedMediaTypes"> <list> <value>application/json;charset=UTF-8</value> </list> </property> </bean> <!-- 配置视图解析器,把控制器的逻辑视频映射为真正的视图 --> <!-- /WEB-INF/views/second.jsp --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/> <property name="prefix" value="/views/"/> <property name="suffix" value=".jsp"/> </bean> <!-- 拦截器 --> <mvc:interceptors> <!-- 国际化操作拦截器 如果采用基于(请求/Session/Cookie)则必需配置 --> <bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor"/> </mvc:interceptors> <!-- 定义无Controller的path<->view直接映射 --> <!-- <mvc:view-controller path="/" view-name="redirect:/" /> --> </beans> ``` 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>mydemo</display-name> <!-- 配置编码方式--> <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> <!-- 配置springmvc的前端控制器 指向spring-mvc.xml 程序在启动的时候就加载springmvc 可以接受所有请求 load-on-startup:表示启动容器时初始化该Servlet; --> <servlet> <servlet-name>springServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!-- 可以自定义servlet.xml配置文件的位置和名称, 默认为WEB-INF目录下,名称为[<servlet-name>]-servlet.xml,如spring-servlet.xml --> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring/spring-mvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <!-- 将前端URL请求和后台处理方法controller建立对应关系--> <servlet-mapping> <servlet-name>springServlet</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <!-- 取消对某一类文件的拦截--> <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>*.md</url-pattern> </servlet-mapping> <!-- Spring配置 --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring/applicationContext.xml</param-value> </context-param> <!-- 欢迎页面--> <welcome-file-list> <welcome-file>/index.jsp</welcome-file> </welcome-file-list> <!--&lt;!&ndash;404错误展示页面&ndash;&gt;--> <!--<error-page>--> <!--<error-code>404</error-code>--> <!--<location>/404.jsp</location>--> <!--</error-page>--> <!--设置session失效时间为30分钟 --> <session-config> <session-timeout>600</session-timeout> </session-config> </web-app> ```
关于sping-security的Access is denied问题
编译时没问题,但是刚进到网页的时候就会报Access is denied,但是却不妨碍登陆,登陆进去查询,添加都能完成,求各位大神指点! **这是一个ssm整合的项目** 日志 ``` org.springframework.security.access.AccessDeniedException: Access is denied at org.springframework.security.access.vote.AffirmativeBased.decide(AffirmativeBased.java:84) at org.springframework.security.access.intercept.AbstractSecurityInterceptor.beforeInvocation(AbstractSecurityInterceptor.java:233) at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:124) at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:91) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:119) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:137) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:111) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:170) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:63) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) at org.springframework.security.web.authentication.www.BasicAuthenticationFilter.doFilterInternal(BasicAuthenticationFilter.java:158) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:200) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:116) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:64) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:56) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:105) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:215) at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:178) at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:357) at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:270) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210) at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:200) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123) at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100) at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408) at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1041) at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:603) at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) at java.lang.Thread.run(Thread.java:748) ``` sping-security.xml配置文件 ``` <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:security="http://www.springframework.org/schema/security" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security.xsd"> <!-- 配置不拦截的资源 --> <security:http pattern="/login.jsp" security="none"/> <security:http pattern="/failer.jsp" security="none"/> <security:http pattern="/css/**" security="none"/> <security:http pattern="/img/**" security="none"/> <security:http pattern="/plugins/**" security="none"/> <!-- 配置具体的规则 auto-config="true" 不用自己编写登录的页面,框架提供默认登录页面 use-expressions="false" 是否使用SPEL表达式(没学习过) --> <security:http auto-config="true" use-expressions="false"> <!-- 配置具体的拦截的规则 pattern="请求路径的规则" access="访问系统的人,必须有ROLE_USER的角色" --> <security:intercept-url pattern="/**" access="ROLE_USER,ROLE_ADMIN"/> <!-- 定义跳转的具体的页面 --> <security:form-login login-page="/login.jsp" login-processing-url="/login.do" default-target-url="/index.jsp" authentication-failure-url="/failer.jsp" authentication-success-forward-url="/pages/main.jsp" /> <!-- 关闭跨域请求 --> <security:csrf disabled="true"/> <!-- 退出 --> <security:logout invalidate-session="true" logout-url="/logout.do" logout-success-url="/login.jsp" /> </security:http> <!-- 切换成数据库中的用户名和密码 --> <security:authentication-manager> <security:authentication-provider user-service-ref="userService"> <!--配置加密的方式--> <!--<security:password-encoder ref="passwordEncoder"/>--> </security:authentication-provider> </security:authentication-manager> <!-- 配置加密类 --> <bean id="passwordEncoder" class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder"/> </beans> ``` ``` @Override public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException { UserInfo userInfo = null; try { userInfo = userDao.findByUsername(s); } catch (Exception e) { e.printStackTrace(); } //User user = new User(userInfo.getUsername(),"{noop}"+userInfo.getPassword(),getAuthority(userInfo.getRoles())); User user = new User(userInfo.getUsername(),"{noop}"+userInfo.getPassword(),userInfo.getStatus() == 0 ? false : true,true,true,true,getAuthority(userInfo.getRoles())); return user; } public List<SimpleGrantedAuthority> getAuthority(List<Role> roles){ List<SimpleGrantedAuthority> list = new ArrayList<>(); for (Role role:roles){ list.add(new SimpleGrantedAuthority("ROLE_"+role.getRoleName())); } return list; } ```
SPRING的奇怪问题
框架是Spring2.5, struts2, ibatis,采用声明式事务,BEAN自动扫描。 [code="xml"] <!-- 使用annotation 自动注册bean,并保证@Required,@Autowired的属性被注入 --> <context:component-scan base-package="jp.co.grids.mda" /> <!-- 使用annotation定义事务 --> <tx:annotation-driven transaction-manager="transactionManager" /> [/code] DAO和SERVICE参考的是SpringSide2,SERVICE继承范型DAO: [code="java"] //Spring Service Bean的标识. @Service //默认将类中的所有函数纳入事务管理. @Transactional public class UserManager extends EntityDao<User> { } [/code] 然后问题来了。 UserManager继承自DAO,我在Action里调用UserManager里面的DAO的方法做CRUD,没有问题。但只要我在UserManager里增加自定义方法,如: [code="java"] //Spring Service Bean的标识. @Service //默认将类中的所有函数纳入事务管理. @Transactional public class UserManager extends EntityDao<User> { public void fun() { } } [/code] 仅仅加一个任意的空方法后,在请求调用了UserManager的Action的时候,就出了这样的LOG,而且没有异常。 2009-03-30 17:55:48 [DEBUG]- Entering nullPropertyValue [target=[com.opensymphony.xwork2.DefaultTextProvider@13e9853], property=struts] 2009-03-30 17:55:48 [DEBUG]- Entering nullPropertyValue [target=[com.opensymphony.xwork2.DefaultTextProvider@13e9853], property=struts] 2009-03-30 17:55:48 [DEBUG]- Creating an DefaultActionProxy for namespace /user and action name user 画面报了500错误 只要在SERVICE类里加入任意自定义方法,就会出这样的问题。太奇怪了。 [b]问题补充:[/b] to iampurse, SpringSide2里就是Serivce继承泛型DAO。我觉得这样的好处有两点: 1,把DAO方法当SERVICE方法用。因为很多场景里业务方法就是简单的CRUD,用DAO方法正合适,不用再到SERVICE里写一层方法了。 2,如果用注入,就要写很多个DAO类,用继承的话,就不用写DAO类了。减少了要维护的文件数量。 但这样做又有点耦合。 UserManager里加的方法就不能算成是DAO的方法了,应该当成是SERVICE的方法。 [b]问题补充:[/b] 呵呵. 把EntityDao配置成bean并加上 abstract看看 这句我有点不太明白.给个代码看一下吧.
在中国程序员是青春饭吗?
今年,我也32了 ,为了不给大家误导,咨询了猎头、圈内好友,以及年过35岁的几位老程序员……舍了老脸去揭人家伤疤……希望能给大家以帮助,记得帮我点赞哦。 目录: 你以为的人生 一次又一次的伤害 猎头界的真相 如何应对互联网行业的「中年危机」 一、你以为的人生 刚入行时,拿着傲人的工资,想着好好干,以为我们的人生是这样的: 等真到了那一天,你会发现,你的人生很可能是这样的: ...
《MySQL 性能优化》之理解 MySQL 体系结构
本文介绍 MySQL 的体系结构,包括物理结构、逻辑结构以及插件式存储引擎。
程序员请照顾好自己,周末病魔差点一套带走我。
程序员在一个周末的时间,得了重病,差点当场去世,还好及时挽救回来了。
复习一周,京东+百度一面,不小心都拿了Offer
京东和百度一面都问了啥,面试官百般刁难,可惜我全会。
Java 14 都快来了,为什么还有这么多人固守Java 8?
从Java 9开始,Java版本的发布就让人眼花缭乱了。每隔6个月,都会冒出一个新版本出来,Java 10 , Java 11, Java 12, Java 13, 到2020年3月份,...
达摩院十大科技趋势发布:2020 非同小可!
【CSDN编者按】1月2日,阿里巴巴发布《达摩院2020十大科技趋势》,十大科技趋势分别是:人工智能从感知智能向认知智能演进;计算存储一体化突破AI算力瓶颈;工业互联网的超融合;机器间大规模协作成为可能;模块化降低芯片设计门槛;规模化生产级区块链应用将走入大众;量子计算进入攻坚期;新材料推动半导体器件革新;保护数据隐私的AI技术将加速落地;云成为IT技术创新的中心 。 新的画卷,正在徐徐展开。...
轻松搭建基于 SpringBoot + Vue 的 Web 商城应用
首先介绍下在本文出现的几个比较重要的概念: 函数计算(Function Compute): 函数计算是一个事件驱动的服务,通过函数计算,用户无需管理服务器等运行情况,只需编写代码并上传。函数计算准备计算资源,并以弹性伸缩的方式运行用户代码,而用户只需根据实际代码运行所消耗的资源进行付费。Fun: Fun 是一个用于支持 Serverless 应用部署的工具,能帮助您便捷地管理函数计算、API ...
讲真,这两个IDE插件,可以让你写出质量杠杠的代码
周末躺在床上看《拯救大兵瑞恩》 周末在闲逛的时候,发现了两个优秀的 IDE 插件,据说可以提高代码的质量,我就安装了一下,试了试以后发现,确实很不错,就推荐给大家。 01、Alibaba Java 代码规范插件 《阿里巴巴 Java 开发手册》,相信大家都不会感到陌生,其 IDEA 插件的下载次数据说达到了 80 万次,我今天又贡献了一次。嘿嘿。 该项目的插件地址: https://github....
Python+OpenCV实时图像处理
目录 1、导入库文件 2、设计GUI 3、调用摄像头 4、实时图像处理 4.1、阈值二值化 4.2、边缘检测 4.3、轮廓检测 4.4、高斯滤波 4.5、色彩转换 4.6、调节对比度 5、退出系统 初学OpenCV图像处理的小伙伴肯定对什么高斯函数、滤波处理、阈值二值化等特性非常头疼,这里给各位分享一个小项目,可通过摄像头实时动态查看各类图像处理的特点,也可对各位调参、测试...
2020年一线城市程序员工资大调查
人才需求 一线城市共发布岗位38115个,招聘120827人。 其中 beijing 22805 guangzhou 25081 shanghai 39614 shenzhen 33327 工资分布 2020年中国一线城市程序员的平均工资为16285元,工资中位数为14583元,其中95%的人的工资位于5000到20000元之间。 和往年数据比较: yea...
为什么猝死的都是程序员,基本上不见产品经理猝死呢?
相信大家时不时听到程序员猝死的消息,但是基本上听不到产品经理猝死的消息,这是为什么呢? 我们先百度搜一下:程序员猝死,出现将近700多万条搜索结果: 搜索一下:产品经理猝死,只有400万条的搜索结果,从搜索结果数量上来看,程序员猝死的搜索结果就比产品经理猝死的搜索结果高了一倍,而且从下图可以看到,首页里面的五条搜索结果,其实只有两条才是符合条件。 所以程序员猝死的概率真的比产品经理大,并不是错...
害怕面试被问HashMap?这一篇就搞定了!
声明:本文以jdk1.8为主! 搞定HashMap 作为一个Java从业者,面试的时候肯定会被问到过HashMap,因为对于HashMap来说,可以说是Java集合中的精髓了,如果你觉得自己对它掌握的还不够好,我想今天这篇文章会非常适合你,至少,看了今天这篇文章,以后不怕面试被问HashMap了 其实在我学习HashMap的过程中,我个人觉得HashMap还是挺复杂的,如果真的想把它搞得明明白...
毕业5年,我问遍了身边的大佬,总结了他们的学习方法
我问了身边10个大佬,总结了他们的学习方法,原来成功都是有迹可循的。
python爬取百部电影数据,我分析出了一个残酷的真相
2019年就这么匆匆过去了,就在前几天国家电影局发布了2019年中国电影市场数据,数据显示去年总票房为642.66亿元,同比增长5.4%;国产电影总票房411.75亿元,同比增长8.65%,市场占比 64.07%;城市院线观影人次17.27亿,同比增长0.64%。 看上去似乎是一片大好对不对?不过作为一名严谨求实的数据分析师,我从官方数据中看出了一点端倪:国产票房增幅都已经高达8.65%了,为什...
推荐10个堪称神器的学习网站
每天都会收到很多读者的私信,问我:“二哥,有什么推荐的学习网站吗?最近很浮躁,手头的一些网站都看烦了,想看看二哥这里有什么新鲜货。” 今天一早做了个恶梦,梦到被老板辞退了。虽然说在我们公司,只有我辞退老板的份,没有老板辞退我这一说,但是还是被吓得 4 点多都起来了。(主要是因为我掌握着公司所有的核心源码,哈哈哈) 既然 4 点多起来,就得好好利用起来。于是我就挑选了 10 个堪称神器的学习网站,推...
这些软件太强了,Windows必装!尤其程序员!
Windows可谓是大多数人的生产力工具,集娱乐办公于一体,虽然在程序员这个群体中都说苹果是信仰,但是大部分不都是从Windows过来的,而且现在依然有很多的程序员用Windows。 所以,今天我就把我私藏的Windows必装的软件分享给大家,如果有一个你没有用过甚至没有听过,那你就赚了????,这可都是提升你幸福感的高效率生产力工具哦! 走起!???? NO、1 ScreenToGif 屏幕,摄像头和白板...
阿里面试,面试官没想到一个ArrayList,我都能跟他扯半小时
我是真的没想到,面试官会这样问我ArrayList。
曾经优秀的人,怎么就突然不优秀了。
职场上有很多辛酸事,很多合伙人出局的故事,很多技术骨干被裁员的故事。说来模板都类似,曾经是名校毕业,曾经是优秀员工,曾经被领导表扬,曾经业绩突出,然而突然有一天,因为种种原因,被裁员了,...
大学四年因为知道了这32个网站,我成了别人眼中的大神!
依稀记得,毕业那天,我们导员发给我毕业证的时候对我说“你可是咱们系的风云人物啊”,哎呀,别提当时多开心啦????,嗯,我们导员是所有导员中最帅的一个,真的???? 不过,导员说的是实话,很多人都叫我大神的,为啥,因为我知道这32个网站啊,你说强不强????,这次是绝对的干货,看好啦,走起来! PS:每个网站都是学计算机混互联网必须知道的,真的牛杯,我就不过多介绍了,大家自行探索,觉得没用的,尽管留言吐槽吧???? 社...
良心推荐,我珍藏的一些Chrome插件
上次搬家的时候,发了一个朋友圈,附带的照片中不小心暴露了自己的 Chrome 浏览器插件之多,于是就有小伙伴评论说分享一下我觉得还不错的浏览器插件。 我下面就把我日常工作和学习中经常用到的一些 Chrome 浏览器插件分享给大家,随便一个都能提高你的“生活品质”和工作效率。 Markdown Here Markdown Here 可以让你更愉快的写邮件,由于支持 Markdown 直接转电子邮...
看完这篇HTTP,跟面试官扯皮就没问题了
我是一名程序员,我的主要编程语言是 Java,我更是一名 Web 开发人员,所以我必须要了解 HTTP,所以本篇文章就来带你从 HTTP 入门到进阶,看完让你有一种恍然大悟、醍醐灌顶的感觉。 最初在有网络之前,我们的电脑都是单机的,单机系统是孤立的,我还记得 05 年前那会儿家里有个电脑,想打电脑游戏还得两个人在一个电脑上玩儿,及其不方便。我就想为什么家里人不让上网,我的同学 xxx 家里有网,每...
2020 年,大火的 Python 和 JavaScript 是否会被取而代之?
Python 和 JavaScript 是目前最火的两大编程语言,但是2020 年,什么编程语言将会取而代之呢? 作者 |Richard Kenneth Eng 译者 |明明如月,责编 | 郭芮 出品 | CSDN(ID:CSDNnews) 以下为译文: Python 和 JavaScript 是目前最火的两大编程语言。然而,他们不可能永远屹立不倒。最终,必将像其他编程语言一...
史上最全的IDEA快捷键总结
现在Idea成了主流开发工具,这篇博客对其使用的快捷键做了总结,希望对大家的开发工作有所帮助。
阿里程序员写了一个新手都写不出的低级bug,被骂惨了。
这种新手都不会范的错,居然被一个工作好几年的小伙子写出来,差点被当场开除了。
谁是华为扫地僧?
是的,华为也有扫地僧!2020年2月11-12日,“养在深闺人不知”的华为2012实验室扫地僧们,将在华为开发者大会2020(Cloud)上,和大家见面。到时,你可以和扫地僧们,吃一个洋...
Idea 中最常用的10款插件(提高开发效率),一定要学会使用!
学习使用一些插件,可以提高开发效率。对于我们开发人员很有帮助。这篇博客介绍了开发中使用的插件。
AI 没让人类失业,搞 AI 的人先失业了
最近和几个 AI 领域的大佬闲聊 根据他们讲的消息和段子 改编出下面这个故事 如有雷同 都是巧合 1. 老王创业失败,被限制高消费 “这里写我跑路的消息实在太夸张了。” 王葱葱哼笑一下,把消息分享给群里。 阿杰也看了消息,笑了笑。在座几位也都笑了。 王葱葱是个有名的人物,21岁那年以全额奖学金进入 KMU 攻读人工智能博士,累计发表论文 40 余篇,个人技术博客更是成为深度学习领域内风向标。 ...
2020年,冯唐49岁:我给20、30岁IT职场年轻人的建议
点击“技术领导力”关注∆每天早上8:30推送 作者|Mr.K 编辑| Emma 来源|技术领导力(ID:jishulingdaoli) 前天的推文《冯唐:职场人35岁以后,方法论比经验重要》,收到了不少读者的反馈,觉得挺受启发。其实,冯唐写了不少关于职场方面的文章,都挺不错的。可惜大家只记住了“春风十里不如你”、“如何避免成为油腻腻的中年人”等不那么正经的文章。 本文整理了冯...
作为一名大学生,如何在B站上快乐的学习?
B站是个宝,谁用谁知道???? 作为一名大学生,你必须掌握的一项能力就是自学能力,很多看起来很牛X的人,你可以了解下,人家私底下一定是花大量的时间自学的,你可能会说,我也想学习啊,可是嘞,该学习啥嘞,不怕告诉你,互联网时代,最不缺的就是学习资源,最宝贵的是啥? 你可能会说是时间,不,不是时间,而是你的注意力,懂了吧! 那么,你说学习资源多,我咋不知道,那今天我就告诉你一个你必须知道的学习的地方,人称...
那些年,我们信了课本里的那些鬼话
教材永远都是有错误的,从小学到大学,我们不断的学习了很多错误知识。 斑羚飞渡 在我们学习的很多小学课文里,有很多是错误文章,或者说是假课文。像《斑羚飞渡》: 随着镰刀头羊的那声吼叫,整个斑羚群迅速分成两拨,老年斑羚为一拨,年轻斑羚为一拨。 就在这时,我看见,从那拨老斑羚里走出一只公斑羚来。公斑羚朝那拨年轻斑羚示意性地咩了一声,一只半大的斑羚应声走了出来。一老一少走到伤心崖,后退了几步,突...
立即提问