【java】spring mvc怎么用实体接受get传过来的参数

现场:get请求,有很多参数(大概20个)
我在controller里面想写个对象来接收他,大概叫 (User user)这样子

请问注解用哪个,
@RequestBody还是@RequestParam
或者其他的

2个回答

如果是get请求,你只能用@RequestParam来接受,页面参数加上user.就可以了,比如说user.pwd等,但是要注意get请求的所有参数都是明文url传输,安全性较低,而且最大只支持1024字节,中文和特殊符号会转码,字节数更长,所以建议最好还是用post或者put请求。

ainiburuqusi
ainiburuqusi 回复zhangpan_soft: 额。URL长度限制和浏览器以及web容器有关系的。不一定是2083字节。
一年多之前 回复
zhangpan_soft
zhangpan_soft 是2k是2048字节,不是1024
一年多之前 回复

如果你想用实体对象来接收参数,就用@RequestBody,并将请求方式改为post.
如果你想用get请求,就不要选择实体对象接收参数,可以改为map,用@RequestParam来接收参数

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
【Java】spring MVC怎么提取参数

![图片说明](https://img-ask.csdn.net/upload/201807/26/1532599548_225365.png) 我controller的方法参数该怎么写,map或者实体javabean都可以,我是对skus哪里有迷惑,想转成List<Map<String,String>z这样,但是老报错 POST请求

jsp页面传值在spring mvc中的controller中的获取

``` <% Seller seller =(Seller)session.getAttribute("sellerinfo"); %> <form action="<%=basePath%>plmanage/updateSeller.do" method="post"> <input type="hidden" name="id" value="<%=seller.getSlId()%>"> <table> <caption>更新卖家信息</caption> <tr> <td>用户名:</td> <td><%=seller.getSellerName() %></td> </tr> <tr> <td>密码</td> <td><input type="password" name="password" value="<%=seller.getPassword() %>"/></td> </tr> <tr> <td>性别</td> <td> <% if(null==seller.getGender()){ %> <input type="radio" name="gender" value="男">男<input type="radio" name="gender" value="女">女 <% }else if(seller.getGender().equals("男")){ %> <input type="radio" name="gender" value="男" checked="checked">男<input type="radio" name="gender" value="女">女 <% }else{ %> <input type="radio" name="gender" value="男" >男<input type="radio" name="gender" value="女" checked="checked">女 <% }%> </td> </tr> <tr> <td>店铺名</td> <td><input type="text" name="storename" value="<%=seller.getStorename()%>"/></td> </tr> <tr> <td>电话</td> <td><input type="text" name="telephone" value="<%=seller.getTelephone()%>"/></td> </tr> <tr> <td>Email</td> <td><input type="text" name="email" value="<%=seller.getEmail()%>"/></td> </tr> <tr> <td>店铺书的数量</td> <td><input type="text" name="bookamount" /></td> </tr> </table> <input type='submit' value='提交'> <input type="reset" value="重置"> </form> </body> ``` 我先说明一下我的目的,在更新用户界面将信息传到controller中调用service更新至数据库,但是controller中获取不到实体Seller。 简单的注册页面就可以将Seller绑定到controller中,为什么这边加了一个数据的获取就不行了。这里的seller数据获取至已有的表单数据。 我做的就是将表单中的数据支持更新修改操作,跳转到如上的代码进行信息输入,再跳转到controller中进行service存储数据

spring mvc +hibernate4事务控制问题求大神解答

``` web.xml <?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"> <display-name>spring-mvc</display-name> <!--配置欢迎界面 --> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <context-param> <param-name>contextConfigLocation</param-name> <param-value> classpath:applicationContext.xml </param-value> </context-param> <!--配置listener --> <!--在这里可以配置spring的监听器,启动的时候需要把spring中的bean都注册到spring容器中 --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!--配置filter对编码进行转换 --> <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> <!--配置servlet --> <!--我们希望spring的控制器比其他servlet优先启动,所以你需要设置load-on-startup 这个东西:值越小越先启动(0-5),没有或者为负数的时候,servlet被选用的时候才加载--> <servlet> <servlet-name>controller</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:controll-servlet.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>controller</servlet-name> <url-pattern>*.action</url-pattern> </servlet-mapping> </web-app> applicationContext.xml <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:dwr="http://www.directwebremoting.org/schema/spring-dwr" 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.directwebremoting.org/schema/spring-dwr http://www.directwebremoting.org/schema/spring-dwr-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> <!-- 启动自动扫描该包下所有的Bean 注意这块,也非常重要 --> <context:component-scan base-package="com.tb" use-default-filters="false"> <context:include-filter type="annotation" expression="org.springframework.stereotype.Service"></context:include-filter> <context:include-filter type="annotation" expression="org.springframework.stereotype.Repository"></context:include-filter> </context:component-scan> <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations"> <list> <value>classpath:hibernate.properties</value> </list> </property> </bean> <!-- 配置数据源 --> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close"> <property name="driverClass"> <value>${db.driver}</value> </property> <property name="jdbcUrl"> <value>${db.url}</value> </property> <property name="user"> <value>${db.user}</value> </property> <property name="password"> <value>${db.password}</value> </property> <property name="maxPoolSize"> <value>300</value> </property> <property name="minPoolSize"> <value>1</value> </property> <property name="initialPoolSize"> <value>1</value> </property> <property name="maxIdleTime"> <value>60</value> </property> <property name="acquireIncrement"> <value>5</value> </property> <property name="acquireRetryAttempts"> <value>10</value> </property> <property name="acquireRetryDelay"> <value>1000</value> </property> <property name="autoCommitOnClose"> <value>true</value> </property> <property name="breakAfterAcquireFailure"> <value>false</value> </property> <property name="checkoutTimeout"> <value>10000</value> </property> <property name="idleConnectionTestPeriod"> <value>60</value> </property> </bean> <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"> <property name="dataSource" ref="dataSource"/> <!-- 让spring帮你扫描这个包底下的所有类,主要作用扫描跟数据库对应的实体类 --> <!-- 设置hibernate的属性 --> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect"> org.hibernate.dialect.OracleDialect </prop> <prop key="hibernate.show_sql">true</prop> <prop key="hibernate.format_sql">true</prop> <prop key="hibernate.hbm2ddl.auto">update</prop> <prop key="hibernate.max_fetch_depth">3</prop> <prop key="hibernate.default_batch_fetch_size">8</prop> <prop key="hibernate.jdbc.batch_size">20</prop> <prop key="javax.persistence.validation.mode">none</prop> </props> </property> <property name="packagesToScan" value="com.neusoft.vo"/> </bean> <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory"></property> </bean> <!-- 配置事务传播特性 --> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="insert*" propagation="REQUIRED" /> <tx:method name="del*" propagation="REQUIRED"/> <tx:method name="update*" propagation="REQUIRED" rollback-for="Exception"/> <tx:method name="add*" propagation="REQUIRED"/> <tx:method name="test*" propagation="REQUIRED" rollback-for="Exception"/> <tx:method name="get*" propagation="REQUIRED"/> <tx:method name="apply*" propagation="REQUIRED"/> <tx:method name="exe*" propagation="REQUIRED" rollback-for="Exception"/> </tx:attributes> </tx:advice> <!-- 需要引入aop的命名空间 --> <aop:config> <aop:pointcut id="daoMethods" expression="execution(* com.neusoft.bo.*.*(..))" /> <aop:advisor advice-ref="txAdvice" pointcut-ref="daoMethods" /> </aop:config> <!-- 开启AOP监听 只对当前配置文件有效 --> <aop:aspectj-autoproxy expose-proxy="true" /> <!-- 开启注解事务 只对当前配置文件有效 --> <tx:annotation-driven transaction-manager="txManager" /> </beans> controll-servlet.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.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd"> <!-- 启动自动扫描该包下所有的Bean(例如@Controller) 这块很重要,会影响到事务--> <context:component-scan base-package="com.tb.action" use-default-filters="false"> <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"></context:include-filter> </context:component-scan> <!-- json --> <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> <property name="messageConverters"> <list> <ref bean="jsonHttpMessageConverter"/> </list> </property> </bean> <bean id="jsonHttpMessageConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"> <property name="supportedMediaTypes"> <list> <value>text/html;charset=UTF-8</value> </list> </property> </bean> <!-- ③:对模型视图名称的解析,即在模型视图名称添加前后缀 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/> <property name="prefix" value="/WEB-INF/jsp/"/> <property name="suffix" value=".jsp"/> </bean> </beans> 以上为配置文件:包路径分别为com.tb.action;com.tb.service;com.tb.model;com.tb.dao; 方法: Controller.java @RequestMapping(params = "executeSearch") public String executeSearch(HttpServletRequest request) { //测试事物控制。 infoService.test(); return "info/search"; } ServiceImpl.java public void test(){ try { infoDAO.test(); throw new Exception(); } catch (Exception e) { e.printStackTrace(); } } Service.java @Transactional public void test(); DaoImpl.java public void test() { WlOperationLog log=this.findEntity(); log.setUsername("2"); updateCommit(log); } 整体代码是这样的,在运行daoImpl.java中test()方法的时候执行第一条SQL时会提交事物,直接修改数据库中的值,执行第二条SQL时会报错,理论上应该都不提交事物。但实际上第一条执行了之后就提交事物了,不知道是我框架问题还是我写的问题,求大神帮忙指出问题所在。万分感谢! ```

spring注解方式报错找不到实体类

这是springMVC.xml配置 ``` <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p" xmlns:mvc="http://www.springframework.org/schema/mvc" 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-3.0.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-3.0.xsd"> <!-- 支持注解 --> <mvc:annotation-driven /> <!--自动装配DefaultAnnotationHandlerMapping和AnnotationMethodHandlerAdapter --> <mvc:default-servlet-handler /> <!-- 设置自动扫描的路径,用于自动注入bean 这里的路径与自己的项目目录对应 --> <!-- 扫描controller路由控制器 --> <context:component-scan base-package="com.TimeSea.controller" /> <context:component-scan base-package="com.TimeSea.dao" /> <context:component-scan base-package="com.TimeSea.service" /> <!-- 视图解析器 --> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" /> <property name="suffix" value=".jsp" /> <!-- 视图文件类型 --> <property name="prefix" value="/WEB-INF/views" /> <!-- 视图文件的文件夹路径 --> </bean> </beans> ``` 这是spring-hibernate.xml配置 ``` <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 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.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd "> <!-- 引入属性文件 --> <context:property-placeholder location="classpath:db.properties" /> <!-- 配置数据源 这里class可以使用不同的驱动--> <bean name="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="url" value="${database.url}" /> <property name="username" value="${database.username}" /> <property name="password" value="${database.password}" /> </bean> <!-- 配置hibernate session工厂 --> <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="hibernateProperties"> <props> <prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop> <prop key="hibernate.dialect">${database.dialect}</prop> <prop key="hibernate.show_sql">${hibernate.show_sql}</prop> <prop key="hibernate.format_sql">${hibernate.format_sql}</prop> <prop key="current_session_context_class">thread</prop> <prop key="hibernate.connection.driver_class">${database.driverClassName}</prop> </props> </property> <!-- 自动扫描注解方式配置的hibernate类文件 --> <property name="packagesToScan"> <list> <!-- 此处与entity实体路径对应 --> <value>com.TimeSea.entity</value> </list> </property> </bean> <!-- 配置事务管理器 --> <bean name="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory"></property> </bean> <!-- 注解方式配置事物 --> <tx:annotation-driven transaction-manager="transactionManager" /> </beans> ``` 报错信息如下: org.hibernate.MappingException: Unknown entity: com.TimeSea.entity.TimeseaUser at org.hibernate.internal.SessionFactoryImpl.getEntityPersister(SessionFactoryImpl.java:1192) at org.hibernate.internal.SessionImpl.locateEntityPersister(SessionImpl.java:2436) at org.hibernate.internal.SessionImpl.access$2100(SessionImpl.java:172) at org.hibernate.internal.SessionImpl$IdentifierLoadAccessImpl.<init>(SessionImpl.java:2378) at org.hibernate.internal.SessionImpl$IdentifierLoadAccessImpl.<init>(SessionImpl.java:2382) at org.hibernate.internal.SessionImpl$IdentifierLoadAccessImpl.<init>(SessionImpl.java:2369) at org.hibernate.internal.SessionImpl.byId(SessionImpl.java:1052) at org.hibernate.internal.SessionImpl.get(SessionImpl.java:975) at com.TimeSea.dao.impl.BaseDaoImpl.findById(BaseDaoImpl.java:63) at com.TimeSea.service.impl.TimeSeaUserSVImpl.selectTimeSeaUserInfo(TimeSeaUserSVImpl.java:20) at com.TimeSea.controller.TimeSeaUserAction.selectUserInfo(TimeSeaUserAction.java:19) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:483) at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221) at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:137) at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:111) at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:806) at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:729) at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85) at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:959) at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893) at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970) at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861) at javax.servlet.http.HttpServlet.service(HttpServlet.java:624) at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846) at javax.servlet.http.HttpServlet.service(HttpServlet.java:731) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208) at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208) at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:85) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208) at org.springframework.orm.hibernate4.support.OpenSessionInViewFilter.doFilterInternal(OpenSessionInViewFilter.java:151) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122) at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:505) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:169) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103) at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:956) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:436) at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1078) at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:625) at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.doRun(AprEndpoint.java:2517) at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:2506) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) at java.lang.Thread.run(Thread.java:745) 哪位可以指教一下

spring mvc不用<form:input>只用input却能提交到ModelAttribute

