请教:springmvc中controller中list如何在jsp中获得?

springmvc中controller里面应该怎写需要详细的过程

4个回答

假如后台有个list
List news = new ArrayList()
model.setAttribute("news", news);
前台jsp


/c:forEach
items填的就是后台传的那个变量, var就是list里每个变量的值

controller的方法加一个参数 model 然后将list放入model中。
一般都用 modelandview

首先,如果返回类型是ResponseBody的Object,可以转换成json数据返回给前台;
其次,如果你返回的是ModelAndView的话,就可以直接addObject添加到视图模型中,然后页面上可以直接使用el表达式获取数据。

支持@zwjapple楼上说的方法,后台在控制器controller中将list绑定model,在页面用/c:forEach标签获取,如下

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
springMVC无法进入controller的问题
springmvc一直无法进入controller导入404的问题 下帖配置文件: springmvc ``` <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd "> <mvc:annotation-driven/> <!-- 自动扫描该包,使SpringMVC认为包下用了@controller注解的类是控制器 --> <context:component-scan base-package="com.controller" /> <context:component-scan base-package="com.impl" /> invengo.warehouse.service.impl" /> <!--避免IE执行AJAX时,返回JSON出现下载文件 --> <bean id="mappingJacksonHttpMessageConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"> <property name="supportedMediaTypes"> <list> <value>text/html;charset=UTF-8</value> </list> </property> </bean> <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> <property name="messageConverters"> <list> <ref bean="mappingJacksonHttpMessageConverter" /> <!-- JSON转换器 --> </list> </property> </bean> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" /> <!-- <property name="prefix" value="/WEB-INF/jsp/" /> --> <property name="prefix" value="/WEB-INF/jsp/" /> <property name="suffix" value=".jsp" /> </bean> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!-- 默认编码 --> <property name="defaultEncoding" value="utf-8" /> <!-- 文件大小最大值 --> <property name="maxUploadSize" value="10485760000" /> <!-- 内存中的最大值 --> <property name="maxInMemorySize" value="40960" /> </bean> <context:annotation-config/> <mvc:resources location="/static/" mapping="/static/**"></mvc:resources> <!-- <mvc:resources location="" mapping=""/> --> <bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource"> <property name="basename"> <value>message</value> </property> <property name="defaultEncoding"> <value>UTF-8</value> </property> </bean> <!-- 日期全局转换配置 --> <bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean"> <property name="converters"> <list> <bean class="com.lava.springmvc.DateConverter" /> </list> </property> </bean> </beans> ``` web.xml ``` <?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0"> <!-- Spring和mybatis的配置文件 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/applicationContext-*.xml</param-value> </context-param> <!-- 使用ContextLoaderListener保证启动时加载Spring --> <listener> <listener-class> org.springframework.web.context.ContextLoaderListener </listener-class> </listener> <servlet> <servlet-name>CXFServlet</servlet-name> <servlet-class> org.apache.cxf.transport.servlet.CXFServlet </servlet-class> <load-on-startup>2</load-on-startup> </servlet> <servlet-mapping> <servlet-name>CXFServlet</servlet-name> <url-pattern>/ws/*</url-pattern> </servlet-mapping> <!-- 编码过滤器 --> <filter> <filter-name>encodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <async-supported>true</async-supported> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>encodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!-- 防止Spring内存溢出监听器 --> <listener> <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class> </listener> <!-- Spring MVC servlet --> <servlet> <servlet-name>SpringMVC</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath*:/WEB-INF/applicationContext-mvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> <async-supported>true</async-supported> </servlet> <servlet-mapping> <servlet-name>SpringMVC</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>/WEB-INF/jsp/login.jsp</welcome-file> </welcome-file-list> <session-config> <session-timeout>30</session-timeout> </session-config> </web-app> ``` 部分代码 ``` @Service("userService") public class UserServiceImpl implements IUserService{ ..... } ``` ``` @RestController public class LoginController { @RequestMapping("captcha.jpg") public void captcha(HttpServletResponse response)throws ServletException,IOException{ ...... } } ```
springMVC中jsp页面访问路径404错误?
配置如下 spring-servlet.xml <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="cache" value="true" /> <property name="prefix" value="/views/" /> <property name="suffix" value=".jsp" /> </bean> Web.xml <servlet-mapping> <servlet-name>spring</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> 我在JSP页面的路径是WebContent/views/EnterpriseInfoManag/pollutionBasInfo.jsp controller的代码是: @Controller public class PollutionBasInfoController { @Resource private PollutionBasInfoService pollutionBasInfoService; @RequestMapping("/findPollutionBasInfo.do") public @ResponseBody List<TBasEnterprise> findPollutionBasInfo(){ List<TBasEnterprise> list = pollutionBasInfoService.findPollutionBasInfo(); return list; } 我用JS访问controller: url:'findPollutionBasInfo.do' 但是地址就自动变成 http://localhost:8080/SKPWMS/views/EnterpriseInfoManag/findPollutionBasInfo.do ,访问controller的路径自动在前面加上了/views/EnterpriseInfoManag,导致404错误,求指导,为什么会这样,应该怎样解决啊???
请教下关于springmvc简单例子出错问题
警告: No mapping found for HTTP request with URI [/springmvc4/test1/helloworld] in DispatcherServlet with name 'springmvc' 运行后一直报错。 我贴下代码 各位帮我看下 web配置: <?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"> <display-name>springMVC1</display-name> <welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file>index.htm</welcome-file> <welcome-file>index.jsp</welcome-file> <welcome-file>default.html</welcome-file> <welcome-file>default.htm</welcome-file> <welcome-file>default.jsp</welcome-file> </welcome-file-list> spring-servlet.xml配置 <servlet> <servlet-name>springmvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath*:config/spring-servlet.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> </web-app> <?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.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd"> <bean name="/test1/helloworld" class="com.web.controller.HelloWorldController" /> <!-- <context:component-scan base-package="com.web.controller"/> --> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/"></property> <property name="suffix" value=".jsp"></property> </bean> </beans> ``` com.web.controller下的类: ``` package com.web.controller; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.Controller; public class HelloWorldController implements Controller{ public ModelAndView handleRequest(HttpServletRequest arg0, HttpServletResponse arg1) throws Exception { System.out.println("aasdadasd"); return new ModelAndView("/welcome"); } } ``` ```
maven springMvc 扫描不到注解controller
``` <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd"> <!-- 自动扫描该包,使SpringMVC认为包下用了@controller注解的类是控制器 --> <context:component-scan base-package="cn.com" use-default-filters="false"> <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/> <context:include-filter type="annotation" expression="org.springframework.web.bind.annotation.ControllerAdvice"/> </context:component-scan> <mvc:annotation-driven> <!--<mvc:async-support default-timeout="300000"/>--> <mvc:message-converters register-defaults="true"> <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter" /> <bean class="org.springframework.http.converter.ByteArrayHttpMessageConverter" /> <bean class="org.springframework.http.converter.StringHttpMessageConverter"> <constructor-arg value="UTF-8" /> </bean> </mvc:message-converters> </mvc:annotation-driven> <!-- 定义跳转的文件的前后缀 ,视图模式配置--> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <!-- 这里的配置我的理解是自动给后面action的方法return的字符串加上前缀和后缀,变成一个 可用的url地址 --> <property name="prefix" value="/WEB-INF/jsp/" /> <property name="suffix" value=".jsp" /> </bean> <!-- 配置文件上传,如果没有使用文件上传可以不用配置,当然如果不配,那么配置文件中也不必引入上传组件包 --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!-- 默认编码 --> <property name="defaultEncoding" value="utf-8" /> <!-- 文件大小最大值 --> <property name="maxUploadSize" value="10485760000" /> <!-- 内存中的最大值 --> <property name="maxInMemorySize" value="40960" /> </bean> </beans> ``` ``` <?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0"> <display-name>Archetype Created Web Application</display-name> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:/spring/*.xml</param-value> </context-param> <!-- 编码过滤器 --> <filter> <filter-name>encodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <async-supported>true</async-supported> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>encodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!-- Spring监听器 --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- 防止Spring内存溢出监听器 --> <listener> <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class> </listener> <!-- Spring MVC servlet --> <servlet> <servlet-name>SpringMVC</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:/spring/spring-mvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> <async-supported>true</async-supported> </servlet> <servlet-mapping> <servlet-name>SpringMVC</servlet-name> <!-- 此处可以可以配置成*.do,对应struts的后缀习惯 --> <url-pattern>/</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>/index.jsp</welcome-file> </welcome-file-list> </web-app> ``` ``` package cn.com.base.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; /** * * @author Mr.Xu * @date * */ @Controller @RequestMapping("/user") public class UserController { /** * 测试 * @author Mr.Xu * @date * @return */ @RequestMapping(value = "/goLogin", method = { RequestMethod.POST,RequestMethod.GET }) public String goUser() { return "login"; } } ```
springMVC无法访问controller,这是怎么回事啊
spring配置 ``` <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/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/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"> <!-- 开启注解扫描 --> <mvc:annotation-driven/> <mvc:default-servlet-handler/> <!-- 扫描controller和service --> <context:component-scan base-package="com.jinJi" use-default-filters="true"></context:component-scan> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!-- 以字节为单位的最大上传文件的大小 --> <property name="maxUploadSize" value="100000" /> </bean> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/jsp/"></property> <property name="suffix" value=".jsp"></property> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" /> </bean> </beans> ``` web.xml ``` <?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </context-param> <!-- 默认欢迎界面 --> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <!-- 网站编码设置为UTF-8 --> <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> <servlet-name>springmvc</servlet-name> </filter-mapping> <servlet> <servlet-name>springmvc</servlet-name> <servlet-class> org.springframework.web.servlet.DispatcherServlet </servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> </web-app> ``` Controller ``` package com.jinji.controller; import java.util.List; import java.util.Map; import javax.annotation.Resource; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import com.jinji.pojo.KeHu; import com.jinji.pojo.LiuYan; import com.jinji.pojo.YongHu; import com.jinji.pojo.ZHAOPIN; import com.jinji.service.JinJiService; @Controller @RequestMapping("/jinji") public class JinJiController { @Resource(name="jinJiService") JinJiService jinjiService ; @ResponseBody @RequestMapping("wangzhan1") public String wangzhan1(Map request){ System.out.println("wangzhan1"); return "wangzhan1"; } @RequestMapping("Liu") public String Liu(LiuYan liuyan,Map request){ jinjiService.saveLIUYAN(liuyan); return "redirect:/jinji/liuyan2.do"; } @RequestMapping("card1") public String card1(Map request){ return "card1"; } @RequestMapping("jianjie1") public String jianjie1(Map request){ List<Map> m=jinjiService.queryGong(); System.out.println(m.size()); request.put("map", jinjiService.queryGong()); return "jianjie1"; } @RequestMapping("case1") public String case1(Map request){ request.put("list", jinjiService.querykehu()); return "case"; } @RequestMapping("lianxi") public String lianxi(Map request){ return "lianxi"; } @RequestMapping("zhaopin") public String zhaopin(Map request){ request.put("list", jinjiService.queryZHAOPIN()); return "zhaopin"; } @RequestMapping("liuyan2") public String lianyan2(Map request){ request.put("RIQI", jinjiService.queryRIQI()); return "liuyan2"; } @RequestMapping("copyright1") public String copyright1(Map request){ return "copyright1"; } @RequestMapping("card2") public String card2(Map request){ return "card2"; } @RequestMapping("card3") public String card3(Map request){ return "card3"; } @RequestMapping("card4") public String card4(Map request){ return "card4"; } @RequestMapping("card5") public String card5(Map request){ return "card5"; } @RequestMapping("card6") public String card6(Map request){ return "card6"; } @RequestMapping("card7") public String card7(Map request){ return "card7"; } @RequestMapping("card8") public String card8(Map request){ return "card8"; } @RequestMapping("card9") public String card9(Map request){ return "card9"; } @RequestMapping("card10") public String card10(Map request){ return "card10"; } @RequestMapping("card11") public String card11(Map request){ return "card11"; } @RequestMapping("card12") public String card12(Map request){ return "card12"; } @RequestMapping("card13") public String card13(Map request){ return "card13"; } @RequestMapping("card14") public String card14(Map request){ return "card14"; } @RequestMapping("delu") public String delu(Map request){ return "delu/delu"; } @RequestMapping("guanli") public String guanli(Map request){ return "houtai/guanli"; } @RequestMapping("show") public String show(Map request){ request.put("list", jinjiService.queryguanli()); return "houtai/show"; } @RequestMapping("nav") public String nav(Map request){ request.put("list", jinjiService.queryZHAOPIN()); return "houtai/nav"; } @RequestMapping("page") public String page(Map request){ request.put("list", jinjiService.queryliuyan()); return "houtai/page"; } @RequestMapping("system") public String system(Map request){ request.put("list", jinjiService.querykehu()); return "houtai/system"; } @RequestMapping("gong") public String gong(Map request){ request.put("list", jinjiService.queryGong()); return "houtai/gong"; } @RequestMapping("deleteGUANLI") public String deleteGUANLI(String did,Map request){ jinjiService.deleteGUANLI(did); return "redirect:/jinji/show.do"; } @RequestMapping("deleteKehu") public String deleteKehu(String kid,Map request){ jinjiService.deleteKeHu(kid); return "redirect:/jinji/system.do"; } @RequestMapping("deleteGong") public String deleteGong(String gid,Map request){ jinjiService.deleteGong(gid); return "redirect:/jinji/gong.do"; } @RequestMapping("deletZHAOPIN") public String deleteZHAOPIN(String zid,Map request){ jinjiService.deleteZhaoPin(zid); return "redirect:/jinji/nav.do"; } @RequestMapping("deletLiuYan") public String deleteLiuYan(String lid,Map request){ jinjiService.deleteLiuYan(lid); return "redirect:/jinji/page.do"; } @RequestMapping("saveGUANLI") public String saveGUANLI(YongHu yonghu,Map request){ jinjiService.savaGuanLi(yonghu); return "redirect:/jinji/show.do"; } @RequestMapping("saveKeHu") public String saveKeHu(KeHu kehu,Map request){ jinjiService.savaKeHu(kehu); return "redirect:/jinji/system.do"; } @RequestMapping("saveZHAOPIN") public String saveZHAOPIN(ZHAOPIN zhaopin,Map request){ jinjiService.savaZHAOPIN(zhaopin); return "redirect:/jinji/nav.do"; } @RequestMapping("saveGong") public String saveGong(String gong,Map request){ jinjiService.saveGong(gong); return "redirect:/jinji/gong.do"; } @RequestMapping(value = "denglu", method = RequestMethod.POST) public String denglu(String USERNAME,String PASSWORD,Map request){ List<Map> list = jinjiService.denglu(USERNAME,PASSWORD); if(list.size()==1){ return "redirect:/jinji/guanli.do"; }else{ return "delu/delu"; } } } ```
springmvc+mybatis调用controller报autowired失败
@service、@controller都写了,@service也写在了实现类而不是接口上,controller中autowired标在了set方法上,单元测试中service和serviceImpl没有问题,但页面调用controller却宝座autowired失败找不到对应service网上找了很多问题我都没有,大概是我检查不够仔细?求大神帮助 添加了一下spring配置和web.xml 异常信息: ``` org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'loginController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire method: public void controller.LoginController.setLoginService(service.LoginService); nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [service.LoginService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {} ``` controller ``` @Controller("loginController") @RequestMapping("/User") @Component public class LoginController { private LoginService loginService; public LoginService getLoginService() { return loginService; } @Autowired @Qualifier("loginService") public void setLoginService(LoginService loginService) { this.loginService = loginService; } @RequestMapping(value = "/Login",method=RequestMethod.POST) public String userLogin(HttpSession session,@RequestParam("userid") String userid, @RequestParam("password") String password, @RequestParam("perflg") int perflg,Model model ) { User user = loginService.Login(userid, password, perflg); if (loginService.Login(userid, password, perflg) != null) { session.setAttribute("userid", user.getUserId()); session.setAttribute("username",user.getUserName()); session.setAttribute("permission", user.getPermission()); session.removeAttribute("nologin"); if (perflg == 0) { return "adminhome"; } if (perflg == 1) { return "goverhome"; } if (perflg == 2) { return "compahome"; } if (perflg == 3) { return "consehome"; } if (perflg == 4) { return "peoplehome"; } } model.addAttribute("Lb_alert", "用户名或密码不正确"); session.setAttribute("nologin", "你还没有登陆."); return "forward:/Login"; } } ``` serviceimpl: ``` @Service("loginService") @Transactional @Component public class LoginServiceImpl implements LoginService { private LoginMapper loginMapper; public LoginMapper getLoginMapper() { return loginMapper; } @Autowired public void setLoginMapper(LoginMapper loginMapper) { this.loginMapper = loginMapper; } @Override public User Login(String userid, String password, int perflg){ return loginMapper.Login(userid, password, perflg); } } ``` service ``` public interface LoginService { public User Login(String userid,String password,int perflg); } ``` spring.xml ``` <!-- 引入属性文件 --> <context:property-placeholder location="classpath:mysqldb.properties" /> <!-- 自动注入 --> <context:component-scan base-package="service" /> <!-- 加载properties文件 --> <!-- <bean id="configProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean"> <property name="locations"> <list> <value>classpath:mysqldb.properties</value> </list> </property> </bean> --> ``` spring-mvc.xml ``` <!-- 自动扫描controller包下的所有类,使其认为spring mvc的控制器 --> <context:component-scan base-package="controller" /> <!-- 配置静态资源吗,直接映射到对应的文件夹,不被DispatcherServlet处理,需要重新spring-mvc-3.0.xsd --> <mvc:resources mapping="/images/**" location="/images/" /> <mvc:resources mapping="/js/**" location="/js/" /> <mvc:resources mapping="/css/**" location="/css/" /> <!-- 对转向页面的路径解析。prefix:前缀, suffix:后缀 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" p:prefix="/" p:suffix=".jsp" /> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="defaultEncoding"> <value>UTF-8</value> </property> <property name="maxUploadSize"> <value>32505856</value><!-- 上传文件 大小限制为31M,31*1024*1024 --> </property> <property name="maxInMemorySize"> <value>4096</value> </property> </bean> ``` spring-mybatis.xml ``` <!-- 配置数据源 --> <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"> <!-- 基本属性 url、user、password --> <property name="driverClassName" value="com.mysql.jdbc.Driver" /> <property name="url" value="jdbc:mysql://localhost:3306/electric" /> <property name="username" value="root" /> <property name="password" value="root" /> <property name="initialSize" value="1" /> <property name="minIdle" value="1" /> <property name="maxActive" value="20" /> <property name="maxWait" value="60000" /> <!-- 超过时间限制是否回收 --> <property name="removeAbandoned" value="true" /> <!-- 超过时间限制多长; --> <property name="removeAbandonedTimeout" value="180" /> <!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 --> <property name="timeBetweenEvictionRunsMillis" value="60000" /> <!-- 配置一个连接在池中最小生存的时间,单位是毫秒 --> <property name="minEvictableIdleTimeMillis" value="300000" /> <!-- 用来检测连接是否有效的sql,要求是一个查询语句--> <property name="validationQuery" value="SELECT 1" /> <!-- 申请连接的时候检测 --> <property name="testWhileIdle" value="true" /> <!-- 申请连接时执行validationQuery检测连接是否有效,配置为true会降低性能 --> <property name="testOnBorrow" value="false" /> <!-- 归还连接时执行validationQuery检测连接是否有效,配置为true会降低性能 --> <property name="testOnReturn" value="false" /> </bean> <!-- Mybatis文件 --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <!-- 映射文件路径 --> <property name="mapperLocations" value="classpath:mapping/*.xml" /> </bean> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="mapper" /> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" /> </bean> <!-- 事务管理器 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean> ``` web.xml ``` <display-name>Archetype Created Web Application</display-name> <!-- Spring和mybatis的配置文件 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring.xml,classpath:spring-mybatis.xml</param-value> </context-param> <!-- spring mvc servlet --> <servlet> <description>spring mvc servlet</description> <servlet-name>springMvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <description>spring mvc 配置文件</description> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring-mvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>springMvc</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>/index.jsp</welcome-file> </welcome-file-list> <!-- 配置session超时时间,单位分钟 --> <session-config> <session-timeout>15</session-timeout> </session-config> ```
为什么SpringMVC会将整个jsp页面作为字符串响应
SpringMVC的相关配置: <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/views/" /> <property name="suffix" value=".jsp" /> <property name="contentType" value="text/html;charset=UTF-8"/> </bean> Controller: ``` @Controller @RequestMapping("/search/") public class SolrController { @Autowired private ItemSolrService service; @RequestMapping("list.html") public String itemList(ItemSolr item,Model model){ Map<String,String> params = new HashMap<String,String>(); if(item != null){ params.put("q", "title:" + item.getTitle()); } List<ItemSolr> itemList = service.queryByMap(params, ItemSolr.class); model.addAttribute("itemList", itemList); return "item_cat_list"; } } ``` 我想要的是跳转到页面将数据显示在html页面上,但实际上把整个jsp页面作为字符串响应了,如下图: ![图片说明](https://img-ask.csdn.net/upload/201707/31/1501513048_240541.png) 有没有人知道原因?求帮助
SpringMVC程序中的IllegalArgumentException
http://blog.csdn.net/sujiangchichu/article/details/16962231 抛出的的异常: [java] view plaincopyprint?在CODE上查看代码片派生到我的代码片 严重: Servlet.service() for servlet baobaotao threw exception java.lang.IllegalArgumentException at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.hibernate.property.BasicPropertyAccessor$BasicSetter.set(BasicPropertyAccessor.java:65) at org.hibernate.tuple.entity.AbstractEntityTuplizer.setPropertyValues(AbstractEntityTuplizer.java:707) at org.hibernate.tuple.entity.PojoEntityTuplizer.setPropertyValues(PojoEntityTuplizer.java:371) at org.hibernate.persister.entity.AbstractEntityPersister.setPropertyValues(AbstractEntityPersister.java:4295) at org.hibernate.engine.internal.TwoPhaseLoad.doInitializeEntity(TwoPhaseLoad.java:186) at org.hibernate.engine.internal.TwoPhaseLoad.initializeEntity(TwoPhaseLoad.java:134) at org.hibernate.loader.Loader.initializeEntitiesAndCollections(Loader.java:995) at org.hibernate.loader.Loader.doQuery(Loader.java:874) at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:289) at org.hibernate.loader.Loader.doList(Loader.java:2438) at org.hibernate.loader.Loader.doList(Loader.java:2424) at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2254) at org.hibernate.loader.Loader.list(Loader.java:2249) at org.hibernate.loader.hql.QueryLoader.list(QueryLoader.java:470) at org.hibernate.hql.internal.ast.QueryTranslatorImpl.list(QueryTranslatorImpl.java:355) at org.hibernate.engine.query.spi.HQLQueryPlan.performList(HQLQueryPlan.java:195) at org.hibernate.internal.SessionImpl.list(SessionImpl.java:1248) at org.hibernate.internal.QueryImpl.list(QueryImpl.java:101) at com.baobaotao.dao.UserDao.findUserByUserName(UserDao.java:34) at com.baobaotao.service.UserService.findUserByUserName(UserService.java:22) at com.baobaotao.web.LoginController.loginCheck(LoginController.java:35) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:176) at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:436) at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:424) at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:923) at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:852) at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:882) at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:789) at javax.servlet.http.HttpServlet.service(HttpServlet.java:637) at javax.servlet.http.HttpServlet.service(HttpServlet.java:717) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102) at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:567) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:293) at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:849) at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:583) at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:454) at java.lang.Thread.run(Thread.java:662) [java] view plaincopyprint?在CODE上查看代码片派生到我的代码片 [java] view plaincopyprint?在CODE上查看代码片派生到我的代码片 User.dao: [java] view plaincopyprint?在CODE上查看代码片派生到我的代码片 package com.baobaotao.dao; import java.util.List; import org.hibernate.Query; import org.hibernate.Transaction; import org.springframework.stereotype.Repository; import com.baobaotao.domain.User; @Repository //通过spring注解定义一个dao public class UserDao extends BaseDAO{ public int getMatchCount(String userName, String passWord){ String hql = "from User user " + " where user.userName = ? " + " and user.passWord = ? " ; Query queryObject = getSession().createQuery(hql); queryObject.setParameter(0,userName ); queryObject.setParameter(1, passWord); @SuppressWarnings("unchecked") List <User> list=queryObject.list(); return list.size(); } public User findUserByUserName(final String userName) { String hql = "from User user " + " where user.userName = ? "; Query queryObject = getSession().createQuery(hql); queryObject.setParameter(0,userName); User user=(User)queryObject.list().get(0); System.out.println(user); return user ; } public void updateLoginInfo(User user) { Transaction ts=getSession().beginTransaction(); getSession().update(user); ts.commit(); } } LoginController [java] view plaincopyprint?在CODE上查看代码片派生到我的代码片 package com.baobaotao.web; import java.util.Date; import javax.servlet.http.HttpServletRequest; 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.RequestParam; import org.springframework.web.servlet.ModelAndView; import com.baobaotao.domain.User; import com.baobaotao.service.UserService; //标注一个springmvc的Controller @Controller public class LoginController { @Autowired private UserService userService; //负责处理index.html的请求 @RequestMapping(value="/index.html") public String loginPage(){ return "login"; } //负责处理loginCheck.html的请求 @RequestMapping(value="/loginCheck.html") public ModelAndView loginCheck(HttpServletRequest request, LoginCommand loginCommand){ boolean isValidUser = userService.hasMatchUser(loginCommand.getUserName(),loginCommand.getPassword() ); if (!isValidUser) { return new ModelAndView("login", "error", "用户名或密码错误。"); } else { User user = userService.findUserByUserName(loginCommand.getUserName()); user.setLastIp(request.getLocalAddr()); System.out.println(request.getLocalAddr()); user.setLastVisit(new Date()); System.out.println(new Date()); userService.loginSuccess(user); // request.getSession().setAttribute("user", user); // return new ModelAndView("main"); ModelAndView mv = new ModelAndView(); mv.setViewName("main"); mv.addObject(user); return mv; } } } UserService [java] view plaincopyprint?在CODE上查看代码片派生到我的代码片 package com.baobaotao.service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.baobaotao.dao.LoginLogDao; import com.baobaotao.dao.UserDao; import com.baobaotao.domain.LoginLog; import com.baobaotao.domain.User; @Service //将userbean标注为一个服务层的Bean public class UserService { @Autowired private UserDao userDao; @Autowired private LoginLogDao loginLogDao; public boolean hasMatchUser(String userName, String passWord){ int matchCount = userDao.getMatchCount(userName, passWord); return matchCount>0; } public User findUserByUserName(String userName){ return userDao.findUserByUserName(userName); } public void loginSuccess(User user){ user.setCredits(5+user.getCredits()); LoginLog loginLog = new LoginLog(); loginLog.setUserId(user.getUserId()); loginLog.setIp(user.getLastIp()); loginLog.setLoginDate(user.getLastVisit()); userDao.updateLoginInfo(user); loginLogDao.insertLoginLog(loginLog); } } login.jsp [html] view plaincopyprint?在CODE上查看代码片派生到我的代码片 <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <html> <head> <title>hehe</title> </head> <body> <c:if test="${!empty error}"> <c:out value="${error}" /> </c:if> <form action="<c:url value="loginCheck.html"/>" method="post"> 用户名: <input type="text" name="userName"> 密 码: <input type="password" name="password"> <input type="submit" value="登录" /> <input type="reset" value="重置" /> </form> </body> </html> 求教,异常如何处理呢? 求教,异常如何处理呢?
springMVC怎么可以访问.do和.jsp
结果:访问.do报404错误;![图片说明](https://img-ask.csdn.net/upload/201905/06/1557130784_736858.png) 访问.jsp可以正常访问: ![图片说明](https://img-ask.csdn.net/upload/201905/06/1557130799_855496.png) 项目结构: ![图片说明](https://img-ask.csdn.net/upload/201905/06/1557131293_133479.png) 两个Controller: ![图片说明](https://img-ask.csdn.net/upload/201905/06/1557130985_851585.png) 这个返回值是json格式的。 ![图片说明](https://img-ask.csdn.net/upload/201905/06/1557131017_288476.png) web.xml ``` <?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <display-name>springmvc</display-name> <!-- Spring配置 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:bean.xml</param-value> </context-param> <!-- Bootstraps the root web application context before servlet initialization --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- DispatcherServlet配置 --> <servlet> <servlet-name>springDispatcherServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:springmvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>springDispatcherServlet</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>springDispatcherServlet</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <!-- 为了能够处理中文的post请求,再配置一个encodingFilter,以避免post请求中文出现乱码情况 --> <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> </web-app> ``` springmvc.xml ``` <context:component-scan base-package="com.web"></context:component-scan> <!-- <aop:aspectj-autoproxy proxy-target-class="true" /> --> <!-- 静态资源(js、image等)的访问 --> <mvc:default-servlet-handler /> <!-- 开启注解 --> <mvc:annotation-driven /> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/view/"></property> <property name="suffix" value=".jsp"></property> </bean> </beans> ``` bean.xml ``` <!-- 1. 数据源 --> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> 省略啦!!!! </bean> <!-- 2. Spring 对SessionFactory创建支持 --> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> <property name="dataSource" ref="dataSource"></property> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop> <prop key="hibernate.show_sql">true</prop> <prop key="hibernate.hbm2ddl.auto">update</prop> </props> </property> <property name="mappingLocations"> <list> <value>classpath:com.pojo/*.hbm.xml</value> </list> </property> </bean> <!-- 3. 事务管理 --> <!-- a. 配置事务管理器类(切面类) --> <bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory"></property> </bean> <!-- b. 事务通知 --> <tx:advice id="txAdvice" transaction-manager="txManager"> </tx:advice> <!-- c. Aop配置 --> <aop:config> <aop:pointcut expression="execution(* *Service.*(..))" id="pt" /> <aop:advisor advice-ref="txAdvice" pointcut-ref="pt" /> </aop:config> <!-- 公用的配置 abstract="true" 表示是一个抽象的bean,不会被实例化; 可以被其他bean继承,就可以省略父bean定义多的属性 --> <bean id="baseDao" abstract="true"> <property name="sessionFactory" ref="sessionFactory"></property> </bean> <!-- dao配置 --> <bean id="userDao" parent="baseDao" class="com.dao.UserDao"></bean> <!-- service配置 --> <bean id="userService" class="com.service.UserService"> <property name="userDao" ref="userDao"></property> </bean> <!-- controller配置 --> <bean id="userController" class="com.controller.UserController"> <property name="userService" ref="userService"></property> </bean> </beans> ``` 请问怎么可以访问.do和.jsp呢?
请教:Spring + Hibernate 无法将数据写入数据库?
Spring + Hibernate 无法将数据写入数据 **请教: 通过Junit单元测试Service可以将数据写入数据库;但部署访问却无法向数据库写入数据。** 1 环境: Spring 3.1.2 Hibernate 4.1.4 Jdk1.6 2 配置: 2.1 Web.xml <!-- Spring ApplicationContext配置文件的路径,可使用通配符,多个路径用,号分隔 此参数用于后面的Spring Context Loader --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath*:/applicationContext.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!--Dispathcer Servlet --> <servlet> <servlet-name>spring-mvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/spring-mvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <!-- Spring MVC Servlet 拦截.do结尾的请求--> <servlet-mapping> <servlet-name>spring-mvc</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> <!-- 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> <!--openSessionInView--> <filter> <filter-name>openSessionInView</filter-name> <filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class> <init-param> <param-name>sessionFactoryBeanName</param-name> <param-value>sessionFactory</param-value> </init-param> </filter> <filter-mapping> <filter-name>openSessionInView</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> 2.2 applicationContext.xml <!--扫描并自动装配 --> <context:annotation-config /> <context:component-scan base-package="com.sp" /> <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations"> <value>classpath:application.properties</value> </property> </bean> <!-- 数据源配置 --> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <!-- Connection Info --> <property name="driverClassName" value="${jdbc.driver}" /> <property name="url" value="${jdbc.url}" /> <property name="username" value="${jdbc.username}" /> <property name="password" value="${jdbc.password}" /> <!-- Connection Pooling Info --> <property name="maxActive" value="${dbcp.maxActive}" /> <property name="maxIdle" value="${dbcp.maxIdle}" /> <property name="defaultAutoCommit" value="false" /> <!-- 连接Idle一个小时后超时 --> <property name="timeBetweenEvictionRunsMillis" value="3600000" /> <property name="minEvictableIdleTimeMillis" value="3600000" /> </bean> <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"> <property name="dataSource" ref="dataSource"></property> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop> <prop key="hibernate.hbm2ddl.auto">update</prop> <prop key="hibernate.connection.autocommit">true</prop> <prop key="hibernate.current_session_context_class">org.springframework.orm.hibernate4.SpringSessionContext</prop> <prop key="hibernate.show_sql">true</prop> <prop key="hibernate.format_sql">true</prop> </props> </property> <property name="packagesToScan"> <list> <value>com.sp.dao</value> <value>com.sp.entity.dict</value> </list> </property> </bean> <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager" abstract="false" lazy-init="default" autowire="default"> <property name="sessionFactory"><ref bean="sessionFactory" /></property> </bean> <!-- 事务管理配置 --> <!--<tx:annotation-driven transaction-manager="transactionManager"></tx:annotation-driven>--> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="insert*" read-only="false" propagation="REQUIRED" /> <tx:method name="get*" read-only="false" propagation="REQUIRED" /> <tx:method name="add*" read-only="false" propagation="REQUIRED" /> <tx:method name="update*" read-only="false" propagation="REQUIRED" /> <tx:method name="delete*" read-only="false" propagation="REQUIRED" /> </tx:attributes> </tx:advice> <aop:config> <aop:advisor pointcut="execution(* com.sp.service.*.*(..))" advice-ref="txAdvice"/> </aop:config> </beans> 2.3 spring-mvc.xml <!-- 启动注解驱动的SpringMVC功能,注册请求URL和注解POJO类方法的映射 --> <mvc:annotation-driven /> <!-- 自动扫描且只扫描@Controller --> <context:component-scan base-package="com.sp.web" use-default-filters="false"> <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller" /> </context:component-scan> <context:component-scan base-package="com.sp.dao.impl"></context:component-scan> <context:component-scan base-package="com.sp.service.impl"></context:component-scan> <mvc:default-servlet-handler /> <!-- 对模型视图名称的解析,在请求时模型视图名称添加后缀。定义JSP --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/views/" /> <property name="suffix" value=".jsp" /> </bean> <!-- 支持上传文件 --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver" /> 2.4 hibernate.cfg.xml <property name="connection.driver_class">com.mysql.jdbc.Driver</property> <property name="connection.url">jdbc:mysql://localhost:3306/test</property> <property name="connection.username">root</property> <property name="connection.password">password</property> <!-- JDBC connection pool (use the built-in) --> <property name="connection.pool_size">1</property> <!-- SQL dialect <property name="dialect">org.hibernate.dialect.MySQLDialect</property> --> <!-- Enable Hibernate's automatic session context management --> <!-- <property name="current_session_context_class">thread</property> --> <!-- Disable the second-level cache --> <!-- <property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property>--> <!-- Echo all executed SQL to stdout --> <property name="show_sql">true</property> <property name="format_sql">true</property> <!-- Drop and re-create the database schema on startup--> <property name="hbm2ddl.auto">update</property> <property name="javax.persistence.validation.mode">none</property> 3 代码: 3.1 Service层: @Component("userService") public class UserServiceImpl implements UserService{ @Autowired private UserDao userDao; @Autowired private FormValidator validator; @Override public String userLogin(UserModel user) { String password = userDao.userLogin(user); if(password.equals(user.getPassword())){ return "sucess"; }else{ return "false"; } } @Override public List<ProjectType> getAllProjectTypes(){ List<ProjectType> projectType = userDao.getAllProjectTypes(); return projectType; } @Override public String addProjectType(@ModelAttribute("newProjectType")ProjectType projectType,BindingResult result,SessionStatus status){ validator.validate(projectType, result); if(result.hasErrors()){ return "newProjectType"; } userDao.save(projectType); //status.setComplete(); return "redirect:showProjectTypes.do"; } //添加《项目类型》 @Override public String addProjectType(ProjectType projectType) { userDao.save(projectType); return "redirect:showProjectTypes.do"; } } 3.2 Control层 @Controller @RequestMapping(value = "/user") public class UserController { @Autowired private UserService userService; @Autowired private FormValidator validator; @RequestMapping(value = "/login",method=RequestMethod.POST) protected String handle(UserModel user,BindingResult result, Model model){ String flag = userService.userLogin(user); System.out.println("flag:" + flag); if ("sucess".equals(flag)){ return "sucess"; } return "test1"; } @RequestMapping(value = "/showProjectTypes") protected ModelAndView getAllProjectTypes(){ ModelAndView mav = new ModelAndView("showProjectTypes"); List<ProjectType> projectTypes = userService.getAllProjectTypes(); mav.addObject("SEARCH_PROJECTTYPE_RESULTS_KEY", projectTypes); return mav; } @RequestMapping(value = "/addProjectType",method=RequestMethod.GET) protected ModelAndView newProjectTypeForm(){ ModelAndView mav = new ModelAndView("newProjectType"); ProjectType projectType = new ProjectType(); mav.getModelMap().put("newProjectType", projectType); return mav; } @RequestMapping(value = "/saveProjectType",method=RequestMethod.POST) protected String addProjectType(@ModelAttribute("newProjectType")ProjectType projectType,BindingResult result,SessionStatus status){ //return userService.addProjectType(projectType, result, status); return userService.addProjectType(projectType); } } 3.3 DAO层 @Component("userDao") public class UserDaoImpl implements UserDao{ @Autowired private SessionFactory sessionFactory; public ProjectType getById(int id) { return (ProjectType) sessionFactory.getCurrentSession().get(ProjectType.class, id); } @Override public String userLogin(UserModel user) { return "123456"; } //获取数据 @Override @SuppressWarnings("unchecked") public List<ProjectType> getAllProjectTypes() { Criteria ceriteria = sessionFactory.getCurrentSession().createCriteria(ProjectType.class); return ceriteria.list(); } //新增数据; @Override // @Transactional(readOnly = true, propagation = Propagation.REQUIRED) public int save(ProjectType projectType) { System.out.println("save:---"); System.out.println(projectType.getIndex()); System.out.println(projectType.getProjectType()); System.out.println(projectType.getProjectTypeAbbr()); return (Integer) sessionFactory.getCurrentSession().save(projectType); } }
springmvc中以get方式请求出现乱码问题,总是有???问号出现,求大神帮忙。
web.xml中的内容 ``` <?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <filter> <filter-name>CharacterEncoding</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>CharacterEncoding</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <servlet> <servlet-name>springmvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:mvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app> ``` Controller中的内容 ``` package cn.sxt.controller; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import cn.sxt.vo.User; @Controller public class HelloController { @RequestMapping("/hello") public String hello(String name,ModelMap model){ model.addAttribute("name",name); System.out.println(name); return "index.jsp"; } } ``` index.jsp中的内容 ``` <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% 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 'index.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> <body> ${name } <br/>欢迎访问! </body> </html> ``` tomcat7的server.xml中也加上了URIEncoding="UTF-8",还是乱码,以post表单形式提交就没问题,我的请求url地址:http://localhost:8080/07springmvc_restful/hello.do?name=张三 求大神,帮忙,多谢,多谢,多谢,多谢,多谢,多谢。
求助:ssm的maven项目tomcat插件启动成功,但是无法访问的问题!
问题描述: springmvc+mybatis项目,tomcat插件成功启动后,访问报404的错误。 个人排查: 1.将其独立部署到tomcat服务器而不用tomcat插件可以成功启动并访问。 2.tomcat插件启动成功后,target下的classes目录下面没有配置文件,但是有class文件。buildpath中已经配置输出文件夹为target/classes,仍然无效。 tomcat插件配置: ``` <plugins> <plugin> <groupId>org.apache.tomcat.maven</groupId> <artifactId>tomcat7-maven-plugin</artifactId> <version>2.2</version> <configuration> <update>true</update> <!-- 热部署 --> <charset>utf-8</charset> <!-- 设置字符集 --> <uriEncoding>UTF-8</uriEncoding><!-- 设置uri编码 --> <port>8080</port> <!-- 设置端口 --> <path>/</path><!-- 设置默认访问应用的路径 --> </configuration> </plugin> </plugins> ``` 前端控制器配置: ``` <!-- 前端控制器 --> <!-- The front controller of this Spring Web application, responsible for handling all application requests --> <servlet> <servlet-name>springDispatcherServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath*:springmvc/springmvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <!-- Map all requests to the DispatcherServlet for handling --> <servlet-mapping> <servlet-name>springDispatcherServlet</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> ``` controller: ``` @Controller public class UserController { @Autowired private UserService userService; @RequestMapping("/") public String hello() { return "index"; } @RequestMapping("/user") @ResponseBody public List<User> getUserList() { List<User> list = userService.getUserList(); return list; } } ``` 访问url:localhost:8080,正常应该跳转到index.jsp界面,实际输出:`No mapping found for HTTP request with URI [/] in DispatcherServlet with name 'springDispatcherServlet'`。 # 求助!!!
springMVC注入失败的问题
运行项目后报错,请问我配置哪里写错了? ``` ERROR [localhost-startStop-1] - Context initialization failed org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'categoryController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.how2java.service.CategoryService com.how2java.controller.CategoryController.categoryService; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'categoryService': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.how2java.mapper.CategoryMapper com.how2java.service.impl.CategoryServiceImpl.categoryMapper; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.how2java.mapper.CategoryMapper] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)} ina.core.StandardWrapper.initServlet(StandardWrapper.java:1227) ``` 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" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5"> <!-- spring的配置文件--> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- spring mvc核心:分发servlet --> <servlet> <servlet-name>mvc-dispatcher</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!-- spring mvc的配置文件 --> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:springMVC.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>mvc-dispatcher</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app> ``` springMVC.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:jdbc="http://www.springframework.org/schema/jdbc" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-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/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/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.2.xsd"> <context:annotation-config/> <context:component-scan base-package="com.how2java.controller" use-default-filters="false"> <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/> </context:component-scan> <mvc:annotation-driven /> <mvc:default-servlet-handler /> <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> ``` 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:tx="http://www.springframework.org/schema/tx" xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation=" http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-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/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName"> <value>com.mysql.jdbc.Driver</value> </property> <property name="url"> <value>jdbc:mysql://localhost:3306/test?characterEncoding=UTF-8</value> </property> <property name="username"> <value>root</value> </property> <property name="password"> <value>123456</value> </property> </bean> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean> <bean id="commonSqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="configLocation" value="classpath:elecDBConfiguration.xml" /> </bean> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="*" propagation="REQUIRED" rollback-for="java.lang.Exception" /> </tx:attributes> </tx:advice> <aop:config> <aop:pointcut id="warehouse" expression="execution (* com.how2java.service.*.*(..))" /> <aop:advisor advice-ref="txAdvice" pointcut-ref="warehouse" /> </aop:config> </beans> ``` elecDBConfiguration.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="Category" type="com.how2java.pojo.Category" /> </typeAliases> <mappers> <mapper resource="com/how2java/mapper/Category.xml"/> </mappers> </configuration> ``` java代码 ``` package com.how2java.pojo; public class Category { private int id; private String name; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() { return "Category [id=" + id + ", name=" + name + "]"; } } ``` ``` package com.how2java.service; import java.util.List; import com.how2java.pojo.Category; public interface CategoryService { List<Category> list(); } ``` ``` package com.how2java.service.impl; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.how2java.mapper.CategoryMapper; import com.how2java.pojo.Category; import com.how2java.service.CategoryService; @Service("categoryService") public class CategoryServiceImpl implements CategoryService{ @Autowired CategoryMapper categoryMapper; public List<Category> list(){ return categoryMapper.list(); }; } ``` ``` package com.how2java.controller; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; import com.how2java.pojo.Category; import com.how2java.service.CategoryService; // 告诉spring mvc这是一个控制器类 @Controller @RequestMapping("") public class CategoryController { @Autowired CategoryService categoryService; @RequestMapping("listCategory") public ModelAndView listCategory(){ ModelAndView mav = new ModelAndView(); List<Category> cs= categoryService.list(); // 放入转发参数 mav.addObject("cs", cs); // 放入jsp路径 mav.setViewName("listCategory"); return mav; } } ```
关于springMVC注解注入失败的问题
注解都写了,没发现哪有遗漏,个人认为是环境配置的问题,求解答 dao ``` package dao; import java.util.List; import org.springframework.orm.hibernate4.support.HibernateDaoSupport; import org.springframework.stereotype.Repository; import entity.Food; @Repository public class FoodDao extends HibernateDaoSupport{ ``` service ``` package Logic; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import dao.FoodDao; import entity.Food; @Service public class FoodLogic { ``` controller ``` import entity.Food; @Controller @RequestMapping("") public class AddFoodController extends AbstractController{ @RequestMapping("/list") public ModelAndView getList(HttpServletRequest request, HttpServletResponse response) { List<Food> foodlist = this.foodLogic.selectAllFood(); response.setCharacterEncoding("UTF-8"); try { PrintWriter write = response.getWriter(); write.write(getJson(foodlist)); write.flush(); write.close(); } catch (IOException e) { e.printStackTrace(); } return this.listView(); } @ResponseBody public String getJson(List list) { JSONObject jsonDate = new JSONObject(); jsonDate.put("list", list); return jsonDate.toString(); } } package Controller.foodController; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.servlet.ModelAndView; import Logic.FoodLogic; public class AbstractController { @Autowired public FoodLogic foodLogic; public ModelAndView listView() { return new ModelAndView("food/list"); } public ModelAndView editView() { return new ModelAndView("food/edit"); } public ModelAndView viewView() { return new ModelAndView("food/view"); } } ``` xml ``` <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd"> <!-- 加载Spring的全局配置文件 --> <!-- scan the package and the sub package --> <context:component-scan base-package="Controller"/> <!-- don't handle the static resource --> <mvc:default-servlet-handler /> <!-- if you use annotation you must configure following setting --> <mvc:annotation-driven /> <!-- configure the InternalResourceViewResolver --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="internalResourceViewResolver"> <!-- 前缀 --> <property name="prefix" value="/htm/" /> <!-- 后缀 --> <property name="suffix" value=".html" /> </bean> ``` web.xml ``` <?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <display-name>OrderMealManager</display-name> <!-- <welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file>index.htm</welcome-file> <welcome-file>index.jsp</welcome-file> <welcome-file>default.html</welcome-file> <welcome-file>default.htm</welcome-file> <welcome-file>default.jsp</welcome-file> </welcome-file-list> --> <!-- 监听spring上下文容器 --> <listener> <listener-class> org.springframework.web.context.ContextLoaderListener </listener-class> </listener> <!--configure the setting of springmvcDispatcherServlet and configure the mapping--> <servlet> <servlet-name>springmvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:springmvc-servlet.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> ``` 错误信息 ``` 八月 08, 2017 12:59:18 下午 org.springframework.context.support.AbstractApplicationContext refresh 警告: Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'addFoodController': Unsatisfied dependency expressed through field 'foodLogic': No qualifying bean of type [Logic.FoodLogic] found for dependency [Logic.FoodLogic]: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [Logic.FoodLogic] found for dependency [Logic.FoodLogic]: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)} 八月 08, 2017 12:59:18 下午 org.springframework.web.servlet.FrameworkServlet initServletBean 严重: Context initialization failed org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'addFoodController': Unsatisfied dependency expressed through field 'foodLogic': No qualifying bean of type [Logic.FoodLogic] found for dependency [Logic.FoodLogic]: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [Logic.FoodLogic] found for dependency [Logic.FoodLogic]: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)} ```
ssm项目springmvc中加入websocke后mybatis不能注入mapper
spring——mybatis文件 ``` <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="driverClass" value="${jdbc.driverClassName}" /> <property name="jdbcUrl" value="${jdbc.url}" /> <property name="user" value="${jdbc.username}" /> <property name="password" value="${jdbc.password}" /> <property name="autoCommitOnClose" value="true"/> <!-- property name="checkoutTimeout" value="${cpool.checkoutTimeout}"/ --> <property name="initialPoolSize" value="${cpool.initialPoolSize}"/> <property name="minPoolSize" value="${cpool.minPoolSize}"/> <property name="maxPoolSize" value="${cpool.maxPoolSize}"/> <property name="maxIdleTime" value="${cpool.maxIdleTime}"/> <property name="acquireIncrement" value="${cpool.acquireIncrement}"/> <property name="idleConnectionTestPeriod" value="${cpool.idleConnectionTestPeriod}"/> <property name="acquireRetryAttempts" value="${cpool.acquireRetryAttempts}"/> <property name="maxStatements" value="${c3p0.maxStatements}"/> <property name="maxStatementsPerConnection" value="${c3p0.maxStatementsPerConnection}"/> </bean> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <!-- mapper和resultmap配置路径 --> <property name="mapperLocations"> <list> <value>classpath:com/yuan/*/entity/*.mapper.xml</value> </list> </property> </bean> <!-- 设置扫描根路径也就是你的mybatis的mapper接口所在包路径; 凡是markerInterface这个接口的子接口都参与到这个扫描, 也就是说所有的mapper接口继承这个SqlMapper。--> <bean name="SqlMapper" class="com.yuan.framework.mapper.SqlMapper"> </bean> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.yuan.*.mapper"/> <property name="markerInterface" ref="SqlMapper" /> </bean> <!-- TransactionManager 事务管理 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean> <!--启动spring事务注解功能--> <tx:annotation-driven transaction-manager="transactionManager" /> ``` springmvc文件 ``` <mvc:annotation-driven/> <!-- <mvc:resources location="/" mapping="/**"/> --> <!-- 自动扫描controller包下的所有类,使其认为spring mvc的控制器 --> <context:component-scan base-package="com.yuan.*.controller" /> <bean id="myHandler" class="com.yuan.framework.websocket.WebsocketEndPoint"></bean> <websocket:handlers> <websocket:mapping path="/myHandler" handler="myHandler"/> <websocket:handshake-interceptors> <bean class="com.yuan.framework.websocket.HandshakeInterceptor"/> </websocket:handshake-interceptors> </websocket:handlers> <!-- <websocket:handlers > <websocket:mapping path="/sockjs/myHandler" handler="myHandler"/> <websocket:sockjs/> </websocket:handlers> --> <!-- 避免IE执行AJAX时,返回JSON出现下载文件 --> <bean id="mappingJacksonHttpMessageConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"> <property name="supportedMediaTypes"> <list> <value>text/html;charset=UTF-8</value> </list> </property> </bean> <!-- 启动Spring MVC的注解功能,完成请求和注解POJO的映射 --> <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> <property name="messageConverters"> <list> <ref bean="mappingJacksonHttpMessageConverter" /><!-- json转换器 --> </list> </property> <!-- 日期格式转换 --> <property name="webBindingInitializer"> <bean class="com.yuan.framework.util.DateConverter"/> </property> </bean> <!-- 对模型视图名称的解析,即在模型视图名称添加前后缀 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" p:prefix="/" p:suffix=".jsp" /> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="defaultEncoding"> <value>UTF-8</value> </property> <property name="maxUploadSize"> <value>32505856</value><!-- 上传文件大小限制为31M,31*1024*1024 --> </property> <property name="maxInMemorySize"> <value>4096</value> </property> </bean> ```
SpringMVC提交put,delete请求405
请求删除操作报:HTTP Status 405 - Request method 'POST' not supported 已经在web.xml配置,HiddenHttpMethodFilter过滤器 jsp页面: <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>主页面</title> <script type="text/javascript" src="js/jquery-1.8.3.min.js"></script> </head> <body> <form action="" method="post"> <input type="hidden" value="DELETE" name="_method"/> </form> <table border="1"> <tr> <th>编号</th> <th>用户名</th> <th>密码</th> <th>邮箱</th> <th>操作</th> </tr> <c:forEach items="${requestScope.list}" var="list"> <tr> <td>${list.userId}</td> <td>${list.userName}</td> <td>${list.password}</td> <td>${list.email}</td> <td> <a href="update" class="update">修改</a> <a href="user/${list.userId}" class="delete">刪除</a> </td> </tr> </c:forEach> </table> <br> <br> </body> </html> <script> $(function(){ $(".delete").click(function(){ var href=$(this).attr("href"); $("form").attr("action",href).submit(); return false; }); }); </script> SpringMVC-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-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd " default-autowire="byName"> <!-- 启用spring mvc 注解 --> <context:annotation-config /> <mvc:annotation-driven /> <!-- 处理静态资源 --> <mvc:default-servlet-handler/> <!--对模型视图名称的解析,即在模型视图名称添加前后缀 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"></property> <property name="suffix" value=".jsp"></property> </bean> <context:component-scan base-package="com.tang" /> <!-- 获取数据源 --> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver"></property> <property name="url" value="jdbc:mysql://localhost:3306/springmvc"></property> <property name="username" value="root"></property> <property name="password" value="123"> </property> </bean> <!-- 启动Spring MVC的注解功能,完成请求和注解POJO的映射 --> <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"></bean> <!-- 给jdbc模板注入数据源 --> <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> <property name="dataSource" ref="dataSource"></property> </bean> </beans> controller代码: package com.tang.controller; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import com.tang.dao.UserDao; import com.tang.pojo.User; @Controller public class LoginController { @Autowired private UserDao userDao; public void setUserDao(UserDao userDao) { this.userDao = userDao; } @ModelAttribute public void test(){ System.out.println("LoginController.test()"); } @RequestMapping("/login") public String doLogin(String username,String password,ModelMap map){ User user=userDao.doLogin(username, password); if(user!=null){ List<User> list=userDao.findAll(); map.put("list", list); return "index"; }else{ return "login"; } } @RequestMapping(value="/update",method=RequestMethod.PUT) public String doUpdate(User user,ModelMap map){ userDao.doUpdate(user); List<User> list=userDao.findAll(); map.put("list", list); return "index"; } @RequestMapping(value="/user/{id}",method=RequestMethod.DELETE) public String doDelete(@PathVariable("id")Integer id,ModelMap map){ userDao.doDelete(id); List<User> list=userDao.findAll(); map.put("list", list); return "index"; } }
SpringMvc 事务无法回滚
我模拟了一个更新和添加操作,添加一个主键重复的用户。按理说添加失败,更新就要回滚。但是事务无法回滚。网上找了好多资料,大部分都是说扫描包时applicationContext.xml和spring-mvc.xml,中包不要重复扫描,排除spring-mvc.xml扫描的Service。但是我怎么改,事务依旧无法回滚,希望大哥们帮帮我这个新手。代码如下 applicationContext.xml ``` <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.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"> <context:annotation-config/> <context:component-scan base-package="com.ali.zyh"> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/> </context:component-scan> <bean id="placeholderConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations"> <list> <value>classpath:properties/jdbc.properties</value> </list> </property> </bean> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"> <property name="url" value="${url}"/> <property name="username" value="${username}"/> <property name="password" value="${password}"/> <property name="driverClassName" value="${driverClass}"/> </bean> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource"/> <property name="mapperLocations" value="classpath:mapping/*.xml"/> </bean> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.ali.zyh.dao"/> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/> </bean> <bean name="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"/> </bean> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="add*" propagation="REQUIRED" read-only="false" /> <tx:method name="delete*" propagation="REQUIRED" read-only="false" /> <tx:method name="update*" propagation="REQUIRED" read-only="false" /> <tx:method name="save*" propagation="REQUIRED" read-only="false" rollback-for="java.lang.Exception"/> </tx:attributes> </tx:advice> <tx:annotation-driven transaction-manager="transactionManager"/> <aop:config> <aop:pointcut id="pc" expression="execution(* com.ali.zyh.service.*.*(..))"/> <aop:advisor advice-ref="txAdvice" pointcut-ref="pc"/> </aop:config> </beans> ``` spring-mvc.xml ``` <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.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"> <context:annotation-config/> <context:component-scan base-package="com.ali.zyh" > <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Service"/> </context:component-scan> <mvc:annotation-driven /> <!--避免IE执行AJAX时,返回JSON出现下载文件 --> <bean id="mappingJacksonHttpMessageConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"> <property name="supportedMediaTypes"> <list> <value>text/html;charset=UTF-8</value> </list> </property> </bean> <mvc:annotation-driven> <mvc:message-converters register-defaults="true"> <bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter"> <property name="supportedMediaTypes"> <list> <value>text/html;charset=UTF-8</value> <value>application/json</value> </list> </property> <property name="features"> <list> <value>WriteMapNullValue</value> <value>QuoteFieldNames</value> </list> </property> </bean> </mvc:message-converters> </mvc:annotation-driven> <!-- 启动SpringMVC的注解功能,完成请求和注解POJO的映射(适配器) --> <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"> <property name="messageConverters"> <list> <bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter"> <property name="supportedMediaTypes"> <list> <value>application/json;charset=UTF-8</value> <value>text/plain;charset=UTF-8</value> </list> </property> </bean> </list> </property> </bean> <!-- 定义跳转的文件的前后缀 ,视图模式配置 (视图渲染器)--> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/webapp/jsp"/> <property name="suffix" value=".jsp"/> </bean> <!-- 文件上传配置 --> <bean class="org.springframework.web.multipart.commons.CommonsMultipartResolver" id="multipartResolver"> <!--默认编码--> <property name="defaultEncoding" value="UTF-8"/> <!--上传文件的大小限制--> <property name="maxUploadSize" value="32505856"/> <!--内存中的最大值--> <property name="maxInMemorySize" value="4096"/> </bean> </beans> ``` web.xml ``` <web-app> <display-name>zyh</display-name> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:/spring/applicationContext.xml</param-value> </context-param> <context-param> <param-name>log4jConfigLocation</param-name> <param-value>classpath:/properties/log4j.properties</param-value> </context-param> <listener>      <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>  </listener> <servlet> <servlet-name>SpringMvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!--contextConfigLocation配置springMvc的配置文件(也就是适配器,映射器)--> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring/spring-mvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>SpringMvc</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> ``` Service层代码 ``` @Service public class UsersService { @Autowired UsersDao usersDao; public void addUsers(Users users) { usersDao.addUsers(users); } public void deleteUsers(String id) { usersDao.deleteUsers(id); } public void updateUsers(Users users) { usersDao.updateUsers(users); } public Users getUsers(String id) { return usersDao.getUsers(id); } } ``` Controller代码 ``` @ResponseBody @RequestMapping(value = "/getOrders",method = RequestMethod.GET) public Object getOrders(String user_id){ Users u = usersService.getUsers(user_id); u.setUsername("aaa"); Users users = new Users(); users.setId("2222"); users.setUsername("事务大哥我错了"); users.setPassword("1111111123"); usersService.updateUsers(u); usersService.addUsers(users); return Msg.OK(); } ```
SpringMvc无法访问后台
web.xml <?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <!-- 字符过滤转码(防止添加到数据库中的数据为乱码) --> <filter> <filter-name>characterEncodingFilter</filter-name> <filter-class> org.springframework.web.filter.CharacterEncodingFilter </filter-class> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> <init-param> <param-name>forceEncoding</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>characterEncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <filter> <filter-name>UrlRewriteFilter</filter-name> <filter-class>org.tuckey.web.filters.urlrewrite.UrlRewriteFilter</filter-class> </filter> <filter-mapping> <filter-name>UrlRewriteFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!-- 配置上下文 --> <context-param> <param-name>contextConfigLocation</param-name> <!-- 利用上下文配置 --> <param-value>classpath:applicationContext*.xml</param-value> </context-param> <!-- 配置监听 --> <listener> <listener-class> org.springframework.web.util.Log4jConfigListener </listener-class> </listener> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- Spring Mvc配置 --> <servlet> <servlet-name>springmvc</servlet-name> <servlet-class> org.springframework.web.servlet.DispatcherServlet </servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>*.css</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>*.js</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>*.html</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>*.css</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>*.ftl</url-pattern> </servlet-mapping> <!-- log4j配置 --> <context-param> <param-name>webAppRootKey</param-name> <param-value>webName.root</param-value> </context-param> <context-param> <param-name>log4jConfigLocation</param-name> <param-value>WEB-INF/log4j.properties</param-value> </context-param> <context-param> <param-name>log4jRefreshInterval</param-name> <param-value>3000</param-value> </context-param> </web-app> ``` springmvc-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:mvc="http://www.springframework.org/schema/mvc" 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/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"> <!-- 启动扫描所有的controller --> <context:component-scan base-package="com" /> <!-- 主要作用于@Controller,激活该模式 下面是一种简写形式,完全可以手动配置替代这种简写形式; 它会自动注册DefaultAnnotationHandlerMapping与AnnotationMethodHandlerAdapter 两个bean, 是spring MVC为@Controllers分发请求所必须的 --> <mvc:annotation-driven /> <!-- 公共映射配置 --> <mvc:view-controller path="/" view-name="index" /> <!-- jsp页面解析器,当Controller返回XXX字符串时,先通过拦截器,然后该类就会在/WEB-INF/views/目录下,查找XXX.jsp文件--> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"></property> <property name="prefix" value="/"></property> <property name="suffix" value=".jsp"></property> </bean> <!-- 异常解析器 --> <bean id="simpleMappingExceptionResolver" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver"> <property name="exceptionMappings"> <props> <prop key="org.springframework.web.multipart.MaxUploadSizeExceededException">common/fileerror</prop> </props> </property> </bean> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!-- set the max upload size100MB --> <property name="maxUploadSize"> <value>104857600</value> </property> <property name="maxInMemorySize"> <value>4096</value> </property> </bean> </beans> ``` package com.video.web; import java.util.List; import javax.annotation.Resource; 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.video.model.Videotab; import com.video.service.videoService; @Controller @RequestMapping("/video/*") public class videoControl { @Resource public videoService service; @RequestMapping( value="select",method=RequestMethod.GET) public ModelAndView addtest(){ Videotab videotab= new Videotab(); videotab.setVedioid(88); List<Videotab> list=service.selectVideo(videotab); System.out.println("id---"+list.get(0).getVedioid()+"/r"+"title----"+list.get(0).getVediotitle()); return null; } } ``` ```
springmvc 前台直接访问@RequestMapping("/show")提示404,后台不报错
相关代码: springmvc.xml <!-- 扫描组件 --> <context:component-scan base-package="com.bjsxt.controller"></context:component-scan> <!-- 注解驱动,注册HandlerMapping和HandlerAdapter --> <mvc:annotation-driven></mvc:annotation-driven> <!-- 设置静态资源 --> <mvc:resources location="/js/" mapping="/js/**"/> <mvc:resources location="/css/" mapping="/css/**"/> <mvc:resources location="/images/" mapping="/images/**"/> <!-- 视图解析器 --> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/"/> <property name="suffix" value=".jsp"/> </bean> applicationcontext.xml: <!-- 注解扫描,spring扫描service,springmvc扫描控制器 --> <context:component-scan base-package="com.bjsxt.service.impl"></context:component-scan> <!-- 加载database属性文件 --> <context:property-placeholder location="classpath:db.properties"/> <!-- 数据源 --> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="${jdbc.driver}"></property> <property name="url" value="${jdbc.url}"></property> <property name="username" value="${jdbc.username}"></property> <property name="password" value="${jdbc.password}"></property> </bean> <!-- SqlSessionFactory --> <bean id="factory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource"/> <property name="typeAliasesPackage" value="com.bjsxt.pojo"/> </bean> <!-- 扫描器 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.bjsxt.mapper"></property> <property name="sqlSessionFactoryBeanName" value="factory"></property> </bean> <!-- 事务 管理器--> <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"></property> </bean> <!-- 声明式事务 --> <tx:advice id="txAdvice" transaction-manager="txManager"> <tx:attributes> <tx:method name="ins*"/> <tx:method name="upd*"/> <tx:method name="del*"/> <tx:method name="*" read-only="true"/> </tx:attributes> </tx:advice> <!-- 配置aop --> <aop:config> <aop:pointcut expression="execution(* com.bjsxt.service.impl.*.*(..))" id="mypoint"/> <aop:advisor advice-ref="txAdvice" pointcut-ref="mypoint"/> </aop:config> 控制器 @Controller public class MenuController { @Resource private MenuService menuServiceImpl; @RequestMapping("/show") @ResponseBody public List<Menu> show(){ System.out.println("show方法"); return menuServiceImpl.show(); } } web.xml <!-- spring上下文参数 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </context-param> <!-- spring监听器 --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- springMVC前端控制器,入口类 --> <servlet> <servlet-name>springmvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!-- springmvc上下文参数,自启动 --> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:springmvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping>
爬虫福利二 之 妹子图网MM批量下载
爬虫福利一:27报网MM批量下载    点击 看了本文,相信大家对爬虫一定会产生强烈的兴趣,激励自己去学习爬虫,在这里提前祝:大家学有所成! 目标网站:妹子图网 环境:Python3.x 相关第三方模块:requests、beautifulsoup4 Re:各位在测试时只需要将代码里的变量 path 指定为你当前系统要保存的路径,使用 python xxx.py 或IDE运行即可。
字节跳动视频编解码面经
三四月份投了字节跳动的实习(图形图像岗位),然后hr打电话过来问了一下会不会opengl,c++,shador,当时只会一点c++,其他两个都不会,也就直接被拒了。 七月初内推了字节跳动的提前批,因为内推没有具体的岗位,hr又打电话问要不要考虑一下图形图像岗,我说实习投过这个岗位不合适,不会opengl和shador,然后hr就说秋招更看重基础。我当时想着能进去就不错了,管他哪个岗呢,就同意了面试...
Java学习的正确打开方式
在博主认为,对于入门级学习java的最佳学习方法莫过于视频+博客+书籍+总结,前三者博主将淋漓尽致地挥毫于这篇博客文章中,至于总结在于个人,实际上越到后面你会发现学习的最好方式就是阅读参考官方文档其次就是国内的书籍,博客次之,这又是一个层次了,这里暂时不提后面再谈。博主将为各位入门java保驾护航,各位只管冲鸭!!!上天是公平的,只要不辜负时间,时间自然不会辜负你。 何谓学习?博主所理解的学习,它是一个过程,是一个不断累积、不断沉淀、不断总结、善于传达自己的个人见解以及乐于分享的过程。
程序员必须掌握的核心算法有哪些?
由于我之前一直强调数据结构以及算法学习的重要性,所以就有一些读者经常问我,数据结构与算法应该要学习到哪个程度呢?,说实话,这个问题我不知道要怎么回答你,主要取决于你想学习到哪些程度,不过针对这个问题,我稍微总结一下我学过的算法知识点,以及我觉得值得学习的算法。这些算法与数据结构的学习大多数是零散的,并没有一本把他们全部覆盖的书籍。下面是我觉得值得学习的一些算法以及数据结构,当然,我也会整理一些看过
linux系列之常用运维命令整理笔录
本博客记录工作中需要的linux运维命令,大学时候开始接触linux,会一些基本操作,可是都没有整理起来,加上是做开发,不做运维,有些命令忘记了,所以现在整理成博客,当然vi,文件操作等就不介绍了,慢慢积累一些其它拓展的命令,博客不定时更新 free -m 其中:m表示兆,也可以用g,注意都要小写 Men:表示物理内存统计 total:表示物理内存总数(total=used+free) use...
Python 基础(一):入门必备知识
目录1 标识符2 关键字3 引号4 编码5 输入输出6 缩进7 多行8 注释9 数据类型10 运算符10.1 常用运算符10.2 运算符优先级 1 标识符 标识符是编程时使用的名字,用于给变量、函数、语句块等命名,Python 中标识符由字母、数字、下划线组成,不能以数字开头,区分大小写。 以下划线开头的标识符有特殊含义,单下划线开头的标识符,如:_xxx ,表示不能直接访问的类属性,需通过类提供
兼职程序员一般可以从什么平台接私活?
这个问题我进行了系统性的总结,以下将进行言简意赅的说明和渠道提供,希望对各位小猿/小媛们有帮助~ 根据我们的经验,程序员兼职主要分为三种:兼职职位众包、项目整包和自由职业者驻场。 所谓的兼职职位众包,指的是需求方这边有自有工程师配合,只需要某个职位的工程师开发某个模块的项目。比如开发一个 app,后端接口有人开发,但是缺少 iOS 前端开发工程师,那么他们就会发布一个职位招聘前端,来配合公司一...
程序员接私活怎样防止做完了不给钱?
首先跟大家说明一点,我们做 IT 类的外包开发,是非标品开发,所以很有可能在开发过程中会有这样那样的需求修改,而这种需求修改很容易造成扯皮,进而影响到费用支付,甚至出现做完了项目收不到钱的情况。 那么,怎么保证自己的薪酬安全呢? 我们在开工前,一定要做好一些证据方面的准备(也就是“讨薪”的理论依据),这其中最重要的就是需求文档和验收标准。一定要让需求方提供这两个文档资料作为开发的基础。之后开发
Python十大装B语法
Python 是一种代表简单思想的语言,其语法相对简单,很容易上手。不过,如果就此小视 Python 语法的精妙和深邃,那就大错特错了。本文精心筛选了最能展现 Python 语法之精妙的十个知识点,并附上详细的实例代码。如能在实战中融会贯通、灵活使用,必将使代码更为精炼、高效,同时也会极大提升代码B格,使之看上去更老练,读起来更优雅。 1. for - else 什么?不是 if 和 else 才
数据库优化 - SQL优化
前面一篇文章从实例的角度进行数据库优化,通过配置一些参数让数据库性能达到最优。但是一些“不好”的SQL也会导致数据库查询变慢,影响业务流程。本文从SQL角度进行数据库优化,提升SQL运行效率。 判断问题SQL 判断SQL是否有问题时可以通过两个表象进行判断: 系统级别表象 CPU消耗严重 IO等待严重 页面响应时间过长
2019年11月中国大陆编程语言排行榜
2019年11月2日,我统计了某招聘网站,获得有效程序员招聘数据9万条。针对招聘信息,提取编程语言关键字,并统计如下: 编程语言比例 rank pl_ percentage 1 java 33.62% 2 c/c++ 16.42% 3 c_sharp 12.82% 4 javascript 12.31% 5 python 7.93% 6 go 7.25% 7
写了很久,这是一份最适合/贴切普通大众/科班/非科班的『学习路线』
说实话,对于学习路线这种文章我一般是不写的,大家看我的文章也知道,我是很少写建议别人怎么样怎么样的文章,更多的是,写自己的真实经历,然后供大家去参考,这样子,我内心也比较踏实,也不怕误导他人。 但是,最近好多人问我学习路线,而且很多大一大二的,说自己很迷茫,看到我那篇 普普通通,我的三年大学 之后很受激励,觉得自己也能行,(是的,别太浪,你一定能行)希望我能给他个学习路线,说
经典算法(5)杨辉三角
写在前面: 我是 扬帆向海,这个昵称来源于我的名字以及女朋友的名字。我热爱技术、热爱开源、热爱编程。技术是开源的、知识是共享的。 这博客是对自己学习的一点点总结及记录,如果您对 Java、算法 感兴趣,可以关注我的动态,我们一起学习。 用知识改变命运,让我们的家人过上更好的生活。 目录一、杨辉三角的介绍二、杨辉三角的算法思想三、代码实现1.第一种写法2.第二种写法 一、杨辉三角的介绍 百度
腾讯算法面试题:64匹马8个跑道需要多少轮才能选出最快的四匹?
昨天,有网友私信我,说去阿里面试,彻底的被打击到了。问了为什么网上大量使用ThreadLocal的源码都会加上private static?他被难住了,因为他从来都没有考虑过这个问题。无独有偶,今天笔者又发现有网友吐槽了一道腾讯的面试题,我们一起来看看。 腾讯算法面试题:64匹马8个跑道需要多少轮才能选出最快的四匹? 在互联网职场论坛,一名程序员发帖求助到。二面腾讯,其中一个算法题:64匹
面试官:你连RESTful都不知道我怎么敢要你?
面试官:了解RESTful吗? 我:听说过。 面试官:那什么是RESTful? 我:就是用起来很规范,挺好的 面试官:是RESTful挺好的,还是自我感觉挺好的 我:都挺好的。 面试官:… 把门关上。 我:… 要干嘛?先关上再说。 面试官:我说出去把门关上。 我:what ?,夺门而去 文章目录01 前言02 RESTful的来源03 RESTful6大原则1. C-S架构2. 无状态3.统一的接
为啥国人偏爱Mybatis,而老外喜欢Hibernate/JPA呢?
关于SQL和ORM的争论,永远都不会终止,我也一直在思考这个问题。昨天又跟群里的小伙伴进行了一番讨论,感触还是有一些,于是就有了今天这篇文。 声明:本文不会下关于Mybatis和JPA两个持久层框架哪个更好这样的结论。只是摆事实,讲道理,所以,请各位看官勿喷。 一、事件起因 关于Mybatis和JPA孰优孰劣的问题,争论已经很多年了。一直也没有结论,毕竟每个人的喜好和习惯是大不相同的。我也看
SQL-小白最佳入门sql查询一
一 说明 如果是初学者,建议去网上寻找安装Mysql的文章安装,以及使用navicat连接数据库,以后的示例基本是使用mysql数据库管理系统; 二 准备前提 需要建立一张学生表,列分别是id,名称,年龄,学生信息;本示例中文章篇幅原因SQL注释略; 建表语句: CREATE TABLE `student` ( `id` int(11) NOT NULL AUTO_INCREMENT, `
项目中的if else太多了,该怎么重构?
介绍 最近跟着公司的大佬开发了一款IM系统,类似QQ和微信哈,就是聊天软件。我们有一部分业务逻辑是这样的 if (msgType = "文本") { // dosomething } else if(msgType = "图片") { // doshomething } else if(msgType = "视频") { // doshomething } else { // dosho
致 Python 初学者
文章目录1. 前言2. 明确学习目标,不急于求成,不好高骛远3. 在开始学习 Python 之前,你需要做一些准备2.1 Python 的各种发行版2.2 安装 Python2.3 选择一款趁手的开发工具3. 习惯使用IDLE,这是学习python最好的方式4. 严格遵从编码规范5. 代码的运行、调试5. 模块管理5.1 同时安装了py2/py35.2 使用Anaconda,或者通过IDE来安装模
“狗屁不通文章生成器”登顶GitHub热榜,分分钟写出万字形式主义大作
一、垃圾文字生成器介绍 最近在浏览GitHub的时候,发现了这样一个骨骼清奇的雷人项目,而且热度还特别高。 项目中文名:狗屁不通文章生成器 项目英文名:BullshitGenerator 根据作者的介绍,他是偶尔需要一些中文文字用于GUI开发时测试文本渲染,因此开发了这个废话生成器。但由于生成的废话实在是太过富于哲理,所以最近已经被小伙伴们给玩坏了。 他的文风可能是这样的: 你发现,
程序员:我终于知道post和get的区别
IT界知名的程序员曾说:对于那些月薪三万以下,自称IT工程师的码农们,其实我们从来没有把他们归为我们IT工程师的队伍。他们虽然总是以IT工程师自居,但只是他们一厢情愿罢了。 此话一出,不知激起了多少(码农)程序员的愤怒,却又无可奈何,于是码农问程序员。 码农:你知道get和post请求到底有什么区别? 程序员:你看这篇就知道了。 码农:你月薪三万了? 程序员:嗯。 码农:你是怎么做到的? 程序员:
《程序人生》系列-这个程序员只用了20行代码就拿了冠军
你知道的越多,你不知道的越多 点赞再看,养成习惯GitHub上已经开源https://github.com/JavaFamily,有一线大厂面试点脑图,欢迎Star和完善 前言 这一期不算《吊打面试官》系列的,所有没前言我直接开始。 絮叨 本来应该是没有这期的,看过我上期的小伙伴应该是知道的嘛,双十一比较忙嘛,要值班又要去帮忙拍摄年会的视频素材,还得搞个程序员一天的Vlog,还要写BU
加快推动区块链技术和产业创新发展,2019可信区块链峰会在京召开
11月8日,由中国信息通信研究院、中国通信标准化协会、中国互联网协会、可信区块链推进计划联合主办,科技行者协办的2019可信区块链峰会将在北京悠唐皇冠假日酒店开幕。   区块链技术被认为是继蒸汽机、电力、互联网之后,下一代颠覆性的核心技术。如果说蒸汽机释放了人类的生产力,电力解决了人类基本的生活需求,互联网彻底改变了信息传递的方式,区块链作为构造信任的技术有重要的价值。   1...
程序员把地府后台管理系统做出来了,还有3.0版本!12月7号最新消息:已在开发中有github地址
第一幕:缘起 听说阎王爷要做个生死簿后台管理系统,我们派去了一个程序员…… 996程序员做的梦: 第一场:团队招募 为了应对地府管理危机,阎王打算找“人”开发一套地府后台管理系统,于是就在地府总经办群中发了项目需求。 话说还是中国电信的信号好,地府都是满格,哈哈!!! 经常会有外行朋友问:看某网站做的不错,功能也简单,你帮忙做一下? 而这次,面对这样的需求,这个程序员
网易云6亿用户音乐推荐算法
网易云音乐是音乐爱好者的集聚地,云音乐推荐系统致力于通过 AI 算法的落地,实现用户千人千面的个性化推荐,为用户带来不一样的听歌体验。 本次分享重点介绍 AI 算法在音乐推荐中的应用实践,以及在算法落地过程中遇到的挑战和解决方案。 将从如下两个部分展开: AI 算法在音乐推荐中的应用 音乐场景下的 AI 思考 从 2013 年 4 月正式上线至今,网易云音乐平台持续提供着:乐屏社区、UGC
8年经验面试官详解 Java 面试秘诀
    作者 | 胡书敏 责编 | 刘静 出品 | CSDN(ID:CSDNnews) 本人目前在一家知名外企担任架构师,而且最近八年来,在多家外企和互联网公司担任Java技术面试官,前后累计面试了有两三百位候选人。在本文里,就将结合本人的面试经验,针对Java初学者、Java初级开发和Java开发,给出若干准备简历和准备面试的建议。   Java程序员准备和投递简历的实
面试官如何考察你的思维方式?
1.两种思维方式在求职面试中,经常会考察这种问题:北京有多少量特斯拉汽车? 某胡同口的煎饼摊一年能卖出多少个煎饼? 深圳有多少个产品经理? 一辆公交车里能装下多少个乒乓球? 一
碎片化的时代,如何学习
今天周末,和大家聊聊学习这件事情。 在如今这个社会,我们的时间被各类 APP 撕的粉碎。 刷知乎、刷微博、刷朋友圈; 看论坛、看博客、看公号; 等等形形色色的信息和知识获取方式一个都不错过。 貌似学了很多,但是却感觉没什么用。 要解决上面这些问题,首先要分清楚一点,什么是信息,什么是知识。 那什么是信息呢? 你一切听到的、看到的,都是信息,比如微博上的明星出轨、微信中的表情大战、抖音上的...
so easy! 10行代码写个"狗屁不通"文章生成器
前几天,GitHub 有个开源项目特别火,只要输入标题就可以生成一篇长长的文章。 背后实现代码一定很复杂吧,里面一定有很多高深莫测的机器学习等复杂算法 不过,当我看了源代码之后 这程序不到50行 尽管我有多年的Python经验,但我竟然一时也没有看懂 当然啦,原作者也说了,这个代码也是在无聊中诞生的,平时撸码是不写中文变量名的, 中文...
知乎高赞:中国有什么拿得出手的开源软件产品?(整理自本人原创回答)
知乎高赞:中国有什么拿得出手的开源软件产品? 在知乎上,有个问题问“中国有什么拿得出手的开源软件产品(在 GitHub 等社区受欢迎度较好的)?” 事实上,还不少呢~ 本人于2019.7.6进行了较为全面的回答,对这些受欢迎的 Github 开源项目分类整理如下: 分布式计算、云平台相关工具类 1.SkyWalking,作者吴晟、刘浩杨 等等 仓库地址: apache/skywalking 更...
相关热词 c#处理浮点数 c# 生成字母数字随机数 c# 动态曲线 控件 c# oracle 开发 c#选择字体大小的控件 c# usb 批量传输 c#10进制转8进制 c#转base64 c# 科学计算 c#下拉列表获取串口
立即提问