一、建立工程,選擇Maven
html
二、填寫項目信息
java
一、Maven配置
先說Maven的項目依賴配置文件pom.xml,咱們進入mvn repository 查找須要搜索的包結果如圖:
mysql
點擊進入第一個搜索結果,而後各類版本
web
點擊所需版本。如圖:
裏面的dependency即爲所需標籤。spring
總的配置文件pom.xml添加依賴包信息以下: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>SSMTestProject</groupId> <artifactId>SSMTestProject</artifactId> <packaging>war</packaging> <version>1.0-SNAPSHOT</version> <name>SSMTestProject Maven Webapp</name> <url>http://maven.apache.org</url> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>4.2.5.RELEASE</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>2.7.2</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>4.2.5.RELEASE</version> </dependency> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>jsp-api</artifactId> <version>2.2</version> </dependency> <dependency> <groupId>jstl</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>4.2.5.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>4.2.5.RELEASE</version> </dependency> <dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-jpa</artifactId> <version>1.9.4.RELEASE</version> </dependency> <dependency> <groupId>org.hibernate.javax.persistence</groupId> <artifactId>hibernate-jpa-2.0-api</artifactId> <version>1.0.1.Final</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-entitymanager</artifactId> <version>5.1.0.Final</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>2.5</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.38</version> </dependency> <dependency> <groupId>org.json</groupId> <artifactId>json</artifactId> <version>20160212</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>2.7.2</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.7.2</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.3.1</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.2.4</version> </dependency> </dependencies> <build> <finalName>SSMTestProject</finalName> </build> </project>
二、web配置數據庫
web.xml配置添加以下信息:express
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd" > <web-app> <display-name>SSMTestProject</display-name> <servlet> <servlet-name>myspring</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>myspring</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <filter> <filter-name>encodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> <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>
使用spring框架的默認DispatcherSerlet。load-on-starup標籤表示servlet的啓用時間,servlet-name指定了serevlet配置文件myspring。url -pattern是指全部路徑均會被該servlet攔截。而filter一句是防止中文亂碼,啓用uft-8。apache
配置Servlet myspring-servlet.xmljson
<?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="com.ssm.controller"/> <!-- 靜態資源(js、image等)的訪問 --> <mvc:default-servlet-handler/> <!-- 開啓註解 --> <mvc:annotation-driven/> <!--ViewResolver 視圖解析器--> <!--用於支持Servlet、JSP視圖解析--> <bean id="jspViewResolver" 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>
log4j.xml 配置文件以下:
<?xml version="1.0" encoding="UTF-8" ?> <!-- Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <!DOCTYPE log4j:configuration SYSTEM "log4j.dtd"> <log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/"> <!-- - This is a sample configuration for log4j. - It simply just logs everything into a single log file. - Note, that you can use properties for value substitution. --> <appender name="CORE" class="org.apache.log4j.FileAppender"> <param name="File" value="${org.apache.cocoon.work.directory}/cocoon-logs/log4j.log" /> <param name="Append" value="false" /> <layout class="org.apache.log4j.PatternLayout"> <param name="ConversionPattern" value="%d %-5p %t %c - %m%n"/> </layout> </appender> <root> <priority value="${org.apache.cocoon.log4j.loglevel}"/> <appender-ref ref="CORE"/> </root> </log4j:configuration>
三、mybatis配置
能夠使用註解或者xml的方式配置sql操做,這裏使用註解方式:
// 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> <!-- development:開發模式 work:工做模式 --> <environments default="development"> <environment id="development"> <transactionManager type="JDBC" /> <dataSource type="POOLED"> <property name="driver" value="com.mysql.jdbc.Driver" /> <property name="url" value="jdbc:mysql://localhost:3306/ssm" /> <property name="username" value="root" /> <property name="password" value="root" /> </dataSource> </environment> </environments> <!--<mappers> <mapper resource="userMapper.xml" /> </mappers>--> <mappers> <mapper class="com.ssm.Mapper.UserMapper"/> </mappers> </configuration>
使用xml方式:
// 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"> <mapper namespace="userMapper"> <!--根據ID獲取對應的值 --> <select id="findUserById" parameterType="int" resultType="com.ssm.model.User"> select * from user where id = #{id} </select> <insert id="addUser" parameterType="com.ssm.model.User"> insert into user(username,password) values(#{username},#{password}) </insert> </mapper>
在main文件夾下建立文件夾java,點擊右鍵將java做爲source文件夾:
Controller
// MainController.java package com.ssm.controller; import com.ssm.model.User; import com.ssm.service.IUserService; import com.ssm.service.UserServiceImpl; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import java.util.List; @Controller public class MainController { private IUserService service = new UserServiceImpl(); @RequestMapping(value = "/hello", method = RequestMethod.GET) public String index(User user) { return "index"; } @RequestMapping(value="/nice",method = RequestMethod.GET) @ResponseBody public List<User> nice(Model model){ return service.getAllUsers(); } @RequestMapping(value ="/toJson",method=RequestMethod.POST) @ResponseBody public User toJson(User user){ service.addUser(user); //一塊兒測試了 return service.findUserById(2); } }
DAO
// IUserDao.java package com.ssm.Dao; import com.ssm.model.User; import java.util.List; public interface IUserDao { public User findUserById(int id); //查詢 public void addUser(User user); //添加 public List<User> getAllUsers(); } // UserDaoImpl.java package com.ssm.Dao; import com.ssm.Mapper.UserMapper; import com.ssm.model.User; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import java.io.IOException; import java.io.Reader; import java.util.List; public class UserDaoImpl implements IUserDao{ private SqlSessionFactory sessionFactory; private SqlSession session; private UserMapper mapper; public UserDaoImpl() { String resource = "config.xml"; // try { // Reader reader = Resources.getResourceAsReader(resource); // sessionFactory = new SqlSessionFactoryBuilder().build(reader); // session = sessionFactory.openSession(); // } catch (IOException e) { // e.printStackTrace(); // } try { Reader reader = Resources.getResourceAsReader(resource); sessionFactory = new SqlSessionFactoryBuilder().build(reader); session = sessionFactory.openSession(); mapper = session.getMapper(UserMapper.class); } catch (IOException e) { e.printStackTrace(); } } public User findUserById(int id) { // String statement = "userMapper.findUserById"; // User user = (User)session.selectOne(statement, 1); // return user; return mapper.findUserById(id); } public void addUser(User user) { // String statement = "userMapper.addUser"; // session.insert(statement, user); // session.commit(); //必定要記得commit mapper.addUser(user); session.commit(); } public List<User> getAllUsers() { return mapper.getAllUsers(); } }
Mapper
// UserMapper.java package com.ssm.Mapper; import com.ssm.model.User; import org.apache.ibatis.annotations.Insert; import org.apache.ibatis.annotations.Select; import java.util.List; public interface UserMapper { @Select("select * from user where id = #{id}") User findUserById(int id); @Insert("insert into user(username,password) values(#{username},#{password})") void addUser(User user); @Select("select * from user") List<User> getAllUsers(); }
Model
// User.java package com.ssm.model; public class User { private String username; private String password; private int id; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public User(String username, String password, int id) { this.username = username; this.password = password; this.id = id; } public User(String username, String password) { this.username = username; this.password = password; } public int getId() { return id; } public void setId(int id) { this.id = id; } public User() { } }
service
// IUserService.java package com.ssm.service; import com.ssm.model.User; import java.util.List; public interface IUserService { public User findUserById(int id); public void addUser(User user); public List<User> getAllUsers(); } // UserServiceImpl.java package com.ssm.service; import com.ssm.Dao.IUserDao; import com.ssm.Dao.UserDaoImpl; import com.ssm.model.User; import java.util.List; public class UserServiceImpl implements IUserService { private IUserDao userDao; public UserServiceImpl() { userDao = new UserDaoImpl(); } public User findUserById(int id) { return userDao.findUserById(id); } public void addUser(User user){ userDao.addUser(user); } public List<User> getAllUsers() { return userDao.getAllUsers(); } }
// index.jsp <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib prefix="sf" uri="http://www.springframework.org/tags/form" %> <html> <body> <h2>Hello World!</h2> <sf:form method="post" modelAttribute="user" action="/toJson"> 用戶名:<sf:input path="username"/> 密碼:<sf:password path="password"/> <input type="submit" value="提交"> </sf:form> </body> </html> // nice.jsp <%-- Created by IntelliJ IDEA. User: Administrator Date: 2017/10/9 Time: 8:01 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>nice to meet you!</title> </head> <body> <br/> <div> ${result} </div> </body> </html>
// ssm.sql /* Navicat MySQL Data Transfer Source Server : localhost Source Server Version : 50554 Source Host : localhost:3306 Source Database : ssm Target Server Type : MYSQL Target Server Version : 50554 File Encoding : 65001 Date: 2017-10-22 18:19:30 */ SET FOREIGN_KEY_CHECKS=0; -- ---------------------------- -- Table structure for user -- ---------------------------- DROP TABLE IF EXISTS `user`; CREATE TABLE `user` ( `id` int(11) NOT NULL AUTO_INCREMENT, `username` varchar(255) NOT NULL, `password` varchar(255) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8; -- ---------------------------- -- Records of user -- ---------------------------- INSERT INTO `user` VALUES ('1', 'guo', '111'); INSERT INTO `user` VALUES ('2', 'root', 'aaa'); INSERT INTO `user` VALUES ('3', '11111', '22222');