Product类 ``` package app06; import java.util.List; import javax.validation.constraints.NotNull; import org.springframework.web.multipart.MultipartFile; public class Product { private static final long servialVersionUID = 74458L; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public Float getPrice() { return price; } public void setPrice(Float price) { this.price = price; } private String name; private String description; private Float price; private List<MultipartFile> images; public List<MultipartFile> getImages() { return images; } public void setImages(List<MultipartFile> images) { this.images = images; } } ``` ProductController类 ``` package app06; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.ArrayList; import java.util.List; import javax.servlet.http.HttpServletRequest; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.client.HttpServerErrorException; import org.springframework.web.multipart.MultipartFile; @Controller public class ProductController { @RequestMapping("/product_input") public String inputProduct(Model model){ model.addAttribute("product",new Product()); return "FileUpload"; } @RequestMapping("/product_save") public String saveProduct(HttpServletRequest servletRequest,@ModelAttribute Product product,BindingResult bindingResult,Model model) throws IOException{ //return null; List<MultipartFile> files = product.getImages(); List<String> fileNames = new ArrayList<String>(); //File mkdir = new File(servletRequest.getServletContext().getRealPath("/image")); //mkdir.mkdir(); if(null != files && files.size() > 0){ for(MultipartFile mpf : files){ String fileName = mpf.getOriginalFilename(); fileNames.add(fileName); File parFile = new File(servletRequest.getServletContext().getRealPath("/").toString()).getParentFile().getAbsoluteFile(); parFile = new File(parFile,"/app06_file"); if(!parFile.exists()){ parFile.mkdirs(); } File imageFile = new File(parFile,fileName); System.out.println(imageFile); if(!imageFile.exists()){ imageFile.createNewFile(); } try{ mpf.transferTo(imageFile); }catch(Exception e){ e.printStackTrace(); } } } return null; } } ``` FileUpload.jsp ``` <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'FileUpload.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <form:form commandName="product" action="product_save" method="post" enctype="multipart/form-data"> <fieldset> <legend>Add a product</legend> Product Name : <form:input path="name"/><br/> Description: <form:input path="description"/><br/> Price:<form:input path="price"/><br/> Product image : <input type="file" name="images[0]"><br/> <input type="reset"><input type="submit" value="Add A Product"> </fieldset> </form:form> <body> </body> </html> ``` 这个代码运行是能成功上传文件的 但是我不明白 <input type="file" name="images[0]">为什么不需要用<form:input>就能被后台的@ModelAttribute Product这个接收到 并且name的image要加个[0] 就算是不加这个[0]也是能成功的 因为我是大一新生一枚 是按照书上一步一步来的 不太了解问问题的方式 求大神指导

spring mvc+hibernate4事务控制

``` web.xml <?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"> <display-name>spring-mvc</display-name> <!--配置欢迎界面 --> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <error-page> <error-code>404</error-code> <location>/error/404.jsp</location> </error-page> <error-page> <error-code>500</error-code> <location>/error/exception.jsp</location> </error-page> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </context-param> <!-- Log4j配置 --> <context-param> <param-name>log4jConfigLocation</param-name> <param-value>WEB-INF/log4j.properties</param-value> </context-param> <!-- 开一条watchdog线程每60秒扫描一下配置文件的变化 --> <context-param> <param-name>log4jRefreshInterval</param-name> <param-value>60000</param-value> </context-param> <!--配置log4j包 --> <listener> <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class> </listener> <!--配置listener --> <!--在这里可以配置spring的监听器,启动的时候需要把spring中的bean都注册到spring容器中 --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!--配置filter对编码进行转换 --> <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> <!--配置servlet --> <!--我们希望spring的控制器比其他servlet优先启动,所以你需要设置load-on-startup 这个东西:值越小越先启动(0-5),没有或者为负数的时候,servlet被选用的时候才加载--> <servlet> <servlet-name>controller</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:controll-servlet.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>controller</servlet-name> <url-pattern>*.action</url-pattern> </servlet-mapping> <filter> <filter-name>openSessionInViewFilter</filter-name> <filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class> <init-param> <param-name>singleSession</param-name> <param-value>true</param-value> </init-param> <init-param> <param-name>sessionFactory</param-name> <param-value>sessionFactory</param-value> </init-param> </filter> <filter-mapping> <filter-name>openSessionInViewFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app> applicationContext.xml <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:dwr="http://www.directwebremoting.org/schema/spring-dwr" 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.directwebremoting.org/schema/spring-dwr http://www.directwebremoting.org/schema/spring-dwr-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations"> <list> <value>classpath:hibernate.properties</value> </list> </property> </bean> <!-- DWR配置--> <dwr:annotation-config></dwr:annotation-config> <!-- 扫描需要转换的java对象 --> <dwr:annotation-scan scanRemoteProxy="true" base-package="com.tb.service" /> <!-- 部署项目时, 请把debug设为false <dwr:controller id="dwrController" debug="true" /> --> <!--DWR初始化配置 --> <dwr:configuration></dwr:configuration> <!-- 配置数据源 --> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close"> <property name="driverClass"> <value>${db.driver}</value> </property> <property name="jdbcUrl"> <value>${db.url}</value> </property> <property name="user"> <value>${db.user}</value> </property> <property name="password"> <value>${db.password}</value> </property> <property name="maxPoolSize"> <value>300</value> </property> <property name="minPoolSize"> <value>1</value> </property> <property name="initialPoolSize"> <value>1</value> </property> <property name="maxIdleTime"> <value>60</value> </property> <property name="acquireIncrement"> <value>5</value> </property> <property name="acquireRetryAttempts"> <value>10</value> </property> <property name="acquireRetryDelay"> <value>1000</value> </property> <property name="autoCommitOnClose"> <value>true</value> </property> <property name="breakAfterAcquireFailure"> <value>false</value> </property> <property name="checkoutTimeout"> <value>100</value> </property> <property name="idleConnectionTestPeriod"> <value>60</value> </property> </bean> <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"> <property name="dataSource" ref="dataSource"/> <!-- 让spring帮你扫描这个包底下的所有类,主要作用扫描跟数据库对应的实体类 --> <!-- 设置hibernate的属性 --> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect"> org.hibernate.dialect.OracleDialect </prop> <prop key="hibernate.show_sql">true</prop> <prop key="hibernate.format_sql">true</prop> <prop key="hibernate.use_outer_join">true </prop> <prop key="hibernate.cglib.use_reflection_optimizer">true </prop> <prop key="hibernate.connection.useUnicode">true</prop> <prop key="hibernate.cache.use_query_cache">false</prop> <prop key="hibernate.default_batch_fetch_size">16</prop> <prop key="hibernate.c3p0.max_size">300</prop> <prop key="hibernate.c3p0.min_size">1</prop> <prop key="hibernate.c3p0.timeout">60</prop> <prop key="hibernate.c3p0.max_statements">100</prop> <prop key="hibernate.c3p0.idle_test_period">60</prop> <prop key="hibernate.c3p0.acquire_increment">5</prop> <prop key="hibernate.c3p0.validate">true</prop> <prop key="hibernate.current_session_context_class">thread</prop> </props> </property> <property name="packagesToScan" value="com.tb.model"/> </bean> <!--事务配置 --> <bean id="txManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory"></property> </bean> <!-- 开启AOP监听 只对当前配置文件有效 --> <aop:aspectj-autoproxy expose-proxy="true" /> <!-- 开启注解事务 只对当前配置文件有效 --> <tx:annotation-driven transaction-manager="txManager"/> <tx:advice id="txAdvice" transaction-manager="txManager"> <tx:attributes> <tx:method name="save*" propagation="REQUIRED" /> <tx:method name="add*" propagation="REQUIRED" /> <tx:method name="create*" propagation="REQUIRED" /> <tx:method name="insert*" propagation="REQUIRED" /> <tx:method name="update*" propagation="REQUIRED" /> <tx:method name="merge*" propagation="REQUIRED" /> <tx:method name="del*" propagation="REQUIRED" /> <tx:method name="remove*" propagation="REQUIRED" /> <tx:method name="put*" propagation="REQUIRED" /> <tx:method name="execute*" propagation="REQUIRED" rollback-for ="Exception.class" /> <tx:method name="tes*" propagation="REQUIRED" /> <tx:method name="use*" propagation="REQUIRED" /> <!--hibernate4必须配置为开启事务 否则 getCurrentSession()获取不到 --> <tx:method name="get*" propagation="REQUIRED" read-only="true" /> <tx:method name="count*" propagation="REQUIRED" read-only="true" /> <tx:method name="find*" propagation="REQUIRED" read-only="true" /> <tx:method name="list*" propagation="REQUIRED" read-only="true" /> <tx:method name="*" propagation="REQUIRED" rollback-for ="Exception.class"/> </tx:attributes> </tx:advice> <bean id="transactionProxy" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean" abstract="true" lazy-init="true"> <property name="transactionManager" ref="txManager"></property> <property name="transactionAttributes"> <props> <prop key="add*">PROPAGATION_REQUIRED,-Exception</prop> <prop key="save*">PROPAGATION_REQUIRED,-Exception</prop> <prop key="tes*">PROPAGATION_REQUIRED,-Exception</prop> <prop key="execute*">PROPAGATION_REQUIRED,-Exception</prop> <prop key="modify*">PROPAGATION_REQUIRED,-Exception</prop> <prop key="update*">PROPAGATION_REQUIRED,-Exception</prop> <prop key="delete*">PROPAGATION_REQUIRED,-Exception</prop> <prop key="remove*">PROPAGATION_REQUIRED,-Exception</prop> <prop key="query*">PROPAGATION_REQUIRED, readOnly,-Exception</prop> <prop key="load*">PROPAGATION_REQUIRED, -Exception</prop> </props> </property> </bean> <!-- 只对业务逻辑层实施事务 --> <aop:config expose-proxy="true"> <aop:pointcut id="txPointcut" expression="execution(* com.tb.*.*(..))" /> <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut" /> </aop:config> <!-- --> <!--配置拦截器 在springmvc的控制器配置文件中,你就可以这么配置拦截器,具体你在拦截器里面做什么,自己去做 <mvc:interceptors> 多个拦截器,顺序执行 <mvc:interceptor> 这里的path符号有/*, /**, *, ? 等,对于student.do?param=1从?开始不作为path 如果不配置或/*,将拦截所有的Controller <mvc:mapping path="/student/save*" /> <bean class="spring.common.interceptor.FromDupInterceptor"></bean> </mvc:interceptor> </mvc:interceptors> --> </beans> controll-servlet.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" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> <context:component-scan base-package="com.tb"> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/> </context:component-scan> <context:component-scan base-package="com.tb"/> <!-- json --> <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> <property name="messageConverters"> <list> <ref bean="jsonHttpMessageConverter"/> </list> </property> </bean> <bean id="jsonHttpMessageConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"> <property name="supportedMediaTypes"> <list> <value>text/html;charset=UTF-8</value> </list> </property> </bean> <!-- ③:对模型视图名称的解析,即在模型视图名称添加前后缀 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/> <property name="prefix" value="/WEB-INF/jsp/"/> <property name="suffix" valu-e=".jsp"/> </bean> </beans> 以上为配置文件:包路径分别为com.tb.action;com.tb.service;com.tb.model;com.tb.dao; 其中com.tb.service下面又分com.tb.service.impl;com.tb.dao包下又分com.tb.dao.impl; 但是现在测试事物一直控制不了,请大神帮忙原因。测试方法: Controller.java @RequestMapping(params = "executeSearch") @Transactional public String executeSearch(HttpServletRequest request) { //测试事物控制。 infoService.test(); return "info/search"; } ServiceImpl.java public void test(){ try { infoDAO.test(); } catch (Exception e) { e.printStackTrace(); } } Service.java @Transactional public void test(); DaoImpl.java @Transactional public void test() { try { String sql = "update operation_log set username='1' where id='1'"; List<Object> condition = new ArrayList<Object>(); this.executeUpdateBySql(sql, condition); String sql1 = "update operation_log set username=33, where id='1'"; this.executeUpdateBySql(sql1, condition); } catch (RuntimeException e) { e.printStackTrace(); } } DaoImpl.java继承HibernateDao HibernateDao.java /***************注入***********/ @Resource private SessionFactory sessionFactory; public SessionFactory getSessionFactory() { return sessionFactory; } public void setSessionFactory(SessionFactory sessionFactory) { this.sessionFactory = sessionFactory; } public Session getSession() { //事务配置后,可通过getCurrentSession方法获得session return sessionFactory.getCurrentSession(); } public int executeUpdateBySql(final String sql,final List<Object> conditions){ try { Query query = getSession().createSQLQuery(sql); if(conditions!=null && conditions.size()>0){ for(int i=0;i<conditions.size();i++){ if(conditions.get(i)!=null && !conditions.get(i).equals("")){ query.setParameter(i, conditions.get(i)); } } } return query.executeUpdate(); } catch (RuntimeException e) { throw e; }finally{ System.out.println(getSessionFactory().getCurrentSession().beginTransaction().isActive()); } } 整体代码是这样的,在运行daoImpl.java中test()方法的时候执行第一条SQL时会提交事物,直接修改数据库中的值,执行第二条SQL时会报错,理论上应该都不提交事物。但实际上第一条执行了之后就提交事物了,不知道是我框架问题还是我写的问题,求大神帮忙指出问题所在。万分感谢! ```

关于REST风格的SpringMVC Controller 传递多个参数的问题

关于REST风格的SpringMVC Controller 传递多个参数的问题 [code="java"] /** * * * Description: 预更新操作根据用户名查询用户信息 然后数据交给携带体 展示到视图 REST风格: /更新的用户的用户名/update * @param username @PathVariable修饰 表示形参同URL中的请求参数 * @param model 携带数据的Model * @return 视图页面/WEB-INF/jsp/user/update页面 * */ @RequestMapping(value="/{username}/update",method=RequestMethod.GET) public String update(@PathVariable String username, Model model){ System.out.println("获取到传入的参数值为:" + username); model.addAttribute(users.get(username)); return "user/update"; }[/code] 当传递多个参数时 如何设置controller 难道就是设置多个@PathVariable

springMVC 实体映射问题

