标签:url xmlns loader css oca 有用 -name mpi 首页
如果还不了解剧情,请返回第3集的剧情 Java归去来第3集:Eclipse中给动态模块升级
SSM(Spring+SpringMVC+MyBatis)框架集由Spring、SpringMVC、MyBatis三个开源框架整合而成,常作为数据源较简单的web项目的框架。其中spring是一个轻量级的控制反转(IoC)和面向切面(AOP)的容器框架。SpringMVC分离了控制器、模型对象、分派器以及处理程序对象的角色,这种分离让它们更容易进行定制。MyBatis是一个支持普通SQL查询,存储过程和高级映射的优秀持久层框架
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>king.weixin</groupId> <artifactId>KingWeixin</artifactId> <packaging>war</packaging> <version>0.0.1-SNAPSHOT</version> <name>KingWeixin Maven Webapp</name> <url>http://maven.apache.org</url> <!-- 公共版本号 --> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <java-version>1.8</java-version> <org.springframework-version>4.3.5.RELEASE</org.springframework-version> <org.aspectj-version>1.7.2</org.aspectj-version> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </properties> <!-- 公共版本号 end --> <dependencies> <!-- junit 开始 --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> <!-- junit 结束 --> <!--spring mvc 开始--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${org.springframework-version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> <version>${org.springframework-version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>${org.springframework-version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>${org.springframework-version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${org.springframework-version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${org.springframework-version}</version> <exclusions> <!-- Exclude Commons Logging in favor of SLF4j --> <exclusion> <groupId>commons-logging</groupId> <artifactId>commons-logging</artifactId> </exclusion> </exclusions> </dependency> <!--spring mvc 结束 --> <!-- mybatis & mysql 开始--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.31</version> </dependency> <dependency> <groupId>commons-dbcp</groupId> <artifactId>commons-dbcp</artifactId> <version>1.4</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.3.0</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.4.1</version> </dependency> <!-- mybatis & mysql 结束--> <!-- javax servlet 开始--> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.0.1</version> <scope>provided</scope> </dependency> <!-- javax servlet 结束--> <!--commons tools 开始 --> <dependency> <groupId>commons-configuration</groupId> <artifactId>commons-configuration</artifactId> <version>1.9</version> </dependency> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.2</version> </dependency> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.5</version> </dependency> <dependency> <groupId>commons-net</groupId> <artifactId>commons-net</artifactId> <version>3.5</version> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.2</version> </dependency> <!--commons tools 结束--> <!--log4j 开始--> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-api</artifactId> <version>2.10.0</version> </dependency> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-core</artifactId> <version>2.10.0</version> </dependency> <!-- https://mvnrepository.com/artifact/org.apache.logging.log4j/log4j-web --> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-web</artifactId> <version>2.10.0</version> </dependency> <!-- https://mvnrepository.com/artifact/org.apache.logging.log4j/log4j-jcl --> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-jcl</artifactId> <version>2.10.0</version> </dependency> <!-- https://mvnrepository.com/artifact/org.apache.logging.log4j/log4j-slf4j-impl --> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-slf4j-impl</artifactId> <version>2.10.0</version> </dependency> <!--log4j 结束--> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> </dependencies> <!--指定source和target编译版本开始 --> <build> <finalName>KingWeixin</finalName> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin> </plugins> </build> <!--指定source和target编译版本结束 --> </project>
<?xml version="1.0" encoding="UTF-8"?> <web-app version="3.0" 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_3_0.xsd"> <!--项目名称 --> <display-name>KingWeixin</display-name> <!--项目编码过滤器开始--> <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> <!--项目编码过滤器结束--> <!-- 配置文件所在位置设置开始--> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath*:/config/spring-*.xml</param-value> </context-param> <!-- 配置文件所在位置设置结束--> <!-- Spring监听配置开始 --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- Spring监听配置结束 --> <!-- SpringMVC配置开始 --> <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:/config/spring-mvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>springDispatcherServlet</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <!-- SpringMVC配置结束--> </web-app>
首先,创建spring-mvc.xml主要配置文件
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns: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.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd"> <!-- 注解扫描包 --> <context:component-scan base-package="com.king.weixin"/> <!-- 开启注解 --> <mvc:annotation-driven/> <!-- 配置静态资源,直接映射到对应的文件夹,不被DispatcherServlet处理,3.04新增功能,需要重新设置spring-mvc-3.0.xsd --> <mvc:resources mapping="/img/**" location="/img/" /> <mvc:resources mapping="/js/**" location="/js/" /> <mvc:resources mapping="/css/**" location="/css/" /> <mvc:resources mapping="/html/**" location="/html/" /> <mvc:resources mapping="/tinymce/**" location="/tinymce/" /> <mvc:resources mapping="/upload/**" location="/upload/" /> <!-- 定义跳转的文件的前后缀 ,视图模式配置--> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <!-- 这里的配置我的理解是自动给后面action的方法return的字符串加上前缀和后缀,变成一个 可用的url地址 --> <property name="prefix" value="/" /> <property name="suffix" value=".jsp" /> </bean> </beans>
其次创建spring-common.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:tx="http://www.springframework.org/schema/tx" 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/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd"> <!-- 1. 数据源 : DriverManagerDataSource --> <!-- <bean id="dataSource" --> <!-- class="org.springframework.jdbc.datasource.DriverManagerDataSource"> --> <!-- <property name="driverClassName" value="com.mysql.jdbc.Driver" /> --> <!-- <property name="url" value="jdbc:mysql://数据服务器IP:3306/king?useUnicode=true&characterEncoding=utf-8" /> --> <!-- <property name="username" value="root" /> --> <!-- <property name="password" value="密码" /> --> <!-- </bean> --> <!-- 2. 数据源 : 连接池 ProxoolDataSource --> <bean id="dataSource" class="org.logicalcobwebs.proxool.ProxoolDataSource"> <property name="driver"> <value>com.mysql.jdbc.Driver</value> </property> <property name="driverUrl"> <value>jdbc:mysql://数据服务器IP:3306/king?user=root&password=密码&useUnicode=true&characterEncoding=utf-8 </value> </property> <property name="user" value="root" /> <property name="password" value="密码" /> <property name="alias" value="Pool_dbname" /> <!-- <property name="houseKeepingSleepTime" value="90000" /> --> <property name="prototypeCount" value="0" /> <property name="maximumConnectionCount" value="50" /> <property name="minimumConnectionCount" value="2" /> <property name="simultaneousBuildThrottle" value="50" /> <!-- <property name="maximumConnectionLifetime" value="14400000" /> --> <property name="houseKeepingTestSql" value="select CURRENT_DATE" /> </bean> <!-- 2. mybatis的SqlSession的工厂: SqlSessionFactoryBean dataSource:引用数据源 MyBatis定义数据源,同意加载配置 --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource"></property> <property name="configLocation" value="classpath:config/mybatis-config.xml" /> </bean> <!-- 3. mybatis自动扫描加载Sql映射文件/接口 : MapperScannerConfigurer sqlSessionFactory basePackage:指定sql映射文件/接口所在的包(自动扫描) --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.king.weixin.mapper"></property> <property name="sqlSessionFactory" ref="sqlSessionFactory"></property> </bean> <!--4. 事务管理 : DataSourceTransactionManager dataSource:引用上面定义的数据源 --> <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"></property> </bean> <!-- 5. 使用声明式事务 transaction-manager:引用上面定义的事务管理器 --> <tx:annotation-driven transaction-manager="txManager" /> </beans>
最后创建mybatis-config.xml数据持久层配置文件
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <!-- 实体类,简称 -设置别名 --> <typeAliases> <typeAlias alias="User" type="com.king.weixin.entity.User" /> </typeAliases> <!-- 实体接口映射资源 --> <!-- 说明:如果xxMapper.xml配置文件放在和xxMapper.java统一目录下,mappers也可以省略,因为org.mybatis.spring.mapper.MapperFactoryBean默认会去查找与xxMapper.java相同目录和名称的xxMapper.xml --> <mappers> <mapper resource="com/king/weixin/mapper/userMapper.xml" /> </mappers> </configuration>
关系,两个Spring文件会在web.xml中引入,mybatis-config文件会在sping定义数据源配置的spring-common.xml文件中引入,具体可以看代码,截止目前,项目搭建完毕,Maven-update project的话,系统会根据pom.xml自动下载相关jar包,这就是Maven的好处
(1)新建entity类User.java
package com.king.weixin.entity; /** * @author KING * 2018-6-8 16:00:06 */ public class User { private int id; private String age; private String userName; public User(){ super(); } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getAge() { return age; } public void setAge(String age) { this.age = age; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public User(int id, String age, String userName) { super(); this.id = id; this.age = age; this.userName = userName; } }
(2)新建UserMapper.java接口类
package com.king.weixin.mapper; import java.util.List; import com.king.weixin.entity.User; public interface UserMapper { void save(User user); boolean update(User user); boolean delete(int id); User findById(int id); List<User> findAll(); }
(3)新建userMapper.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <!-- namespace:必须与对应的接口全类名一致 id:必须与对应接口的某个对应的方法名一致 --> <mapper namespace="com.king.weixin.mapper.UserMapper"> <insert id="save" parameterType="User"> insert into t_user(user_name,user_age) values(#{userName},#{age}) </insert> <update id="update" parameterType="User"> update t_user set user_name=#{userName},user_age=#{age} where user_id=#{id} </update> <delete id="delete" parameterType="int"> delete from t_user where user_id=#{id} </delete> <!-- mybsits_config中配置的alias类别名,也可直接配置resultType为类路径 --> <select id="findById" parameterType="int" resultType="User"> select user_id id,user_name userName,user_age age from t_user where user_id=#{id} </select> <select id="findAll" resultType="User"> select user_id id,user_name userName,user_age age from t_user </select> </mapper>
(4)新建UserService.java接口类
package com.king.weixin.service; import java.util.List; import com.king.weixin.entity.User; public interface UserService { void save(User user); boolean update(User user); boolean delete(int id); User findById(int id); List<User> findAll(); }
(5)新建UserServiceImpl.java实现类
package com.king.weixin.service; import java.util.List; import javax.annotation.Resource; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.king.weixin.mapper.UserMapper; import com.king.weixin.entity.User; import com.king.weixin.service.UserService; @Service @Transactional //此处不再进行创建SqlSession和提交事务,都已交由spring去管理了 public class UserServiceImpl implements UserService { @Resource private UserMapper mapper; public boolean delete(int id) { return mapper.delete(id); } public List<User> findAll() { List<User> findAllList = mapper.findAll(); return findAllList; } public User findById(int id) { User user = mapper.findById(id); return user; } public void save(User user) { mapper.save(user); } public boolean update(User user) { return mapper.update(user); } }
(6)新建UserController.java控制类
package com.king.weixin.controller; import java.io.IOException; import java.io.PrintWriter; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import com.king.weixin.entity.User; import com.king.weixin.service.UserService; @Controller @RequestMapping("/user") public class UserController { @Autowired private UserService userService; /** * 获取所有用户列表 * @param request * @return */ @RequestMapping("/getAllUser") public String getAllUser(HttpServletRequest request){ System.out.println("访问的是我"); List<User> findAll = userService.findAll(); request.setAttribute("userList", findAll); return "/index"; } /** * 跳转到添加用户界面 * @param request * @return */ @RequestMapping("/toAddUser") public String toAddUser(HttpServletRequest request){ return "/addUser"; } /** * 添加用户并重定向 * @param user * @param request * @return */ @RequestMapping("/addUser") public String addUser(User user,HttpServletRequest request){ userService.save(user); return "redirect:/user/getAllUser"; } /** *编辑用户 * @param user * @param request * @return */ @RequestMapping("/updateUser") public String updateUser(User user,HttpServletRequest request){ if(userService.update(user)){ user = userService.findById(user.getId()); request.setAttribute("user", user); return "redirect:/user/getAllUser"; }else{ return "/error"; } } /** * 根据id查询单个用户 * @param id * @param request * @return */ @RequestMapping("/getUser") public String getUser(int id,HttpServletRequest request){ request.setAttribute("user", userService.findById(id)); return "/editUser"; } /** * 删除用户 * @param id * @param request * @param response */ @RequestMapping("/delUser") public void delUser(int id,HttpServletRequest request,HttpServletResponse response){ String result = "{\"result\":\"error\"}"; if(userService.delete(id)){ result = "{\"result\":\"success\"}"; } response.setContentType("application/json"); try { PrintWriter out = response.getWriter(); out.write(result); } catch (IOException e) { e.printStackTrace(); } } @RequestMapping("/GoLogin") public String GoLogin(HttpServletRequest request,HttpServletResponse response) { return "/login"; } @RequestMapping("/CheckLogin") public void CheckLogin(HttpServletRequest request,HttpServletResponse response) throws IOException { String sysusername="king"; String syspassword="123456"; String username=request.getParameter("userName"); String password=request.getParameter("passWord"); System.out.println("用户名:"+username); System.out.println("密码:"+password); HttpSession session=request.getSession(); if(username.equals(sysusername)&&password.equals(syspassword)) { session.setAttribute("username",username ); response.getWriter().write("success"); } else { response.getWriter().write("err"); } } }
后台的类已创建完成,下面我们新建一个index.jsp页面做测试,页面内容如下,这里我引入了jstl标签,具体代码请看下面的代码
<%@ page language="java" contentType="text/html; charset=utf8" pageEncoding="utf8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <meta http-equiv="Content-Type" content="text/html; charset=utf8"> <title>SpringMvc测试页</title> </head> <script type="text/javascript"> function queryuser() { window.location.href="<%=request.getContextPath()%>/user/getAllUser"; } </script> <body> <h3>Hello,world</h3><br> <button onclick="queryuser()">查询所有用户</button> <table border="1"> <tr> <td>用户编号</td><td>年龄</td><td>姓名</td> </tr> <c:forEach items="${userList}" var="user" varStatus="vs"> <tr> <td align = "center">${user.id}</td> <td align = "center">${user.age}</td> <td align = "center">${user.userName}</td> </tr> </c:forEach> </table> </body> </html>
启动项目,访问如下图所示,访问到首页
点击查询所有用户按钮
后台我在UserController里面的getAllUser方法做了打印,可以看到请求已经到了Controller里面,实战结束
Java归去来第4集:java实战之Eclipse中创建Maven类型的SSM项目
标签:url xmlns loader css oca 有用 -name mpi 首页
原文地址:https://www.cnblogs.com/wxjnew/p/9157186.html