1.坐标文件
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>cn.web</groupId> <artifactId>spring_mvc</artifactId> <version>1.0-SNAPSHOT</version> <packaging>war</packaging> <name>itheima_spring_mvc Maven Webapp</name> <!-- FIXME change it to the project's website --> <url>http://www.example.com</url> <dependencies> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.32</version> </dependency> <dependency> <groupId>c3p0</groupId> <artifactId>c3p0</artifactId> <version>0.9.1.2</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.1.10</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>5.0.5.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>5.0.5.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>5.0.5.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>5.0.5.RELEASE</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.0.1</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>javax.servlet.jsp-api</artifactId> <version>2.2.1</version> <scope>provided</scope> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>2.9.0</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.9.0</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-annotations</artifactId> <version>2.9.0</version> </dependency> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.1</version> </dependency> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.3</version> </dependency> <!--JdbcTemplate包--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>5.0.5.RELEASE</version> </dependency> </dependencies> </project>
2.web.xml配置
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" version="4.0"> <!--配置SpringMVC的前端控制器:所有请求转发到spring-web的 DispatcherServlet 来处理--> <servlet> <servlet-name>DispatcherServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring-mvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>DispatcherServlet</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <!--配置全局过滤的filter:设置编码方式--> <filter> <filter-name>CharacterEncodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>CharacterEncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!--全局初始化参数 初始化加载Bean配置--> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </context-param> <!--配置监听器 在ContextLoaderListener监听器中完成bean配置加载到容器--> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!--<servlet>--> <!--<servlet-name>userservlet</servlet-name>--> <!--<servlet-class>cn.web.servlet.UserServlet</servlet-class>--> <!--</servlet>--> <!--<servlet-mapping>--> <!--<servlet-name>userservlet</servlet-name>--> <!--<url-pattern>/user</url-pattern>--> <!--</servlet-mapping>--> </web-app>
3.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" 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"> <!--加载外部的properties文件--> <context:property-placeholder location="classpath:jdbc.properties"/> <!--配置数据源--> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="driverClass" value="${jdbc.driver}"></property> <property name="jdbcUrl" value="${jdbc.url}"></property> <property name="user" value="${jdbc.username}"></property> <property name="password" value="${jdbc.password}"></property> </bean> <!--配置JdbcTemplate--> <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> <property name="dataSource" ref="dataSource"></property> </bean> <!--手动配置3层--> <!--dao层注入--> <bean id="userDao" class="cn.web.dao.impl.UserDaoImpl"> <property name="jdbcTemplate" ref="jdbcTemplate"></property> </bean> <!--server层注入--> <bean id="userServer" class="cn.web.Server.Impl.UserServerImpl"> <property name="userDao" ref="userDao"></property> </bean> </beans>
4.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" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd "> <!--Controller的组件扫描--> <context:component-scan base-package="cn.web"> <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/> </context:component-scan> <!--mvc注解驱动,直接返回json--> <mvc:annotation-driven></mvc:annotation-driven> <!--mvc找不到资源,交给servlet处理--> <mvc:default-servlet-handler></mvc:default-servlet-handler> <!--自定义异常处理器--> <bean class="cn.web.resolver.ExceptionResolver"/> </beans>
5.Controller层
package cn.web.controller; import cn.web.Server.UserServer; import cn.web.domain.User; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import java.util.List; /* * 注意事项: * 1.Controller层只能通过注解来注入,Server就只能通过自动注入方式获取 * 2.这里server层、dao层都是通过xml注入,也可以通过注解注入 * */ @Controller @RequestMapping("/user") public class UserContoller { @Autowired private UserServer server; @RequestMapping("/findAll") @ResponseBody public List<User> findAll() { return server.findAll(); } @RequestMapping("/findById") @ResponseBody public User findById(int id) { return server.findById(id); } @RequestMapping("/insert") @ResponseBody public Long insert(User user) { return server.insert(user); } @RequestMapping("/update") @ResponseBody public boolean update(User user) { return server.update(user); } @RequestMapping("/delete") @ResponseBody public boolean delete(User user) { return server.delete(user); } @RequestMapping("/paramList") @ResponseBody public List<User> delete(@RequestBody List<User> list) { return list; } }
6.server层
package cn.web.Server.Impl; import cn.web.Server.UserServer; import cn.web.dao.UserDao; import cn.web.domain.User; import java.util.List; public class UserServerImpl implements UserServer { private UserDao dao; public void setUserDao(UserDao userDao) { this.dao = userDao; } public List<User> findAll() { return dao.findAll(); } public User findById(int id) { return dao.findById(id); } public long insert(User user) { return dao.insert(user); } public boolean update(User user) { return dao.update(user); } public boolean delete(User user) { return dao.delete(user); }
7.dao层
package cn.web.dao.impl; import cn.web.dao.UserDao; import cn.web.domain.User; import org.springframework.dao.DataAccessException; import org.springframework.jdbc.core.BeanPropertyRowMapper; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.PreparedStatementCreator; import org.springframework.jdbc.support.GeneratedKeyHolder; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.List; public class UserDaoImpl implements UserDao { private JdbcTemplate template; public void setJdbcTemplate(JdbcTemplate jdbcTemplate) { this.template = jdbcTemplate; } public List<User> findAll() { String sql="SELECT * FROM USER"; List<User> query = template.query(sql, new BeanPropertyRowMapper<User>(User.class)); return query; } public User findById(int id) { User user=null; try { String sql="SELECT * FROM USER WHERE id=?"; user = template.queryForObject(sql, new BeanPropertyRowMapper<User>(User.class),id); }catch (DataAccessException e){ e.printStackTrace(); } return user; } public long insert(final User user) { final String sql="INSERT INTO USER (id,username,PASSWORD) VALUES(NULL,?,?)"; //1.创建PreparedStatementCreator PreparedStatementCreator creator=new PreparedStatementCreator() { //2.使用原始jdbc完成PreparedStatement组件 public PreparedStatement createPreparedStatement(Connection connection) throws SQLException { PreparedStatement preparedStatement=connection.prepareStatement(sql,PreparedStatement.RETURN_GENERATED_KEYS); preparedStatement.setObject(1,user.getUsername()); preparedStatement.setObject(2,user.getPassword()); return preparedStatement; } }; //3.创建 GeneratedKeyHolder GeneratedKeyHolder keyHolder=new GeneratedKeyHolder(); //4.插入数据 template.update(creator, keyHolder); //5.获得自增长id long l = keyHolder.getKey().longValue(); //int update = template.update(sql, user.getUsername(), user.getPassword()); return l; } public boolean update(User user) { String sql="UPDATE USER SET username=?, PASSWORD=? WHERE ID=?"; int update = template.update(sql, user.getUsername(), user.getPassword(), user.getId()); return update>0; } public boolean delete(User user) { String sql ="DELETE FROM USER WHERE id=?"; int update = template.update(sql, user.getId()); return update>0; } }
8.全局异常捕获过滤器
package cn.web.resolver; import org.springframework.web.servlet.HandlerExceptionResolver; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; public class ExceptionResolver implements HandlerExceptionResolver { public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) { ModelAndView modelAndView = new ModelAndView(); System.out.println("错误日志"); /* * 错误写入log4日志 * */ e.printStackTrace(); modelAndView.setViewName("/error.html"); return modelAndView; } }