/** *这里是表的结构 */ CREATE TABLE "PS"."U_BILL" ( "ID" NUMBER(11) NOT NULL , "BILL_NUM" VARCHAR2(16 CHAR) NULL , "BILL_STATUS" VARCHAR2(8 CHAR) NULL , "PAY_BACK_DATE" DATE NULL , "PAY_BACK_TIME" VARCHAR2(16 CHAR) NULL , "PAY_MONEY" NUMBER(25,10) NULL , "PAYGROUP_ID" NUMBER(25,10) NULL , "UUID" VARCHAR2(64 CHAR) NULL , "WHOCREATED" VARCHAR2(100 CHAR) NULL , "WHENCREATED" TIMESTAMP(6) DEFAULT SYSDATE NULL , "WHOMODIFIED" VARCHAR2(100 CHAR) NULL , "WHENMODIFIED" TIMESTAMP(6) NULL ) LOGGING NOCOMPRESS NOCACHE ; /** *这是我的实体类代码 */ package com.entity; import java.math.BigDecimal; import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; /** * U_BILL Entity @author sjy */ @Entity @Table(name = "U_BILL", schema = "PS") public class TUBill { private BigDecimal id; private String billNum; private String billStatus; private Date payBackDate; private double payMoney; private BigDecimal paygroupId; private String uuid; // Constructors /** default constructor */ public TUBill() { super(); } /** full constructor */ public TUBill(BigDecimal id, String billNum, String billStatus, Date payBackDate, double payMoney, BigDecimal paygroupId, String uuid) { super(); this.id = id; this.billNum = billNum; this.billStatus = billStatus; this.payBackDate = payBackDate; this.payMoney = payMoney; this.paygroupId = paygroupId; this.uuid = uuid; } // Property accessors @Id @Column(name = "ID", unique = true, nullable = false, precision = 11, scale = 0) public BigDecimal getId() { return id; } public void setId(BigDecimal id) { this.id = id; } @Column(name = "BILL_NUM", length = 16) public String getBillNum() { return billNum; } public void setBillNum(String billNum) { this.billNum = billNum; } @Column(name = "BILL_STATUS", length = 8) public String getBillStatus() { return billStatus; } public void setBillStatus(String billStatus) { this.billStatus = billStatus; } @Temporal(TemporalType.TIMESTAMP) @Column(name = "PAY_BACK_DATE", length = 7) public Date getPayBackDate() { return payBackDate; } public void setPayBackDate(Date payBackDate) { this.payBackDate = payBackDate; } @Column(name = "PAY_MONEY", precision = 25, scale = 10) public double getPayMoney() { return payMoney; } public void setPayMoney(double payMoney) { this.payMoney = payMoney; } @Column(name = "PAYGROUP_ID", precision = 25, scale = 10) public BigDecimal getPayGroupid() { return paygroupId; } public void setPayGroupid(BigDecimal paygroupId) { this.paygroupId = paygroupId; } @Column(name = "UUID", length = 64) public String getUuid() { return uuid; } public void setUuid(String uuid) { this.uuid = uuid; } } 请教各位大神,,我运行时候报错 org.springframework.orm.hibernate4.HibernateQueryException: could not resolve property: paygroupId of: com.entity.TUBill; nested exception is org.hibernate.QueryException: could not resolve property: paygroupId of: com.entity.TUBill 这个是因为我实体映射写错了吗?还是因为数据库中的类型和实体里面的类型没匹配上?这个怎么解决啊,求指教啊~~~~~~

@valid或者@validated怎么验证list中的元素

我想用@valid校验一个请求的参数,发现如果是list或者是数组,就会不校验里面的元素,如下。如果不是list或者数组,就可以。 @RequestMapping(method = RequestMethod.POST, value = "/helloBean") public String helloBean(@RequestBody @Validated List<User> u) { System.out.println("id是---"+u.get(0).getId()); System.out.println("name是---"+u.get(0).getName()); System.out.println("email是---"+u.get(0).getEmail()); /*System.out.println("======================="); System.out.println(ValidatorUtil.validate(u)); System.out.println("=======================");*/ return"Hello Bean!"; } 查了网上,发现@Valid只有在这个注解写在成员变量上,才会去llist里面校验,比如 @Valid private User u; 后来自己自定义一个注解,发现其对list根本不起作用,求解

请教spring 3+mybatis整合出错问题

spring 3+mybatis3+spring security整合,我的包和层次结构如下:采用的是按照模块分层, 每层有dao,sevrice,web三个目录,所有的实体类放在model文件夹中 security包中,有dao,service,web三个目录,其中 SecurityDao.java @MyBatisDao public interface SecurityDao extends BaseMapper<Security> { // 获得群组usergroups对应的权限 public List<Security> getGroupResources(); } SecurityService.java接口 ``` public interface SecurityService extends BaseService<Security> { public List<Security> getGroupResources(); } ``` SecurityServiceImpl .java @Service(value = "securityService") public class SecurityServiceImpl implements SecurityService { @Autowired private SecurityDao securityDao; // 获得群组usergroups对应的权限 public List<Security> getGroupResources() { return securityDao.getGroupResources(); } } MyBatisDao.java ``` /** * 标识MyBatis的DAO,方便{@link org.mybatis.spring.mapper.MapperScannerConfigurer}的扫描。 * */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) @Documented @Component public @interface MyBatisDao { /** * The value may indicate a suggestion for a logical component name, * to be turned into a Spring bean in case of an autodetected component. * @return the suggested component name, if any */ String value() default ""; } ``` 然后系统有一个model的包,存放各模块的实体类这里有security.java,get/set就省略 了, 然后在maven的resource下建立文件src\resource\mappings\modules\security\SecurityDao.xml ``` <mapper namespace="com.liao.modules.core.security.dao.SecurityDao"> <resultMap id="getUserInfoMap" type="Security"> <result property="userid" column="userid"/> <result property="username" column="username"/> <result property="password" column="password"/> <result property="enabled" column="enabled"/> </resultMap> <select id="getGroupResources" resultType="Security"> select g.role_name roleName,a.url resourceValue from usergroups g join groupauthority_mapping ga on g.groupid=ga.groupid join authority a on ga.authorityid=a.authorityid </select> ``` spring-mvc.xml: ``` <!-- 自动扫描bean,把作了注解的类转换为bean --> <context:component-scan base-package="com.liao" > <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/> </context:component-scan> ``` 其他mvc配置省略 spring-context-application.xml: ``` <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <!-- 自动匹配Mapper映射文件 --> <property name="mapperLocations" value="classpath:mappings/**/*.xml"/> <property name="typeAliasesPackage" value="com.liao.model"/> <property name="configLocation" value="classpath:/mybatis-config.xml"></property> </bean> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.liao" /> <property name="annotationClass" value="com.itownet.isms.core.annotation.MyBatisDao"/> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" /> </bean> <!-- 事务配置 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean> ``` mybatis-config.xml: ``` <configuration> <!-- 全局参数 --> <settings> <!-- 使全局的映射器启用或禁用缓存。 --> <setting name="cacheEnabled" value="true"/> <!-- 全局启用或禁用延迟加载。当禁用时,所有关联对象都会即时加载。 --> <setting name="lazyLoadingEnabled" value="true"/> <!-- 当启用时,有延迟加载属性的对象在被调用时将会完全加载任意属性。否则,每种属性将会按需要加载。 --> <setting name="aggressiveLazyLoading" value="true"/> <!-- 是否允许单条sql 返回多个数据集 (取决于驱动的兼容性) default:true --> <setting name="multipleResultSetsEnabled" value="true"/> <!-- 是否可以使用列的别名 (取决于驱动的兼容性) default:true --> <setting name="useColumnLabel" value="true"/> <!-- 允许JDBC 生成主键。需要驱动器支持。如果设为了true,这个设置将强制使用被生成的主键,有一些驱动器不兼容不过仍然可以执行。 default:false --> <setting name="useGeneratedKeys" value="false"/> <!-- 指定 MyBatis 如何自动映射 数据基表的列 NONE:不隐射 PARTIAL:部分 FULL:全部 --> <setting name="autoMappingBehavior" value="PARTIAL"/> <!-- 这是默认的执行类型 (SIMPLE: 简单; REUSE: 执行器可能重复使用prepared statements语句;BATCH: 执行器可以重复执行语句和批量更新) --> <setting name="defaultExecutorType" value="SIMPLE"/> <!-- 使用驼峰命名法转换字段。 --> <setting name="mapUnderscoreToCamelCase" value="true"/> <!-- 设置本地缓存范围 session:就会有数据的共享 statement:语句范围 (这样就不会有数据的共享 ) defalut:session --> <setting name="localCacheScope" value="SESSION"/> <!-- 设置但JDBC类型为空时,某些驱动程序 要指定值,default:OTHER,插入空值时不需要指定类型 --> <setting name="jdbcTypeForNull" value="NULL"/> </settings> ``` 在spring secrutiy中,调用 ``` public class DefinitionSourceFactoryBean implements FilterInvocationSecurityMetadataSource { @Autowired private SecurityService securityService; public void findResources() { List<Security> resourcesgroup = securityService.getGroupResources(); } } ``` 这个时候在运行securityService.getGroupResources();,说: mybatis,Invalid bound statement (not found): com.liao.core.security.dao.SecurityDao.getGroupResources 编译后,已经检查过,maoper.xml在web-inf\classes目录下了,为什么呢?

springMVC form 表单提交错误,类型转换错误

1、我用form表单提交表单,偶尔会报类型转换的错误,一直找不到原因,并不是每次都这样,偶尔几天出一个。 2、我不是直接提交的表单,使用的是easyui的form提交,因为可以回调。 3、我的form表单,设置了 <form method="post" id="peopleInfo" enctype="multipart/form-data"> 下面是我的部分代码和错误,请教各位了 四月 04, 2018 8:29:53 上午 org.apache.catalina.core.StandardWrapperValve invoke 严重: Servlet.service() for servlet [SpringMVC] in context with path [/XMGL] threw exception [Request processing failed; nested exception is org.springframework.beans.ConversionNotSupportedException: Failed to convert value of type 'java.lang.String' to required type 'org.springframework.web.multipart.commons.CommonsMultipartFile'; nested exception is java.lang.IllegalStateException: Cannot convert value of type [java.lang.String] to required type [org.springframework.web.multipart.commons.CommonsMultipartFile]: no matching editors or conversion strategy found] with root cause java.lang.IllegalStateException: Cannot convert value of type [java.lang.String] to required type [org.springframework.web.multipart.commons.CommonsMultipartFile]: no matching editors or conversion strategy found at org.springframework.beans.TypeConverterDelegate.convertIfNecessary(TypeConverterDelegate.java:287) at org.springframework.beans.TypeConverterDelegate.convertIfNecessary(TypeConverterDelegate.java:107) at org.springframework.beans.TypeConverterSupport.doConvert(TypeConverterSupport.java:64) at org.springframework.beans.TypeConverterSupport.convertIfNecessary(TypeConverterSupport.java:47) at org.springframework.validation.DataBinder.convertIfNecessary(DataBinder.java:603) at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.resolveRequestParam(HandlerMethodInvoker.java:519) at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.resolveHandlerArguments(HandlerMethodInvoker.java:352) at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:172) at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:446) at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:434) at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:959) at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893) at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:966) at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:868) at javax.servlet.http.HttpServlet.service(HttpServlet.java:650) at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:842) at javax.servlet.http.HttpServlet.service(HttpServlet.java:731) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208) at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208) at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:85) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:218) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:110) at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:506) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:169) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103) at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:962) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:445) at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1115) at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:637) at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.doRun(AprEndpoint.java:2549) at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:2538) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) at java.lang.Thread.run(Thread.java:748) ``` ``` ``` ```

基于springmvc+mybatis的登录表单提交后404

