前言
前天用SpringJdbc连接了一把SQLServer,早上起来用SpringMVC+SpringJdbc+EasUI写了个增删改查的demo,主要是熟悉下SpringMVC相关知识点,如view层向Controller传参的几种方式,从Controller向view传递model的几种方式。 其中从view层向controller层传递时遇到了些问题,刚开始报400、415,都是由于传递的方式后台无法识别。
开发环境
idea2016、SpringMVC4、SpringJdbc4
项目结构
项目源文件
1、pom.xml
1 <dependencies> 2 <dependency> 3 <groupId>org.springframework</groupId> 4 <artifactId>spring-beans</artifactId> 5 <version>4.3.6.RELEASE</version> 6 </dependency> 7 <dependency> 8 <groupId>org.springframework</groupId> 9 <artifactId>spring-context</artifactId> 10 <version>4.3.6.RELEASE</version> 11 </dependency> 12 <dependency> 13 <groupId>org.springframework</groupId> 14 <artifactId>spring-core</artifactId> 15 <version>4.3.6.RELEASE</version> 16 </dependency> 17 <dependency> 18 <groupId>org.springframework</groupId> 19 <artifactId>spring-test</artifactId> 20 <version>4.3.6.RELEASE</version> 21 </dependency> 22 <dependency> 23 <groupId>org.springframework</groupId> 24 <artifactId>spring-web</artifactId> 25 <version>4.3.6.RELEASE</version> 26 </dependency> 27 <dependency> 28 <groupId>org.springframework</groupId> 29 <artifactId>spring-webmvc</artifactId> 30 <version>4.3.6.RELEASE</version> 31 </dependency> 32 <dependency> 33 <groupId>org.springframework</groupId> 34 <artifactId>spring-jdbc</artifactId> 35 <version>4.3.6.RELEASE</version> 36 </dependency> 37 <dependency> 38 <groupId>junit</groupId> 39 <artifactId>junit</artifactId> 40 <version>4.10</version> 41 </dependency> 42 <dependency> 43 <groupId>com.microsoft.sqlserver</groupId> 44 <artifactId>sqljdbc4</artifactId> 45 <version>4.0</version> 46 </dependency> 47 <dependency> 48 <groupId>commons-dbcp</groupId> 49 <artifactId>commons-dbcp</artifactId> 50 <version>1.4</version> 51 </dependency> 52 <dependency> 53 <groupId>com.alibaba</groupId> 54 <artifactId>fastjson</artifactId> 55 <version>1.2.12</version> 56 </dependency> 57 <dependency> 58 <groupId>com.fasterxml.jackson.core</groupId> 59 <artifactId>jackson-core</artifactId> 60 <version>2.5.0</version> 61 </dependency> 62 <dependency> 63 <groupId>com.fasterxml.jackson.core</groupId> 64 <artifactId>jackson-annotations</artifactId> 65 <version>2.5.0</version> 66 </dependency> 67 <dependency> 68 <groupId>com.fasterxml.jackson.core</groupId> 69 <artifactId>jackson-databind</artifactId> 70 <version>2.5.0</version> 71 </dependency> 72 </dependencies>
2、web.xml
<web-app> <display-name>Archetype Created Web Application</display-name> <!--告知javaEE容器,有那些内容需要添加到上下文里去--> <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 前端控制器--> <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> </servlet> <servlet-mapping> <servlet-name>SpringMVC</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app>
3、jdbc.properties
sqlserver.driver=com.microsoft.sqlserver.jdbc.SQLServerDriver
sqlserver.url=jdbc:sqlserver://127.0.0.1:1433;databaseName=testdb
sqlserver.username=sa
sqlserver.password=0
4、springmvc-servlet.xml
<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.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <bean id="jdbcConfig" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="location" value="classpath:jdbc.properties"/> </bean> <!--配置数据源--> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="${sqlserver.driver}"/> <property name="url" value="${sqlserver.url}"/> <property name="username" value="${sqlserver.username}"/> <property name="password" value="${sqlserver.password}"/> </bean> <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> <property name="dataSource" ref="dataSource"/> </bean> <!--json数据源处理--> <bean id="stringConverter" class="org.springframework.http.converter.StringHttpMessageConverter"> <property name="supportedMediaTypes"> <list> <value>text/plain;charset=UTF-8</value> </list> </property> </bean> <bean id="jsonConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"></bean> <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> <property name="messageConverters"> <list> <ref bean="stringConverter" /> <ref bean="jsonConverter" /> </list> </property> </bean> <!--启用最新的注解器、映射器--> <mvc:annotation-driven/> <!--静态资源访问--> <mvc:default-servlet-handler/> <context:component-scan base-package="com.autohome.dao"/> <context:component-scan base-package="com.autohome.service"/> <!--扫描controller--> <context:component-scan base-package="com.autohome.controller"/> <!--配置视图解析器--> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/views/"/> <property name="suffix" value=".jsp"/> </bean> </beans>
5、Dao
@Repository public class UserDaoImpl implements IUserDao { @Autowired JdbcTemplate jdbcTemplate; public List<User> listAllUser() { List<User> list = jdbcTemplate.query("select * from UserInfo",new User()); return list; } public List<User> listPagedUser(int pageIndex,int pageSize){ String sql="select top "+pageSize+" * from UserInfo where id not in (select top ("+pageSize+" * ("+pageIndex+" -1)) id from UserInfo)"; List<User> list = jdbcTemplate.query(sql,new User()); return list; } public int getUserCount() { int result = jdbcTemplate.queryForObject("select count(*) from UserInfo",Integer.class); return result; } public User getUserById(int id) { User user = jdbcTemplate.queryForObject("select * from UserInfo where id=?",new Object[]{id},new User()); return user; } public int insertUser(final User user) { int result = jdbcTemplate.update("insert into UserInfo (UserName,age) VALUES (?,?)", new PreparedStatementSetter() { public void setValues(PreparedStatement ps) throws SQLException { ps.setString(1,user.getName()); ps.setInt(2,user.getAge()); } }); return result; } public int updateUser(final User user) { int result = jdbcTemplate.update("UPDATE UserInfo set UserName=?,age=? where id=?", new PreparedStatementSetter() { public void setValues(PreparedStatement ps) throws SQLException { ps.setString(1,user.getName()); ps.setInt(2,user.getAge()); ps.setInt(3,user.getId()); } }); return result; } public int deleteUser(int id) { int result = jdbcTemplate.update("delete from UserInfo where id=?",new Object[]{id},new int[]{Types.INTEGER}); return result; } }
6、Controller
@Controller @RequestMapping("/User") public class UserController { @Autowired private IUserBiz userBiz; @RequestMapping("/index") public ModelAndView index(){ List<User> list =userBiz.listAllUser(); return new ModelAndView("index"); } @RequestMapping(value="/userJson",method = RequestMethod.GET) public ResponseEntity<JSONObject> getUserJson(@RequestParam("page")int pageIndex, @RequestParam("rows")int pageSize){ JSONObject obj =new JSONObject(); List<User> list =userBiz.listPagedUser(pageIndex,pageSize); int total=userBiz.getUserCount(); obj.put("total",total); obj.put("rows",list); return new ResponseEntity<JSONObject>(obj, HttpStatus.OK); } @RequestMapping(value="/deleteUser",method = RequestMethod.POST) public ResponseEntity<JSONObject> deleteUser(@RequestParam("id")int id){ JSONObject obj =new JSONObject(); int result = userBiz.deleteUser(id); obj.put("returncode",result); obj.put("msg",result>0?"success":"error"); return new ResponseEntity<JSONObject>(obj,HttpStatus.OK); } @RequestMapping(value="/saveUser",method = RequestMethod.POST) public ResponseEntity<JSONObject> saveUser(@RequestBody User user){ JSONObject obj =new JSONObject(); int result = userBiz.insertUser(user); obj.put("returncode",result); obj.put("msg",result>0?"success":"error"); return new ResponseEntity<JSONObject>(obj,HttpStatus.OK); } @RequestMapping(value="/editUser",method = RequestMethod.POST) public ResponseEntity<JSONObject> updateUser(@RequestBody User user){ JSONObject obj =new JSONObject(); int result = userBiz.updateUser(user); obj.put("returncode",result); obj.put("msg",result>0?"success":"error"); return new ResponseEntity<JSONObject>(obj,HttpStatus.OK); } }
总结
做这个demo的过程中,首先遇到了SpringMVC中访问静态的资源的,再就是用ajax post访问请求Controller参数的格式及语法问题,contentType参数很重要,我是通过把参数序列化成字符串,然后在Controller通过bean的方式接收,主要标注ResponseBody。