前端填写正确的用户名和密码后,提交登录,浏览器显示404,前端提交的地址是/userlogin,后端对接的/user/userlogin也是对的,浏览器f12里显示请求的确成功传给了后端,但是不知道为什么404。用的是tomcat8.5,java版本1.8,phpstudy最新版,mysql5.7.26。 ## 这是所用到的包: ![图片说明](https://img-ask.csdn.net/upload/202002/01/1580567617_880785.jpg) ## 这是目录结构: ![图片说明](https://img-ask.csdn.net/upload/202002/01/1580567511_223692.jpg) ## 这是web.xml: ```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"> <display-name>springmvc_test</display-name> <welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <!-- 配置spring监听器 --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- 加载spring配置文件 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath*:config/context-config.xml</param-value> </context-param> <!-- 配置前端控制器 --> <servlet> <servlet-name>springmvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <!-- DispatcherServlet在初始化方法里面会读取该初始化参数的值来获得 spring配置文件的位置 ,然后启动spring容器。 --> <param-name>contextConfigLocation</param-name> <param-value>classpath*:config/springmvc-config.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <!-- 配置字符编码 --> <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> </filter> <filter-mapping> <filter-name>encodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app> ``` ## 这是context-config.xml: ```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: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.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!-- 扫描service包下的注解 --> <context:component-scan base-package="com.test.service"></context:component-scan> <!-- 配置数据库 --> <!-- 加载配置文件 --> <!-- <context:property-placeholder location="classpath:jdbc.properties"/> --> <bean id="dateSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="driver" value="com.mysql.jdbc.Driver"></property> <property name="url" value="jdbc:mysql://localhost:3306/Eday_Test"></property> <property name="username" value="root"></property> <property name="password" value="123456"></property> </bean> <!-- 配置Sqlsessionfactory并将数据源注入 --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <!-- 引入数据源 --> <property name="dateSource" ref="dateSource"></property> <!-- 载入mybatis配置文件 --> <property name="configLocation" value="classpath:mybatis-config.xml"></property> <!-- 载入配置mapper映射的xml --> <property name="mapperLocations" value="classpath:com/test/mapper/*.xml"></property> </bean> <!-- 配置扫描mapper接口 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackge" value="com.test.mapper"></property> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property> </bean> <!-- 配置事务管理器 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dateSource" ref="dateSource"></property> </bean> <tx:annotation-driven transaction-manager="transactionManager"/> </beans> ``` ## 这是mybatis-config.xml: ```xml <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <typeAliases> <!-- 配置别名 --> <typeAlias alias="User" type="com.test.pojo.User"/> </typeAliases> </configuration> ``` ## 这是springmvc-config.xml: ```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: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 http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"> <!-- 扫描controller包下的注解 --> <context:component-scan base-package="com.test.controller"></context:component-scan> <!-- 开启注解 --> <mvc:annotation-driven></mvc:annotation-driven> <!-- 静态资源访问 --> <mvc:default-servlet-handler/> <!-- 视图解析器 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <!-- 配置试图解析的默认路径,即配置页面的根路径 --> <property name="prefix" value="/"></property> <property name="suffix" value=".jsp"></property> </bean> </beans> ``` ## 这是UserController.java: ```java package com.test.controller; import javax.servlet.http.HttpSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; import com.test.pojo.User; import com.test.service.UserService; //声明控制器 @Controller //设置bean的scope属性为多例(prototype) @Scope("prototype") //设置请求映射,当客户端请求/user时,转到该控制器处理 @RequestMapping("/user") public class UserController { @Autowired private UserService userService; @RequestMapping(value="/userlogin") public ModelAndView login(String user_Name,String user_pwd,ModelAndView mv,HttpSession session){ //调用userService中的login方法处理user实体类对象 User user = userService.login(user_Name,user_pwd); //登录的逻辑判断,判断条件是返回结果不为空 if(user!=null){ //登陆成功,将user对象设置到HttpSession作用范围域中,相当于服务端的cookie,有效时间默认30分钟 //在程序运行期间,在任意页面都可以提取它的值。 session.setAttribute("user",user); //转发到main请求 //登录成功,跳转页面 mv.setViewName("login/login-success"); }else{ //登录失败,向前端传递失败信息 mv.addObject("message","用户名或密码错误,请重新输入!"); //登录失败,跳转到登录页面 mv.setViewName("login"); } return mv; } //跳转到用户注册界面 @RequestMapping(value="/userregister"/*,method=RequestMethod.POST*/) public String register(User user){ String user_Name = user.getUser_Name(); //如果数据库中没有该用户,可以注册,否则跳转页面 if(userService.findByUserName(user_Name)==null){ //添加用户 userService.register(user); //注册成功,跳转到主页面 return "index"; }else{ //注册失败,跳转到错误页面 return "error"; } } } ``` ## 这是UserMapper.java: ```java package com.test.mapper; import org.apache.ibatis.annotations.Param; import com.test.pojo.User; public interface UserMapper { //根据用户名和密码查找,mybatis中有多个参数时,需要使用@Param注解 User findByUserNameAndPassword(@Param("user_Name")String user_Name,@Param("user_Pwd")String user_Pwd); //增加用户 void addUser(User user); //根据用户名查询 User findByUserName(String user_Name); } ``` ## 这是UserMapper.xml: ```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="com.tes.mapper.UserMapper"> <!-- 根据用户名和密码查询 --> <select id="findByUserNameAndPasssword" resultType="User"> select * from user where user_Name=#{user_Name} and user_Pwd=#{user_Pwd} </select> <!-- 增加用户 --> <insert id="addUser" parameterType="User"> insert into user (user_Name,user_Pwd,user_Email,user_NickName,user_Birth,user_Phone,user_InvitationCode) values(#{user_Name},#{user_Pwd},#{user_Email},#{user_NickName},#{user_Birth},#{user_Phone},#{user_InvitationCode}) </insert> <!-- 根据用户名查询 --> <select id="findByUserName" resultType="User"> select * from user where user_Name=#{user_Name} </select> </mapper> ``` ## 这是User.java: ```java package com.test.pojo; import java.sql.Timestamp; public class User { private int user_Id; private String user_Name; private int user_Pwd; private String user_Email; private String user_NickName; private Timestamp user_Time; private String user_Birth; private int user_Fans; private int user_Follow; private int user_Score; private String user_HeadImgAddr; private int user_Phone; private String user_InvitationCode; public int getUser_Id() { return user_Id; } public void setUser_Id(int user_Id) { this.user_Id = user_Id; } public String getUser_Name() { return user_Name; } public void setUser_Name(String user_Name) { this.user_Name = user_Name; } public int getUser_Pwd() { return user_Pwd; } public void setUser_Pwd(int user_Pwd) { this.user_Pwd = user_Pwd; } public String getUser_Email() { return user_Email; } public void setUser_Email(String user_Email) { this.user_Email = user_Email; } public String getUser_NickName() { return user_NickName; } public void setUser_NickName(String user_NickName) { this.user_NickName = user_NickName; } public Timestamp getUser_Time() { return user_Time; } public void setUser_Time(Timestamp user_Time) { this.user_Time = user_Time; } public String getUser_Birth() { return user_Birth; } public void setUser_Birth(String user_Birth) { this.user_Birth = user_Birth; } public int getUser_Fans() { return user_Fans; } public void setUser_Fans(int user_Fans) { this.user_Fans = user_Fans; } public int getUser_Follow() { return user_Follow; } public void setUser_Follow(int user_Follow) { this.user_Follow = user_Follow; } public int getUser_Score() { return user_Score; } public void setUser_Score(int user_Score) { this.user_Score = user_Score; } public String getUser_HeadImgAddr() { return user_HeadImgAddr; } public void setUser_HeadImgAddr(String user_HeadImgAddr) { this.user_HeadImgAddr = user_HeadImgAddr; } public int getUser_Phone() { return user_Phone; } public void setUser_Phone(int user_Phone) { this.user_Phone = user_Phone; } public String getUser_InvitationCode() { return user_InvitationCode; } public void setUser_InvitationCode(String user_InvitationCode) { this.user_InvitationCode = user_InvitationCode; } @Override public String toString() { return "User [user_Id=" + user_Id + ", user_Name=" + user_Name + ", user_Pwd=" + user_Pwd + ", user_Email=" + user_Email + ", user_NickName=" + user_NickName + ", user_Time=" + user_Time + ", user_Birth=" + user_Birth + ", user_Fans=" + user_Fans + ", user_Follow=" + user_Follow + ", user_Score=" + user_Score + ", user_HeadImgAddr=" + user_HeadImgAddr + ", user_Phone=" + user_Phone + ", user_InvitationCode=" + user_InvitationCode + "]"; } } ``` ## 这是UserService.java: ```java package com.test.service; import com.test.pojo.User; public interface UserService { //通过用户名及密码核查用户登录 User login(String user_Name,String user_Pwd); //增加用户 void register(User user); //根据用户名查询 User findByUserName(String user); } ``` ## 这是UserServiceImpl.java: ```java package com.test.service.impl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.test.mapper.UserMapper; import com.test.pojo.User; import com.test.service.UserService; @Service @Transactional public class UserServiceImpl implements UserService { //注入UserMapper接口 @Autowired private UserMapper userMapper; //登录,根据用户名和密码进行查询 @Override public User login(String user_Name,String user_Pwd){ return userMapper.findByUserNameAndPassword(user_Name,user_Pwd); } //注册,增加用户 @Override public void register(User user){ userMapper.addUser(user); } //根据用户名查询 @Override public User findByUserName(String user_Name){ return userMapper.findByUserName(user_Name); } } ``` ##这是login.jsp ```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"> <link rel="stylesheet" type="text/css" href="../css/login.css" /> <title>登录</title> </head> <body> <!--导航栏--> <nav class="nav"> <ul> <li class="logo"><a href="#">Eday</a></li> <li class="shouye"><a href="../index.jsp" class="neirong">首页</a></li> <li class="fgx">|</li> <li><a href="#" class="neirong">文章列表</a></li> <li class="fgx">|</li> <li><a href="#" class="neirong">留言板</a></li> <li class="fgx">|</li> <li><a href="#" class="neirong">更新日志</a></li> </ul> </nav> <!--登录板块--> <header class="header"> <p class="logintitle"> <b>登录</b> </p> <form action="${pageContext.request.contextPath }/user/userlogin" method="post" class=login-form> <p class= login-username-p> <label for="username" class="login-username-text">用户名:</label> <input type=text name="user_Name" class="login-username-input"> <br><a href="register.jsp" class=login-register>注册</a> </p> <p class="login-psw-p"> <label for="psw" class="login-psw-text">密码:</label> <input type=password name="user_Pwd" class="login-psw-input"> <br><a href="#" class=login-forget>忘记密码</a> </p> <div class=login-button-div> <label for=button></label> <button type=sublim class=login-button>登录</button> </div> </form> </header> </body> </html> ``` ## 这是login-success.jsp: ```jsp <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>登录成功,请等待跳转...</title> <script type="text/javascript"> onload=function(){ setInterval(go, 1000); }; var x=3; //利用了全局变量来执行 function go(){ x--; if(x>0){ document.getElementById("sp").innerHTML=x; //每次设置的x的值都不一样了。 }else{ location.href='../index.jsp'; } } </script> </head> <body> <!--导航栏--> <nav class="nav"> <ul> <li class="logo"><a href="#">Eday</a></li> <li class="shouye"><a href="../index.jsp" class="neirong">首页</a></li> <li class="fgx">|</li> <li><a href="#" class="neirong">文章列表</a></li> <li class="fgx">|</li> <li><a href="#" class="neirong">留言板</a></li> <li class="fgx">|</li> <li><a href="#" class="neirong">更新日志</a></li> </ul> </nav> <header> <div> <p>登录成功!页面将在3秒后自动跳转,请稍等...</p> </div> </header> </body> </html> ``` ## 这是数据库: ![图片说明](https://img-ask.csdn.net/upload/202002/01/1580568589_694404.jpg)

spring2.5.6 hibernate3.3.2 annotation无法持久化entity

请教一下各位: <br /> <br />试了一下spring2.5.6 MVC + hibernate3.3.2的annotation组合,在持久化实体时,没有报错,日志也显示调用到了相应的操作,但是数据库中却没有数据...,不知道是哪里有问题<img src="/images/smiles/icon_sad.gif"/> ,代码如下: <br /> <br /><strong>applicationContext.xml</strong> <br /><pre name="code" class="java"> &lt;context:property-placeholder location="classpath:jdbc.properties"/&gt; &lt;bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close"&gt; &lt;property name="driverClass" value="${jdbc.driverClassName}"/&gt; &lt;property name="jdbcUrl" value="${jdbc.url}"/&gt; &lt;property name="user" value="${jdbc.username}"/&gt; &lt;property name="password" value="${jdbc.password}"/&gt; &lt;property name="minPoolSize"&gt;&lt;value&gt;10&lt;/value&gt;&lt;/property&gt; &lt;property name="maxPoolSize"&gt;&lt;value&gt;100&lt;/value&gt;&lt;/property&gt; &lt;property name="maxIdleTime"&gt;&lt;value&gt;1800&lt;/value&gt;&lt;/property&gt; &lt;property name="acquireIncrement"&gt;&lt;value&gt;2&lt;/value&gt;&lt;/property&gt; &lt;property name="maxStatements"&gt;&lt;value&gt;100&lt;/value&gt;&lt;/property&gt; &lt;property name="initialPoolSize"&gt;&lt;value&gt;10&lt;/value&gt;&lt;/property&gt; &lt;property name="idleConnectionTestPeriod"&gt;&lt;value&gt;1800&lt;/value&gt;&lt;/property&gt; &lt;property name="acquireRetryAttempts"&gt;&lt;value&gt;30&lt;/value&gt;&lt;/property&gt; &lt;property name="breakAfterAcquireFailure"&gt;&lt;value&gt;true&lt;/value&gt;&lt;/property&gt; &lt;property name="testConnectionOnCheckout"&gt;&lt;value&gt;false&lt;/value&gt;&lt;/property&gt; &lt;/bean&gt; &lt;bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"&gt; &lt;property name="dataSource" ref="dataSource"&gt;&lt;/property&gt; &lt;property name="annotatedClasses"&gt; &lt;list&gt; &lt;value&gt;com.zy.sa.test.entity.Userinfo&lt;/value&gt; &lt;/list&gt; &lt;/property&gt; &lt;!-- &lt;property name="packagesToScan" value="com.zy.sa.test.entity.*" /&gt; --&gt; &lt;property name="hibernateProperties"&gt; &lt;props&gt; &lt;prop key="hibernate.connection.provider_class"&gt;com.mchange.v2.c3p0.ComboPooledDataSource&lt;/prop&gt; &lt;prop key="hibernate.dialect"&gt;${hibernate_dialect}&lt;/prop&gt; &lt;prop key="hibernate.show_sql"&gt;${hibernate_show_sql}&lt;/prop&gt; &lt;prop key="hibernate.format_sql"&gt;true&lt;/prop&gt; &lt;prop key="hibernate.transcation.flush_before_completion"&gt;true&lt;/prop&gt; &lt;prop key="hibernate.generate_statistics"&gt;true&lt;/prop&gt; &lt;prop key="hibernate.connection.release_mode"&gt;auto&lt;/prop&gt; &lt;prop key="hibernate.autoReconnect"&gt;true&lt;/prop&gt; &lt;prop key="hibernate.bytecode.use_reflection_optimizer"&gt;true&lt;/prop&gt; &lt;/props&gt; &lt;/property&gt; &lt;/bean&gt; &lt;bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager" p:sessionFactory-ref="sessionFactory"/&gt; &lt;!-- 支持 @Transactional --&gt; &lt;tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true" /&gt; </pre> <br /> <br /><strong>annomvc-servlet.xml</strong> <br /><pre name="code" class="java"> &lt;!-- 对web包中的所有类进行扫描,以完成Bean创建和自动依赖注入的功能 --&gt; &lt;context:component-scan base-package="com.zy.sa.test" /&gt; &lt;context:annotation-config/&gt; &lt;!-- 启动Spring MVC的注解功能,完成请求和注解POJO的映射 --&gt; &lt;bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" /&gt; &lt;!-- 对模型视图名称的解析,即在模型视图名称添加前后缀 --&gt; &lt;bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" p:prefix="/WEB-INF/jsp/" p:suffix=".jsp" /&gt;</pre> <br /> <br /><strong>web.xml</strong> <br /> <br /><pre name="code" class="java">&lt;!-- Spring 服务层的配置文件 --&gt; &lt;context-param&gt; &lt;param-name&gt;contextConfigLocation&lt;/param-name&gt; &lt;param-value&gt;/WEB-INF/applicationContext.xml&lt;/param-value&gt; &lt;/context-param&gt; &lt;!-- 日志配置 --&gt; &lt;context-param&gt; &lt;param-name&gt;log4jConfigLocation&lt;/param-name&gt; &lt;param-value&gt;/WEF-INF/classes/log4j.properties&lt;/param-value&gt; &lt;/context-param&gt; &lt;!-- Spring 容器启动监听器 --&gt; &lt;listener&gt; &lt;listener-class&gt;org.springframework.web.context.ContextLoaderListener&lt;/listener-class&gt; &lt;/listener&gt; &lt;!-- 要负责处理由JavaBeans Introspector的使用而引起的缓冲泄露 --&gt; &lt;listener&gt; &lt;listener-class&gt;org.springframework.web.util.IntrospectorCleanupListener&lt;/listener-class&gt; &lt;/listener&gt; &lt;!-- 编码 --&gt; &lt;filter&gt; &lt;filter-name&gt;encodingFilter&lt;/filter-name&gt; &lt;filter-class&gt;org.springframework.web.filter.CharacterEncodingFilter&lt;/filter-class&gt; &lt;init-param&gt; &lt;param-name&gt;encoding&lt;/param-name&gt; &lt;param-value&gt;UTF-8&lt;/param-value&gt; &lt;/init-param&gt; &lt;init-param&gt; &lt;param-name&gt;forceEncoding&lt;/param-name&gt; &lt;param-value&gt;true&lt;/param-value&gt; &lt;/init-param&gt; &lt;/filter&gt; &lt;!-- Hibernate Open Session In View --&gt; &lt;filter&gt; &lt;filter-name&gt;hibernateFilter&lt;/filter-name&gt; &lt;filter-class&gt;org.springframework.orm.hibernate3.support.OpenSessionInViewFilter&lt;/filter-class&gt; &lt;/filter&gt; &lt;!-- Hibernate Open Session In View --&gt; &lt;filter-mapping&gt; &lt;filter-name&gt;hibernateFilter&lt;/filter-name&gt; &lt;url-pattern&gt;/*&lt;/url-pattern&gt; &lt;/filter-mapping&gt; &lt;!-- 编码 --&gt; &lt;filter-mapping&gt; &lt;filter-name&gt;encodingFilter&lt;/filter-name&gt; &lt;url-pattern&gt;*.jsp&lt;/url-pattern&gt; &lt;/filter-mapping&gt; &lt;!-- Spring MVC 的Servlet,它将加载WEB-INF/annomvc-servlet.xml 的配置文件,以启动Spring MVC模块--&gt; &lt;servlet&gt; &lt;servlet-name&gt;annomvc&lt;/servlet-name&gt; &lt;servlet-class&gt;org.springframework.web.servlet.DispatcherServlet&lt;/servlet-class&gt; &lt;load-on-startup&gt;2&lt;/load-on-startup&gt; &lt;/servlet&gt; &lt;servlet-mapping&gt; &lt;servlet-name&gt;annomvc&lt;/servlet-name&gt; &lt;url-pattern&gt;*.do&lt;/url-pattern&gt; &lt;/servlet-mapping&gt; &lt;welcome-file-list&gt; &lt;welcome-file&gt;index.html&lt;/welcome-file&gt; &lt;welcome-file&gt;index.htm&lt;/welcome-file&gt; &lt;welcome-file&gt;index.jsp&lt;/welcome-file&gt; &lt;welcome-file&gt;default.html&lt;/welcome-file&gt; &lt;welcome-file&gt;default.htm&lt;/welcome-file&gt; &lt;welcome-file&gt;default.jsp&lt;/welcome-file&gt; &lt;/welcome-file-list&gt; &lt;error-page&gt; &lt;exception-type&gt;java.lang.Exception&lt;/exception-type&gt; &lt;location&gt;/WEB-INF/common/uncaughtException.jsp&lt;/location&gt; &lt;/error-page&gt; &lt;error-page&gt; &lt;error-code&gt;403&lt;/error-code&gt; &lt;location&gt;/WEB-INF/common/403.jsp&lt;/location&gt; &lt;/error-page&gt; &lt;error-page&gt; &lt;error-code&gt;404&lt;/error-code&gt; &lt;location&gt;/WEB-INF/common/404.jsp&lt;/location&gt; &lt;/error-page&gt; &lt;error-page&gt; &lt;error-code&gt;500&lt;/error-code&gt; &lt;location&gt;/WEB-INF/common/500.jsp&lt;/location&gt; &lt;/error-page&gt;</pre> <br /> <br /><strong>MyController.java</strong> <br /> <br /><pre name="code" class="java">@Controller @RequestMapping("/my.do") public class MyController { @Autowired private UserinfoService userinfoService; @RequestMapping public String my(Userinfo user) { System.out.println("my.do"); System.out.println("userinfoService: " + userinfoService); System.out.println(user); userinfoService.createUserInfo(user); return "userinfo_create"; } }</pre> <br /> <br /> <br /><strong>UserinfoServiceImpl.java</strong> <br /> <br /><pre name="code" class="java">@Service @Transactional public class UserinfoServiceImpl implements UserinfoService { @Autowired private UserinfoDao userinfoDao; @Override @Transactional(readOnly=false, propagation=Propagation.REQUIRED) public void createUserInfo(Userinfo user) { Userinfo userinfo = new Userinfo(); userinfo.setId("ww"); userinfo.setUserName("wangwu"); userinfo.setPassword("111"); userinfo.setEmail("ww@aaa.com"); userinfoDao.save(userinfo); userinfoDao.getSession().save(userinfo); } @Override @Transactional(readOnly=true) public List&lt;Userinfo&gt; getAllUser() { return userinfoDao.getAll(); }</pre> <br /> <br /><strong>UserinfoDao.java</strong> <br /><pre name="code" class="java">@Repository public class UserinfoDao extends HibernateDao&lt;Userinfo, String&gt; { @Override @Autowired public void setSessionFactory(SessionFactory sessionFactory) { logger.info("sessionFactory: " + sessionFactory); super.setSessionFactory(sessionFactory); } }</pre> <br /> <br /><strong>HibernateDao.java</strong> <br /> <br /><pre name="code" class="java"> public Session getSession() { return sessionFactory.getCurrentSession(); } public void save(final T entity) { Assert.notNull(entity, "entity不能为空"); getSession().saveOrUpdate(entity); logger.debug("save entity: {}", entity); } </pre> <br /> <br />通过:http://localhost:8080/springannotation/my.do?id=lisi&amp;userName=ls&amp;password=111&amp;email=ls@aaa.com访问,控制台打印出了实体信息,但数据库无数据,不知道问题出在哪里?<img src="/images/smiles/icon_razz.gif"/> <br/><strong>问题补充</strong><br/>没人帮忙看一下啊 <br />

springBoot使用注解注入失败

**useMapper的xml文件** ``` <mapper namespace="com.auto.dao.UserMapper"> <select id="findByName" parameterType="String" resultType="User"> select * from t_user where username=#{username} </select> </mapper> ``` **mapper接口代码** ``` public interface UserMapper { public User findByName(String username); } ``` **springboot启动类的代码** ``` @SpringBootApplication @MapperScan("com.auto.dao") public class App { public static void main(String[] args) { SpringApplication.run(App.class,args); } } ``` **pom.xml文件配置** ``` <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.10.RELEASE</version> </parent> <groupId>com.auto</groupId> <artifactId>MavenDay01</artifactId> <version>0.0.1-SNAPSHOT</version> <properties> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <!-- spirngBoot启动器 --> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <!-- jstl --> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> </dependency> <dependency> <groupId>org.apache.tomcat.embed</groupId> <artifactId>tomcat-embed-jasper</artifactId> </dependency> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.3.1</version> </dependency> ``` **user的实体类** ``` @Repository public class User { private String username; private String password; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } @Override public String toString() { return "User [username=" + username + ", password=" + password + "]"; } } ``` **这是properties的配置文件** ``` spring.datasource.driverClassName=com.mysql.jdbc.Driver spring.datasource.url=jdbc:mysql://localhost:3306/mysql spring.datasource.username=root spring.datasource.password=123456 spring.datasource.type=com.alibaba.druid.pool.DruidDataSource mybatis.type-aliases-package=com.auto.entity 实体类和mapper.xml文件都在这包里面 server.port=9090 spring.mvc.view.prefix=/WEB-INF/jsp/ spring.mvc.view.suffix=.jsp ``` **我写了个service接口,然后写了个实现类重写findByName方法返回userMapper中方法,在实现类中注入了userMapper接口,这里无法使用@Autowired注入** ``` @Service @Transactional public class UserServiceImpl implements UserService{ @Resource UserMapper userMapper; @Override public User findByName(String username) { return userMapper.findByName(username); } } ``` **报错** ``` org.apache.ibatis.binding.BindingException: Invalid bound statement (not found): com.auto.dao.UserMapper.findByName ``` 总是报找不到接口,加上注解标记也没用,换成在接口上用@mapper注解也不行,是什么问题,我在网上看说有什么依赖包冲突问题,但我换了几个版本也不行; **问题已经解决:** 问题出在没有在properties文件中添加mapper.xml文件的扫描路径 解决办法:在properties文件中加上 mybatis.mapper-locations=com/.../.../*.xml 这里是mapper.xml文件的路径

Spring集成Hibernate,使用JPA注解方式,新增数据无法提交

<div class="iteye-blog-content-contain" style="font-size: 14px;"> <p>环境:</p> <p style="padding-left: 60px;">spring 3.1</p> <p style="padding-left: 60px;">hibernate 4.2.8 final </p> <p style="padding-left: 60px;">mysql 5.6</p> <p>问题描述:</p> <p style="padding-left: 30px;">调用controller的查询方法,可以正常返回数据</p> <p style="padding-left: 30px;">调用controller的创建方法,即:新增数据,控制台打印出了读取和修改序号表的sql,但是没有打印插入数据的sql,数据库表中也没有新增数据。</p> <p style="padding-left: 30px;">怀疑是spring控制的事务没有提交,但是排查了两三天,从网上找了各种方法,都没有解决问题。</p> <p style="padding-left: 30px;">请各位大侠拉小弟一把,实在是找不到事务为什么没有提交。</p> <p> </p> <p style="padding-left: 30px;">web.xml</p> <p style="padding-left: 30px;"> </p> <pre name="code" class="xml">&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;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="WebApp_ID" version="2.5"&gt; &lt;!-- 欢迎界面 --&gt; &lt;welcome-file-list&gt; &lt;welcome-file&gt;index.html&lt;/welcome-file&gt; &lt;/welcome-file-list&gt; &lt;!-- spring框架 --&gt; &lt;listener&gt; &lt;listener-class&gt;org.springframework.web.context.ContextLoaderListener&lt;/listener-class&gt; &lt;/listener&gt; &lt;!-- 上下文配置 --&gt; &lt;context-param&gt; &lt;param-name&gt;contextConfigLocation&lt;/param-name&gt; &lt;param-value&gt; /WEB-INF/applicationContext.xml, /WEB-INF/config/**/*.xml &lt;/param-value&gt; &lt;/context-param&gt; &lt;!-- spring mvc --&gt; &lt;servlet&gt; &lt;servlet-name&gt;dispatcher&lt;/servlet-name&gt; &lt;servlet-class&gt;org.springframework.web.servlet.DispatcherServlet&lt;/servlet-class&gt; &lt;load-on-startup&gt;1&lt;/load-on-startup&gt; &lt;/servlet&gt; &lt;servlet-mapping&gt; &lt;servlet-name&gt;dispatcher&lt;/servlet-name&gt; &lt;!-- 拦截所有url --&gt; &lt;url-pattern&gt;/&lt;/url-pattern&gt; &lt;/servlet-mapping&gt; &lt;!-- 回话有效期30分钟 --&gt; &lt;session-config&gt; &lt;session-timeout&gt;30&lt;/session-timeout&gt; &lt;/session-config&gt; &lt;!-- log4j日志 --&gt; &lt;listener&gt; &lt;listener-class&gt;org.springframework.web.util.Log4jConfigListener&lt;/listener-class&gt; &lt;/listener&gt; &lt;!-- log4j日志配置 --&gt; &lt;context-param&gt; &lt;param-name&gt;log4jConfigLocation&lt;/param-name&gt; &lt;param-value&gt;/WEB-INF/properties/log4j.properties&lt;/param-value&gt; &lt;/context-param&gt; &lt;/web-app&gt;</pre> <p> applicationContext.xml</p> <p> </p> <p style="padding-left: 30px;"> </p> <pre name="code" class="xml">&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:p="http://www.springframework.org/schema/p" 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-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-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/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"&gt; &lt;!-- 注解配置 --&gt; &lt;context:annotation-config /&gt; &lt;!--允许使用注解方式配置事务 --&gt; &lt;tx:annotation-driven transaction-manager="transactionManager" /&gt; &lt;!-- 自动扫描的包名 --&gt; &lt;context:component-scan base-package="com.lxl" /&gt; &lt;!-- 对标注@PersistenceContext的类经行增强,引入代理后的EntityManager实例 --&gt; &lt;bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" /&gt; &lt;!-- 对标注@Repository的类经行增强,将EntityManager异常转换为SpringDAO体系的异常 --&gt; &lt;bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" /&gt; &lt;!-- 属性文件 --&gt; &lt;context:property-placeholder location="/WEB-INF/properties/**/*.properties" /&gt; &lt;!-- 数据源 --&gt; &lt;bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"&gt; &lt;property name="driverClassName" value="${jdbc.driverClassName}" /&gt; &lt;property name="url" value="${jdbc.url}" /&gt; &lt;property name="username" value="${jdbc.username}" /&gt; &lt;property name="password" value="${jdbc.password}" /&gt; &lt;/bean&gt; &lt;!-- JPA 实体管理工厂 --&gt; &lt;bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"&gt; &lt;property name="persistenceXmlLocation" value="classpath:META-INF/persistence.xml" /&gt; &lt;property name="dataSource" ref="dataSource" /&gt; &lt;property name="persistenceUnitName" value="ServicePlatform" /&gt; &lt;property name="jpaVendorAdapter"&gt; &lt;bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"&gt; &lt;property name="showSql" value="true" /&gt; &lt;property name="generateDdl" value="true" /&gt; &lt;property name="databasePlatform" value="org.hibernate.dialect.MySQL5Dialect" /&gt; &lt;/bean&gt; &lt;/property&gt; &lt;/bean&gt; &lt;!-- JPA 事务管理 --&gt; &lt;bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"&gt; &lt;property name="dataSource" ref="dataSource" /&gt; &lt;property name="entityManagerFactory" ref="entityManagerFactory" /&gt; &lt;/bean&gt; &lt;/beans&gt;</pre> <p> dispatcher-servlet.xml</p> <p> </p> <p style="padding-left: 30px;"> </p> <pre name="code" class="xml">&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:p="http://www.springframework.org/schema/p" 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-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-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/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"&gt; &lt;!-- 默认的注解映射的支持 --&gt; &lt;mvc:annotation-driven /&gt; &lt;!-- 自动扫描的包名 --&gt; &lt;context:component-scan base-package="com.lxl" /&gt; &lt;!-- 配置一下对json数据的转换 &lt;bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"&gt; &lt;property name="messageConverters"&gt; &lt;list&gt; &lt;bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"&gt;&lt;/bean&gt; &lt;/list&gt; &lt;/property&gt; &lt;/bean&gt; --&gt; &lt;!-- 视图解析器 --&gt; &lt;bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"&gt; &lt;property name="prefix" value="/view" /&gt; &lt;property name="suffix" value=".jsp" /&gt; &lt;/bean&gt; &lt;!-- 对静态资源文件的访问 方案一 (二选一) --&gt; &lt;mvc:default-servlet-handler /&gt; &lt;!-- 对静态资源文件的访问 方案二 (二选一) &lt;mvc:resources mapping="/images/**" location="/images/" cache-period="31556926"/&gt; &lt;mvc:resources mapping="/js/**" location="/js/" cache-period="31556926"/&gt; &lt;mvc:resources mapping="/css/**" location="/css/" cache-period="31556926"/&gt; --&gt; &lt;/beans&gt;</pre> <p> </p> <p> </p> <p style="padding-left: 30px;">persistence.xml</p> <p style="padding-left: 30px;"> </p> <pre name="code" class="xml">&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd"&gt; &lt;persistence-unit name="ServicePlatform" transaction-type="RESOURCE_LOCAL"&gt; &lt;/persistence-unit&gt; &lt;/persistence&gt; </pre> <p> </p> <p> </p> <p style="padding-left: 30px;">实体bean</p> <p style="padding-left: 30px;"> </p> <pre name="code" class="java">package com.lxl.bsp.identity.entity; import java.io.Serializable; import java.sql.Timestamp; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name = "bd_id") public class Identity implements Serializable { private static final long serialVersionUID = -8763611811485844772L; @Id @GeneratedValue(strategy = GenerationType.TABLE) private Long id; @Column(length = 100) private String code; private Long value; @Column(length = 10) private String prefix; @Column(length = 10) private String suffix; @Column(length = 255) private String description; private Integer length; @Column(length = 30) private String creator; @Column(name = "create_date") private Timestamp createDate; @Column(length = 30) private String modifier; @Column(name = "modify_Date") private Timestamp modifyDate; private Boolean dr; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } public Long getValue() { return value; } public void setValue(Long value) { this.value = value; } public String getPrefix() { return prefix; } public void setPrefix(String prefix) { this.prefix = prefix; } public String getSuffix() { return suffix; } public void setSuffix(String suffix) { this.suffix = suffix; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public Integer getLength() { return length; } public void setLength(Integer length) { this.length = length; } public String getCreator() { return creator; } public void setCreator(String creator) { this.creator = creator; } public Timestamp getCreateDate() { return createDate; } public void setCreateDate(Timestamp createDate) { this.createDate = createDate; } public String getModifier() { return modifier; } public void setModifier(String modifier) { this.modifier = modifier; } public Timestamp getModifyDate() { return modifyDate; } public void setModifyDate(Timestamp modifyDate) { this.modifyDate = modifyDate; } public Boolean getDr() { return dr; } public void setDr(Boolean dr) { this.dr = dr; } @Override public String toString() { return "Identity [id=" + id + ", code=" + code + ", value=" + value + ", prefix=" + prefix + ", suffix=" + suffix + ", description=" + description + ", length=" + length + ", creator=" + creator + ", createDate=" + createDate + ", modifier=" + modifier + ", modifyDate=" + modifyDate + ", dr=" + dr + "]"; } } </pre> <p> </p> <p> </p> <p style="padding-left: 30px;">IdentityDaoImpl.java</p> <p style="padding-left: 30px;"> </p> <pre name="code" class="java">package com.lxl.bsp.identity.dao; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import com.lxl.bsp.api.exception.ServicePlatformException; import com.lxl.bsp.identity.entity.Identity; @Repository public class IdentityDaoImpl implements IIdentityDao { @PersistenceContext private EntityManager em; @Transactional(propagation = Propagation.REQUIRED) public Identity create(Identity data) { em.persist(data); return data; } @Override public Identity retriver(String id) throws ServicePlatformException { Long pk = Long.valueOf(id); return em.find(Identity.class, pk); } @Override public Identity update(Identity data) throws ServicePlatformException { em.persist(data); return data; } @Override public void delete(String id) throws ServicePlatformException { em.remove(retriver(id)); } } </pre> <p> IdentityController.java</p> <p> </p> <p style="padding-left: 30px;"> </p> <pre name="code" class="java">package com.lxl.bsp.identity.controller; import java.sql.Timestamp; import java.util.Calendar; import javax.annotation.Resource; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import com.lxl.bsp.api.exception.ServicePlatformException; import com.lxl.bsp.identity.dao.IIdentityDao; import com.lxl.bsp.identity.entity.Identity; @Controller @RequestMapping("identity") public class IdentityController { private static Log log = LogFactory.getLog(IdentityController.class); @Resource private IIdentityDao dao; @RequestMapping("retriver") @ResponseBody public Identity retriver(@RequestParam String id) throws ServicePlatformException { return dao.retriver(id); } @RequestMapping("create") @ResponseBody public Identity create() throws ServicePlatformException { int i = 1; Identity data = new Identity(); data.setCode("code" + i); Calendar c = Calendar.getInstance(); data.setCreateDate(new Timestamp(c.getTime().getTime())); data.setCreator("creator" + i); data.setDescription("description" + i); data.setDr(false); // data.setId("id" + Integer.toString(i)); data.setLength(30); data.setModifier("modifier" + i); data.setModifyDate(new Timestamp(c.getTime().getTime())); data.setPrefix("prefix"); data.setSuffix("suffix"); data.setValue(0L); Identity returnData = dao.create(data); log.debug(returnData); return returnData; } @RequestMapping("update") @ResponseBody public Identity update() throws ServicePlatformException { int i = 1; Identity data = new Identity(); data.setCode("1"); Calendar c = Calendar.getInstance(); data.setCreateDate(new Timestamp(c.getTime().getTime())); data.setCreator("creator" + i); data.setDescription("description" + i); data.setDr(false); // data.setId("id" + Integer.toString(i)); data.setLength(30); data.setModifier("modifier" + i); data.setModifyDate(new Timestamp(c.getTime().getTime())); data.setPrefix("prefix"); data.setSuffix("suffix"); data.setValue(0L); Identity returnData = dao.update(data); log.debug(returnData); return returnData; } @RequestMapping("delete") public void delete(@RequestParam String id) throws ServicePlatformException { dao.delete(id); } } </pre> <p> </p> <p> </p> <p style="padding-left: 30px;">数据表结构DDL</p> <p style="padding-left: 30px;"> </p> <pre name="code" class="sql">-- ---------------------------- -- Table structure for bd_id -- ---------------------------- DROP TABLE IF EXISTS `bd_id`; CREATE TABLE `bd_id` ( `id` bigint(30) NOT NULL, `code` varchar(100) DEFAULT NULL, `create_date` datetime DEFAULT NULL, `creator` varchar(30) DEFAULT NULL, `description` varchar(255) DEFAULT NULL, `dr` tinyint(1) DEFAULT NULL, `length` int(11) DEFAULT NULL, `modifier` varchar(30) DEFAULT NULL, `modify_Date` datetime DEFAULT NULL, `prefix` varchar(10) DEFAULT NULL, `suffix` varchar(10) DEFAULT NULL, `value` bigint(20) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8;</pre> <p> </p> <p> </p> <p style="padding-left: 30px;">附件中是项目压缩包,只要电脑上安装了数据库,解压即可运行,数据库名称是osd</p> <p> </p> </div>

网上下载的项目-导入ssm小米商城的后台项目访问登录界面login的时候无法跳转到其他页面是怎么回事?

在网上下载的ssm小米商城的后台项目 1:项目没有错误,,, 2:在访问登录界面login的时候- 却无法跳转到其他页面 3:数据库不知道是不是正常 4:我的数据库设置了管理员登录:admin 密码123456 5: 写了个generatorConfig.xml 6:::新增:看到有人回复说数据库的名字没有改: 我用的是mysql 数据库名是:shop 密码是:1234 userId我不知道是要赋值什么值,,一般不是userName吗??但是这个项目中的确实userId ,,所以我也给他 赋值了数据库的用户名 “root”但是这样配置根本就没有用,,同样无法跳转页面:::: 如果配置错了,,麻烦指出来,,非常感谢,,新手新手,,实力有限抱歉 求大神帮助,,,呜呜,,还是跳转不了 数据库图片: ![图片说明](https://img-ask.csdn.net/upload/201812/26/1545786449_770158.png) 数据库配置图: ![图片说明](https://img-ask.csdn.net/upload/201812/26/1545786860_325497.png) 按照网友提出的问题:修改数据库名和密码: 我把connectionURL 的 work_attendance也改成了shop,, 如下: //connectionURL="jdbc:mysql://localhost:3306/work_attendance" connectionURL="jdbc:mysql://localhost:3306/shop" <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://localhost:3306/shop" userId="root" password="1234"> </jdbcConnection> 但是还是没有用,,,依然无法跳转,,总感觉没有错误,,,不知道错在哪了。。。。,,,,大神,,大神们求帮助中 代码如下: <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN" "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd" > <generatorConfiguration> <!--classPathEntry:数据库的JDBC驱动 --> <!-- location="D:\Develop\MvnRepo\mysql\mysql-connector-java\5.1.34\mysql-connector-java-5.1.34.jar"/> --> <classPathEntry location="D:\Users\lydia\workspaceSSH\shopCMS\src\main\webapp\WEB-INF\lib\mysql-connector-java-5.1.34.jar"/> <context id="MysqlTables" targetRuntime="MyBatis3"> <!-- 注意这里面的顺序确定的,不能随变更改 --> <!-- 自定义的分页插件 <plugin type="com.deppon.foss.module.helloworld.shared.PaginationPlugin"/> --> <!-- 可选的(0 or 1) --> <!-- 注释生成器 --> <commentGenerator> <!-- 是否去除自动生成的注释 true:是 : false:否 --> <property name="suppressAllComments" value="true"/> </commentGenerator> <!-- 必须的(1 required) --> <!--数据库连接的信息:驱动类、连接地址、用户名、密码 connectionURL="jdbc:mysql://localhost:3306/work_attendance" --> <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://localhost:3306/shop" userId="root" password="1234"> </jdbcConnection> ,, 登录界面 ![图片说明](https://img-ask.csdn.net/upload/201812/24/1545659180_616623.jpg) 每次一点击登录: console界面就显示: [DEBUG][2018-12-24 21:47:08] org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:845) DispatcherServlet with name 'SpringMVC' processing POST request for [/shopCMS/login/check] [DEBUG][2018-12-24 21:47:08] org.springframework.web.servlet.handler.AbstractHandlerMethodMapping.getHandlerInternal(AbstractHandlerMethodMapping.java:297) Looking up handler method for path /login/check [DEBUG][2018-12-24 21:47:08] org.springframework.web.servlet.handler.AbstractHandlerMethodMapping.getHandlerInternal(AbstractHandlerMethodMapping.java:302) Returning handler method [public java.lang.String com.shop.shopmanager.controller.LoginController.checkLogin(javax.servlet.http.HttpServletRequest) throws java.io.UnsupportedEncodingException,java.security.NoSuchAlgorithmException] [DEBUG][2018-12-24 21:47:08] org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:248) Returning cached instance of singleton bean 'loginController' [DEBUG][2018-12-24 21:47:08] org.mybatis.spring.SqlSessionUtils.getSqlSession(SqlSessionUtils.java:104) Creating a new SqlSession [DEBUG][2018-12-24 21:47:08] org.mybatis.spring.SqlSessionUtils.getSqlSession(SqlSessionUtils.java:140) SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@7738ee46] was not registered for synchronization because synchronization is not active [DEBUG][2018-12-24 21:47:08] org.springframework.jdbc.datasource.DataSourceUtils.doGetConnection(DataSourceUtils.java:110) Fetching JDBC Connection from DataSource [DEBUG][2018-12-24 21:47:08] org.mybatis.spring.transaction.SpringManagedTransaction.openConnection(SpringManagedTransaction.java:86) JDBC Connection [com.alibaba.druid.proxy.jdbc.ConnectionProxyImpl@41131e6d] will not be managed by Spring [DEBUG][2018-12-24 21:47:08] org.apache.ibatis.logging.jdbc.BaseJdbcLogger.debug(BaseJdbcLogger.java:139) ==> Preparing: SELECT cu.user_id AS user_id4, login_name, login_password, salt, user_name, real_name, sex, age, pic_img, cu.`status` AS status4, email, telephone, cu.create_time AS create_time4, cu.update_time AS update_time4, cr.role_id AS role_id2, role_name, role_sign, is_system, cr.`status` AS status2, cr.create_time AS create_time2, cr.update_time AS update_time2, cr.remarks AS remarks2, cm.menu_id AS menu_id1, parent_id, menu_type, menu_code, menu_name, sort, href, icon, cm.`status` AS status1, permission, cm.create_time AS create_time1, cm.update_time AS update_time1, cm.remarks AS remarks1 FROM cms_menu cm, cms_role cr, cms_role_menu crm, cms_user cu, cms_user_role cur WHERE crm.role_id = cr.role_id AND crm.menu_id = cm.menu_id AND cur.user_id = cu.user_id AND cur.role_id = cr.role_id AND cu.login_name = ?; [DEBUG][2018-12-24 21:47:08] org.apache.ibatis.logging.jdbc.BaseJdbcLogger.debug(BaseJdbcLogger.java:139) ==> Parameters: admin(String) [DEBUG][2018-12-24 21:47:08] org.apache.ibatis.logging.jdbc.BaseJdbcLogger.debug(BaseJdbcLogger.java:139) <== Total: 73 [DEBUG][2018-12-24 21:47:08] org.mybatis.spring.SqlSessionUtils.closeSqlSession(SqlSessionUtils.java:168) Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@7738ee46] [DEBUG][2018-12-24 21:47:08] org.springframework.jdbc.datasource.DataSourceUtils.doReleaseConnection(DataSourceUtils.java:327) Returning JDBC Connection to DataSource [DEBUG][2018-12-24 21:47:08] org.apache.shiro.realm.AuthenticatingRealm.getAuthenticationInfo(AuthenticatingRealm.java:569) Looked up AuthenticationInfo [admin] from doGetAuthenticationInfo [DEBUG][2018-12-24 21:47:08] org.apache.shiro.realm.AuthenticatingRealm.cacheAuthenticationInfoIfPossible(AuthenticatingRealm.java:507) AuthenticationInfo caching is disabled for info [admin]. Submitted token: [org.apache.shiro.authc.UsernamePasswordToken - admin, rememberMe=false]. [DEBUG][2018-12-24 21:47:08] org.mybatis.spring.SqlSessionUtils.getSqlSession(SqlSessionUtils.java:104) Creating a new SqlSession [DEBUG][2018-12-24 21:47:08] org.mybatis.spring.SqlSessionUtils.getSqlSession(SqlSessionUtils.java:140) SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@33b81d6e] was not registered for synchronization because synchronization is not active [DEBUG][2018-12-24 21:47:08] org.springframework.jdbc.datasource.DataSourceUtils.doGetConnection(DataSourceUtils.java:110) Fetching JDBC Connection from DataSource [DEBUG][2018-12-24 21:47:08] org.mybatis.spring.transaction.SpringManagedTransaction.openConnection(SpringManagedTransaction.java:86) JDBC Connection [com.alibaba.druid.proxy.jdbc.ConnectionProxyImpl@41131e6d] will not be managed by Spring [DEBUG][2018-12-24 21:47:08] org.apache.ibatis.logging.jdbc.BaseJdbcLogger.debug(BaseJdbcLogger.java:139) ==> Preparing: SELECT cu.user_id AS user_id4, login_name, login_password, salt, user_name, real_name, sex, age, pic_img, cu.`status` AS status4, email, telephone, cu.create_time AS create_time4, cu.update_time AS update_time4, cr.role_id AS role_id2, role_name, role_sign, is_system, cr.`status` AS status2, cr.create_time AS create_time2, cr.update_time AS update_time2, cr.remarks AS remarks2, cm.menu_id AS menu_id1, parent_id, menu_type, menu_code, menu_name, sort, href, icon, cm.`status` AS status1, permission, cm.create_time AS create_time1, cm.update_time AS update_time1, cm.remarks AS remarks1 FROM cms_menu cm, cms_role cr, cms_role_menu crm, cms_user cu, cms_user_role cur WHERE crm.role_id = cr.role_id AND crm.menu_id = cm.menu_id AND cur.user_id = cu.user_id AND cur.role_id = cr.role_id AND cu.login_name = ?; [DEBUG][2018-12-24 21:47:08] org.apache.ibatis.logging.jdbc.BaseJdbcLogger.debug(BaseJdbcLogger.java:139) ==> Parameters: admin(String) [DEBUG][2018-12-24 21:47:08] org.apache.ibatis.logging.jdbc.BaseJdbcLogger.debug(BaseJdbcLogger.java:139) <== Total: 73 [DEBUG][2018-12-24 21:47:08] org.mybatis.spring.SqlSessionUtils.closeSqlSession(SqlSessionUtils.java:168) Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@33b81d6e] [DEBUG][2018-12-24 21:47:08] org.springframework.jdbc.datasource.DataSourceUtils.doReleaseConnection(DataSourceUtils.java:327) Returning JDBC Connection to DataSource 原密码:123456Dts7jk 加密之后的密码为:lZQ/OoEBjTylEoEfxoyWeQ== [DEBUG][2018-12-24 21:47:08] org.apache.shiro.web.servlet.SimpleCookie.addCookieHeader(SimpleCookie.java:226) Added HttpServletResponse Cookie [rememberMe=deleteMe; Path=/shopCMS; Max-Age=0; Expires=Sun, 23-Dec-2018 13:47:08 GMT] [DEBUG][2018-12-24 21:47:08] org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdviceChain.invoke(ResponseBodyAdviceChain.java:61) Invoking ResponseBodyAdvice chain for body=login_fail [DEBUG][2018-12-24 21:47:08] org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdviceChain.invoke(ResponseBodyAdviceChain.java:83) After ResponseBodyAdvice chain body=login_fail [DEBUG][2018-12-24 21:47:08] org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodProcessor.writeWithMessageConverters(AbstractMessageConverterMethodProcessor.java:163) Written [login_fail] as "text/plain;charset=ISO-8859-1" using [org.springframework.http.converter.StringHttpMessageConverter@395cf6a4] [DEBUG][2018-12-24 21:47:08] org.springframework.web.servlet.DispatcherServlet.processDispatchResult(DispatcherServlet.java:1018) Null ModelAndView returned to DispatcherServlet with name 'SpringMVC': assuming HandlerAdapter completed request handling [DEBUG][2018-12-24 21:47:08] org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:996) Successfully completed request [DEBUG][2018-12-24 21:47:08] org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:248) Returning cached instance of singleton bean 'sqlSessionFactory' [DEBUG][2018-12-24 21:47:08] org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:845) DispatcherServlet with name 'SpringMVC' processing GET request for [/shopCMS/login] [DEBUG][2018-12-24 21:47:08] org.springframework.web.servlet.handler.AbstractHandlerMethodMapping.getHandlerInternal(AbstractHandlerMethodMapping.java:297) Looking up handler method for path /login [DEBUG][2018-12-24 21:47:08] org.springframework.web.servlet.handler.AbstractHandlerMethodMapping.getHandlerInternal(AbstractHandlerMethodMapping.java:302) Returning handler method [public java.lang.String com.shop.shopmanager.controller.LoginController.login()] [DEBUG][2018-12-24 21:47:08] org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:248) Returning cached instance of singleton bean 'loginController' [DEBUG][2018-12-24 21:47:08] org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:931) Last-Modified value for [/shopCMS/login] is: -1 [DEBUG][2018-12-24 21:47:08] org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1225) Rendering view [org.springframework.web.servlet.view.JstlView: name 'login'; URL [/WEB-INF/views/login.jsp]] in DispatcherServlet with name 'SpringMVC' [DEBUG][2018-12-24 21:47:08] org.springframework.web.servlet.view.InternalResourceView.renderMergedOutputModel(InternalResourceView.java:166) Forwarding to resource [/WEB-INF/views/login.jsp] in InternalResourceView 'login' [DEBUG][2018-12-24 21:47:08] org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:996) Successfully completed request [DEBUG][2018-12-24 21:47:08] org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:248) Returning cached instance of singleton bean 'sqlSessionFactory' ``` ``` 我的数据库中有admin和密码 123456,,但是就是无法跳转到登录后的页面希望大佬能帮我看看是什么原因》》》 ------------------------------------ 后续添加,,,,麻烦大佬结合上述和下述看看是什么问题,,拜托拜托, 1:数据库用户表信息: ![图片说明](https://img-ask.csdn.net/upload/201812/28/1545962958_570862.png) 2:我的项目结构: ![图片说明](https://img-ask.csdn.net/upload/201812/28/1545962858_134226.png) 3:以下是登录控制器“LoginController”的代码: package com.shop.shopmanager.controller; import java.io.UnsupportedEncodingException; import java.security.NoSuchAlgorithmException; import javax.servlet.http.HttpServletRequest; import org.apache.shiro.SecurityUtils; import org.apache.shiro.authc.UsernamePasswordToken; import org.apache.shiro.subject.Subject; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import com.shop.shopmanager.service.CmsUserService; /** * @Author 康健 * @Date 2017/8/14 14:54 */ @Controller @RequestMapping("login") public class LoginController { @Autowired private CmsUserService cmsUserService; /** * @Author JackWang [www.coder520.com] * @Date 2017/6/18 12:47 * @Description 登录页面 */ @RequestMapping public String login() { return "login"; } /** * @Author JackWang [www.coder520.com] * @Date 2017/6/18 12:47 * @Description 校验登录 */ @RequestMapping("/check") @ResponseBody public String checkLogin(HttpServletRequest request) throws UnsupportedEncodingException, NoSuchAlgorithmException { String username = request.getParameter("username"); String pwd = request.getParameter("password"); UsernamePasswordToken token = new UsernamePasswordToken(username, pwd); // token.setRememberMe(true); Subject subject = SecurityUtils.getSubject(); try { subject.login(token); SecurityUtils.getSubject().getSession().setTimeout(1800000); } catch (Exception e) { return "login_fail"; } return "login_succ"; } /* @RequestMapping("/register") @ResponseBody public String register(@RequestBody User user) throws UnsupportedEncodingException, NoSuchAlgorithmException { userService.createUser(user); return "succ"; }*/ } 4:UsernamePasswordToken 我没有这个类,这好像是一个方法-------网上好像说这是个认证机制,,不知道跳转不了跟这个有没有关系 网上解释:是最常见的用户名/密码的认证机制;同时,由于它实现了RememberMeAuthenticationToken接口,我们可以通过令牌设置“记住我”的功能。 但是,“已记住”和“已认证”是有区别的: 已记住的用户仅仅是非匿名用户,你可以通过subject.getPrincipals()获取用户信息。但是它并非是认证通过的用户,当你访问需要认证用户的功能时,你仍然需要重新提交认证信息。 这一区别可以参考淘宝网站,网站会默认记住登录的用户,再次访问网站时,对于非敏感的页面功能,页面上会显示记住的用户信息,但是当你访问网站账户信息时仍然需要再次进行登录认证。 5: 我的自定义数据库配置“jdbc.properties”: driverClassName=com.mysql.jdbc.Driver validationQuery=SELECT 1 jdbc_url=jdbc:mysql://localhost:3306/shop?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull&useSSL=false jdbc_username=root jdbc_password=1234 6:"generatorConfig.xml" 这个就是上面的数据库驱动的配置 <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN" "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd" > <generatorConfiguration> <!--classPathEntry:数据库的JDBC驱动 --> <!-- location="D:\Develop\MvnRepo\mysql\mysql-connector-java\5.1.34\mysql-connector-java-5.1.34.jar"/> --> <classPathEntry location="D:\Users\lydia\workspaceSSH\shopCMS\src\main\webapp\WEB-INF\lib\mysql-connector-java-5.1.34.jar"/> <context id="MysqlTables" targetRuntime="MyBatis3"> <!-- 注意这里面的顺序确定的,不能随变更改 --> <!-- 自定义的分页插件 <plugin type="com.deppon.foss.module.helloworld.shared.PaginationPlugin"/> --> <!-- 可选的(0 or 1) --> <!-- 注释生成器 --> <commentGenerator> <!-- 是否去除自动生成的注释 true:是 : false:否 --> <property name="suppressAllComments" value="true"/> </commentGenerator> <!-- 必须的(1 required) --> <!--数据库连接的信息:驱动类、连接地址、用户名、密码 connectionURL="jdbc:mysql://localhost:3306/work_attendance" --> <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://localhost:3306/shop" userId="root" password="1234"> </jdbcConnection> <!-- 可选的(0 or 1) --> <!-- 类型转换器或者加类型解析器 --> <!-- 默认false,把JDBC DECIMAL 和 NUMERIC 类型解析为 Integer true,把JDBC DECIMAL 和 NUMERIC 类型解析为java.math.BigDecimal --> <javaTypeResolver> <property name="forceBigDecimals" value="false"/> </javaTypeResolver> <!-- 必须的(1 required) --> <!-- java模型生成器 --> <!-- targetProject:自动生成代码的位置 --> <javaModelGenerator targetPackage="com.coder520.user.entity" targetProject="D:\Develop\IDEAWorkPlace\work-attendance\src\main\java" > <!--TODO enableSubPackages:是否让schema作为包的后缀 --> <property name="enableSubPackages" value="true"/> <!-- 从数据库返回的值被清理前后的空格 --> <property name="trimStrings" value="true"/> </javaModelGenerator> <!-- 必须的(1 required) --> <!-- map xml 生成器 <sqlMapGenerator targetPackage="com.coder520.user.dao" targetProject="D:\Develop\IDEAWorkPlace\work-attendance\src\main\java"> <property name="enableSubPackages" value="true"/> </sqlMapGenerator> --> <sqlMapGenerator targetPackage="com.coder520.user.dao" targetProject="D:\Users\lydia\workspaceSSH\shopCMS\src\main\java"> <property name="enableSubPackages" value="true"/> </sqlMapGenerator> <!-- 可选的(0 or 1) --> <!-- mapper 或者就是dao接口生成器 --> <javaClientGenerator targetPackage="com.coder520.user.dao" targetProject="D:\Users\lydia\workspaceSSH\shopCMS\src\main\java" type="XMLMAPPER"> <property name="enableSubPackages" value="true"/> </javaClientGenerator> <!-- 必须的(1...N) --> <!-- pojo 实体生成器 --> <!-- tableName:用于自动生成代码的数据库表;domainObjectName:对应于数据库表的javaBean类名 --> <!-- schema即为数据库名 可不写 --> <table tableName="role" domainObjectName="Role" enableInsert="true" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"> <!-- 忽略字段 可选的(0 or 1) --> <!-- <ignoreColumn column="is_use" /> --> <!--//无论字段是什么类型,生成的类属性都是varchar。 可选的(0 or 1) 测试无效 --> <!-- <columnOverride column="city_code" jdbcType="VARCHAR" /> --> </table> <table tableName="permission" domainObjectName="Permission" enableInsert="true" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"> <!-- 忽略字段 可选的(0 or 1) --> <!-- <ignoreColumn column="is_use" /> --> <!--//无论字段是什么类型,生成的类属性都是varchar。 可选的(0 or 1) 测试无效 --> <!-- <columnOverride column="city_code" jdbcType="VARCHAR" /> --> </table> </context> </generatorConfiguration> 万分感谢大佬,,,,,帮我解决这问题我就认你当师傅,,,大佬 ,,拜托了,,,还需要什么麻烦留下言哈

在中国程序员是青春饭吗?

今年,我也32了 ,为了不给大家误导,咨询了猎头、圈内好友,以及年过35岁的几位老程序员……舍了老脸去揭人家伤疤……希望能给大家以帮助,记得帮我点赞哦。 目录: 你以为的人生 一次又一次的伤害 猎头界的真相 如何应对互联网行业的「中年危机」 一、你以为的人生 刚入行时,拿着傲人的工资,想着好好干,以为我们的人生是这样的: 等真到了那一天,你会发现,你的人生很可能是这样的: ...

再不跳槽,应届毕业生拿的都比我多了!

跳槽几乎是每个人职业生涯的一部分,很多HR说“三年两跳”已经是一个跳槽频繁与否的阈值了,可为什么市面上有很多程序员不到一年就跳槽呢?他们不担心影响履历吗? PayScale之前发布的**《员工最短任期公司排行榜》中,两家码农大厂Amazon和Google**,以1年和1.1年的员工任期中位数分列第二、第四名。 PayScale:员工最短任期公司排行榜 意外的是,任期中位数极小的这两家公司,薪资...

我以为我学懂了数据结构,直到看了这个导图才发现,我错了

数据结构与算法思维导图

数据库——玩转SQL语句(以MySQL为例)

一、前言 照着大学的SQL server来学

技术大佬:我去,你写的 switch 语句也太老土了吧

昨天早上通过远程的方式 review 了两名新来同事的代码,大部分代码都写得很漂亮,严谨的同时注释也很到位,这令我非常满意。但当我看到他们当中有一个人写的 switch 语句时,还是忍不住破口大骂:“我擦,小王,你丫写的 switch 语句也太老土了吧!” 来看看小王写的代码吧,看完不要骂我装逼啊。 private static String createPlayer(PlayerTypes p...

华为初面+综合面试(Java技术面)附上面试题

华为面试整体流程大致分为笔试,性格测试,面试,综合面试,回学校等结果。笔试来说,华为的难度较中等,选择题难度和网易腾讯差不多。最后的代码题,相比下来就简单很多,一共3道题目,前2题很容易就AC,题目已经记不太清楚,不过难度确实不大。最后一题最后提交的代码过了75%的样例,一直没有发现剩下的25%可能存在什么坑。 笔试部分太久远,我就不怎么回忆了。直接将面试。 面试 如果说腾讯的面试是挥金如土...

和黑客斗争的 6 天!

互联网公司工作,很难避免不和黑客们打交道,我呆过的两家互联网公司,几乎每月每天每分钟都有黑客在公司网站上扫描。有的是寻找 Sql 注入的缺口,有的是寻找线上服务器可能存在的漏洞,大部分都...

讲一个程序员如何副业月赚三万的真实故事

loonggg读完需要3分钟速读仅需 1 分钟大家好,我是你们的校长。我之前讲过,这年头,只要肯动脑,肯行动,程序员凭借自己的技术,赚钱的方式还是有很多种的。仅仅靠在公司出卖自己的劳动时...

上班一个月,后悔当初着急入职的选择了

最近有个老铁,告诉我说,上班一个月,后悔当初着急入职现在公司了。他之前在美图做手机研发,今年美图那边今年也有一波组织优化调整,他是其中一个,在协商离职后,当时捉急找工作上班,因为有房贷供着,不能没有收入来源。所以匆忙选了一家公司,实际上是一个大型外包公司,主要派遣给其他手机厂商做外包项目。**当时承诺待遇还不错,所以就立马入职去上班了。但是后面入职后,发现薪酬待遇这块并不是HR所说那样,那个HR自...

总结了 150 余个神奇网站,你不来瞅瞅吗?

原博客再更新,可能就没了,之后将持续更新本篇博客。

副业收入是我做程序媛的3倍,工作外的B面人生是怎样的?

提到“程序员”,多数人脑海里首先想到的大约是:为人木讷、薪水超高、工作枯燥…… 然而,当离开工作岗位,撕去层层标签,脱下“程序员”这身外套,有的人生动又有趣,马上展现出了完全不同的A/B面人生! 不论是简单的爱好,还是正经的副业,他们都干得同样出色。偶尔,还能和程序员的特质结合,产生奇妙的“化学反应”。 @Charlotte:平日素颜示人,周末美妆博主 大家都以为程序媛也个个不修边幅,但我们也许...

MySQL数据库面试题(2020最新版)

文章目录数据库基础知识为什么要使用数据库什么是SQL?什么是MySQL?数据库三大范式是什么mysql有关权限的表都有哪几个MySQL的binlog有有几种录入格式?分别有什么区别?数据类型mysql有哪些数据类型引擎MySQL存储引擎MyISAM与InnoDB区别MyISAM索引与InnoDB索引的区别?InnoDB引擎的4大特性存储引擎选择索引什么是索引?索引有哪些优缺点?索引使用场景(重点)...

如果你是老板,你会不会踢了这样的员工?

有个好朋友ZS,是技术总监,昨天问我:“有一个老下属,跟了我很多年,做事勤勤恳恳,主动性也很好。但随着公司的发展,他的进步速度,跟不上团队的步伐了,有点...

我入职阿里后,才知道原来简历这么写

私下里,有不少读者问我:“二哥,如何才能写出一份专业的技术简历呢?我总感觉自己写的简历太烂了,所以投了无数份,都石沉大海了。”说实话,我自己好多年没有写过简历了,但我认识的一个同行,他在阿里,给我说了一些他当年写简历的方法论,我感觉太牛逼了,实在是忍不住,就分享了出来,希望能够帮助到你。 01、简历的本质 作为简历的撰写者,你必须要搞清楚一点,简历的本质是什么,它就是为了来销售你的价值主张的。往深...

程序员写出这样的代码,能不挨骂吗?

当你换槽填坑时,面对一个新的环境。能够快速熟练,上手实现业务需求是关键。但是,哪些因素会影响你快速上手呢?是原有代码写的不够好?还是注释写的不够好?昨夜...

离职半年了,老东家又发 offer,回不回?

有小伙伴问松哥这个问题,他在上海某公司,在离职了几个月后,前公司的领导联系到他,希望他能够返聘回去,他很纠结要不要回去? 俗话说好马不吃回头草,但是这个小伙伴既然感到纠结了,我觉得至少说明了两个问题:1.曾经的公司还不错;2.现在的日子也不是很如意。否则应该就不会纠结了。 老实说,松哥之前也有过类似的经历,今天就来和小伙伴们聊聊回头草到底吃不吃。 首先一个基本观点,就是离职了也没必要和老东家弄的苦...

HTTP与HTTPS的区别

面试官问HTTP与HTTPS的区别,我这样回答让他竖起大拇指!

程序员毕业去大公司好还是小公司好?

虽然大公司并不是人人都能进,但我仍建议还未毕业的同学,尽力地通过校招向大公司挤,但凡挤进去,你这一生会容易很多。 大公司哪里好?没能进大公司怎么办?答案都在这里了,记得帮我点赞哦。 目录: 技术氛围 内部晋升与跳槽 啥也没学会,公司倒闭了? 不同的人脉圈,注定会有不同的结果 没能去大厂怎么办? 一、技术氛围 纵观整个程序员技术领域,哪个在行业有所名气的大牛,不是在大厂? 而且众所...

程序员为什么千万不要瞎努力?

本文作者用对比非常鲜明的两个开发团队的故事,讲解了敏捷开发之道 —— 如果你的团队缺乏统一标准的环境,那么即使勤劳努力,不仅会极其耗时而且成果甚微,使用...

为什么程序员做外包会被瞧不起?

二哥,有个事想询问下您的意见,您觉得应届生值得去外包吗?公司虽然挺大的,中xx,但待遇感觉挺低,马上要报到,挺纠结的。

当HR压你价,说你只值7K,你该怎么回答?

当HR压你价,说你只值7K时,你可以流畅地回答,记住,是流畅,不能犹豫。 礼貌地说:“7K是吗?了解了。嗯~其实我对贵司的面试官印象很好。只不过,现在我的手头上已经有一份11K的offer。来面试,主要也是自己对贵司挺有兴趣的,所以过来看看……”(未完) 这段话主要是陪HR互诈的同时,从公司兴趣,公司职员印象上,都给予对方正面的肯定,既能提升HR的好感度,又能让谈判气氛融洽,为后面的发挥留足空间。...

面试阿里p7,被按在地上摩擦,鬼知道我经历了什么?

面试阿里p7被问到的问题(当时我只知道第一个):@Conditional是做什么的?@Conditional多个条件是什么逻辑关系?条件判断在什么时候执...

终于懂了TCP和UDP协议区别

终于懂了TCP和UDP协议区别

无代码时代来临,程序员如何保住饭碗?

编程语言层出不穷,从最初的机器语言到如今2500种以上的高级语言,程序员们大呼“学到头秃”。程序员一边面临编程语言不断推陈出新,一边面临由于许多代码已存在,程序员编写新应用程序时存在重复“搬砖”的现象。 无代码/低代码编程应运而生。无代码/低代码是一种创建应用的方法,它可以让开发者使用最少的编码知识来快速开发应用程序。开发者通过图形界面中,可视化建模来组装和配置应用程序。这样一来,开发者直...

面试了一个 31 岁程序员,让我有所触动,30岁以上的程序员该何去何从?

最近面试了一个31岁8年经验的程序猿,让我有点感慨,大龄程序猿该何去何从。

大三实习生,字节跳动面经分享,已拿Offer

说实话,自己的算法,我一个不会,太难了吧

程序员垃圾简历长什么样?

已经连续五年参加大厂校招、社招的技术面试工作,简历看的不下于万份 这篇文章会用实例告诉你,什么是差的程序员简历! 疫情快要结束了,各个公司也都开始春招了,作为即将红遍大江南北的新晋UP主,那当然要为小伙伴们做点事(手动狗头)。 就在公众号里公开征简历,义务帮大家看,并一一点评。《启舰:春招在即,义务帮大家看看简历吧》 一石激起千层浪,三天收到两百多封简历。 花光了两个星期的所有空闲时...

《C语言函数速查》main()主函数

每一个C程序都必须有一main()函数, 可以根据自己的爱好把它放在程序的某个地方。有些程序员把它放在最前面, 而另一些程序员把它放在最后面, 无论放在哪个地方, 以下几点说明都是适合的。

Java岗开发3年,公司临时抽查算法,离职后这几题我记一辈子

前几天我们公司做了一件蠢事,非常非常愚蠢的事情。我原以为从学校出来之后,除了找工作有测试外,不会有任何与考试有关的事儿。 但是,天有不测风云,公司技术总监、人事总监两位大佬突然降临到我们事业线,叫上我老大,给我们组织了一场别开生面的“考试”。 那是一个风和日丽的下午,我翘着二郎腿,左手端着一杯卡布奇诺,右手抓着我的罗技鼠标,滚动着轮轴,穿梭在头条热点之间。 “淡黄的长裙~蓬松的头发...

大牛都会用的IDEA调试技巧!!!

导读 前天面试了一个985高校的实习生,问了他平时用什么开发工具,他想也没想的说IDEA,于是我抛砖引玉的问了一下IDEA的调试用过吧,你说说怎么设置断点...

面试官:你连SSO都不懂,就别来面试了

大厂竟然要考我SSO,卧槽。

终于,月薪过5万了!

来看几个问题想不想月薪超过5万?想不想进入公司架构组?想不想成为项目组的负责人?想不想成为spring的高手,超越99%的对手?那么本文内容是你必须要掌握的。本文主要详解bean的生命...

我说我懂多线程,面试官立马给我发了offer

不小心拿了几个offer,有点烦

立即提问
相关内容推荐