三:搭建SpringMVC的框架
1. 建立Java web 项目,版本号选择2.5.
2. 删除src ,右键选择Source Folder,创建名为src/test/java、src/test/resource、src/main/java、src/main/resourse的文件夹。
3. 考入如图所示的jar包
4. 在web.xml中创建Spring容器并添加对象,代码如下:
<?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_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>jdweb</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>DispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- 执行init()方法时获取相关参数,写在DispatcherServlet中,代表当Tomcat启动时此servlet调用init()方法,加载classpath:application.xml,产生一个Spring容器,并且开始扫描,将对象放入容器中 -->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:application.xml</param-value>
</init-param>
<!-- 在服务器启动时创建servlet对象 -->
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>DispatcherServlet</servlet-name>
<!--/表示拦截所有请求-->
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
注:org.springframework.web.servlet.DispatcherServlet的路径可以在Java Resourses 下的 Libraries下获取路径。这是Spring-webmvc jar包中封装好的servlet文件,主要用作职责调度工作,本身主要用于控制流程。就是不在人为为创建获取对象容器了。
5. application.xml文件的创建与配置,在src/main/resourses中,右键选择Spring Bean Configuration File创建该文件。(名字是自由的取的)
然后在application.xml的页面下方点击namespace勾选如下图所示:
最后配置application.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/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
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.3.xsd">
<!-- 为com.jd包下的带service,Controller,Component注解的类创建对象 -->
<context:component-scan base-package="com.jd"></context:component-scan>
<!-- 所有的请求都会进入DispatcherServlet的servlet中(切片搜索map集合),若该controll中无方法(根据@RequestMapping("userInfo/Login.do")注释判断)处理该请求,则会执行以下语句,用服务器自己处理(进一步搜索本地资源) -->
<mvc:default-servlet-handler/>
<mvc:annotation-driven></mvc:annotation-driven>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/view/"></property>
<property name="suffix" value=".html"></property>
</bean>
</beans>
小结一下其中的知识点:
(1)load-on-startup:服务器启动时创建Servlet对象
(2)获取contextConfigLocation值
(3)classpath:application.xml:创建Spring容器+实例化类
(4)若该类中含有@controller注解,则将该类中方法上@RequestMapping中的value值添加到Map集合中
(5)任何一个请求过来,就与Map集合中的已有的Servlet匹配
(6)如果在Map集合中没找到,不用等待,就用默认Servlet处理。
6. 注解的使用讲解
- @Component、@Repository、@Controller、@Service所注释的类才会在
<context:component-scan base-package="com.jd"></context:component-scan>
中被代码识别,在Spring容器中创建相应的对象。
2. @Controller :通常加在以controller结尾的类上,该类通常是处理浏览器请求的控制类(类似于servlet类处理get,post请求)
3. @Repository:通常加在Dao层上。(最总处理客户端浏览器请求的类)
4. @Service:通常加在Service层上。(对客户端传送的数据进行加工)
5. @Autowired:在对象上加上该注释,表示创建对象(调用Spring容器中创建好的对象)
7. 层次的创建,建立如图所示的结构
各文件代码如下:
package com.jd.userInfo;
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.RequestMethod;
@Controller
public class UserInfoController {
@Autowired
private IUserInfoService userInfoService;
@RequestMapping(value="/userInfo/Login.do", method=RequestMethod.POST)
public String login(String userName,String password) {
System.out.println(userName+":"+password);
if(userInfoService.login(userName,password)) {
return "success";
}
else {
return "fail";
}
}
}
package com.jd.tool.db;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import com.mysql.jdbc.Connection;
/**
* 数据库连接工具类
*
* @author
*/
public class Dbtools {
static {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
System.out.printf(e.getMessage(), e);
}
}
/**
* 获取数据库连接
*
* @author
*/
private static Connection getConnection() {
@SuppressWarnings("unused")
Connection connection = null;
try {
return connection = (Connection) DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/venus", "root",
"root");
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
/**
* 释放数据库资源(Statement和Connection)
*
* @author
*/
private static void close(PreparedStatement preparedStatement, Connection connection) {
try {// 注意顺序,先关statement再关connection
if (preparedStatement != null) {
preparedStatement.close();
}
} catch (SQLException e) {
System.out.printf(e.getMessage(), e);
}
try {
if (connection != null) {
connection.close();
}
} catch (SQLException e) {
System.out.printf(e.getMessage(), e);
}
}
/**
* 释放数据库资源(ResultSet、Statement和Connection)
*
* @author
*/
private static void close(ResultSet resultset, PreparedStatement preparedStatement, Connection connection) {
try {
if (resultset != null) {
resultset.close();
}
} catch (SQLException e) {
System.out.printf(e.getMessage(), e);
}
close(preparedStatement, connection);
}
/**
* 数据的选择
*
* @author
*/
public static void select(String sql, IRowMapper rowMappper, Object... params) {
Connection connection = getConnection();
PreparedStatement preparedStatement = null;
ResultSet resultset = null;
try {
preparedStatement = connection.prepareStatement(sql);
for (int i = 0; i < params.length; i++) {
preparedStatement.setObject(i + 1, params[i]);
}
resultset = preparedStatement.executeQuery();
rowMappper.rowMapper(resultset);
} catch (SQLException e) {
System.out.printf(e.getMessage(), e);
} finally {
close(resultset, preparedStatement, connection);
}
}
/**
* 数据的修改(delect、insert和update)
*
* @author
*/
public static boolean data(String sql, Object... params) {
Connection connection = getConnection();
PreparedStatement prepareStatement = null;
int result = 0;
try {
prepareStatement = connection.prepareStatement(sql);// 创建修改环境。
for (int i = 0; i < params.length; i++) {
prepareStatement.setObject(i + 1, params[i]);
}
result = prepareStatement.executeUpdate();
} catch (SQLException e) {
System.out.printf(e.getMessage(), e);
} finally {
close(prepareStatement, connection);
}
return result > 0;
}
}
package com.jd.tool.db;
import java.sql.ResultSet;
public interface IRowMapper {
public void rowMapper(ResultSet resultset);
}
package com.jd.userInfo.imp;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.springframework.stereotype.Repository;
import com.jd.tool.db.Dbtools;
import com.jd.tool.db.IRowMapper;
import com.jd.userInfo.IUserInfoDao;
@Repository
public class UserInfoDao implements IUserInfoDao {
public boolean login(String userName, String password) {
String sql="select userName from userinfo where userName=? and password=?";
class RowMapper implements IRowMapper{
boolean state;
public void rowMapper(ResultSet resultset) {
try {
if(resultset.next()) {
state = true;
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
RowMapper rowMapper = new RowMapper();
Dbtools.select(sql, rowMapper, userName,password);
return rowMapper.state;
}
}
package com.jd.userInfo.imp;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.jd.userInfo.IUserInfoDao;
import com.jd.userInfo.IUserInfoService;
@Service
public class UserInfoService implements IUserInfoService {
@Autowired
private IUserInfoDao userInfoDao;
public boolean login(String userName, String password) {
return userInfoDao.login(userName, password);
}
}
package com.jd.userInfo;
public interface IUserInfoDao {
boolean login(String userName,String password);
}
package com.jd.userInfo;
public interface IUserInfoService {
boolean login(String userName,String password);
}
package com.jd.userInfo;
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.RequestMethod;
@Controller
public class UserInfoController {
@Autowired
private IUserInfoService userInfoService;
@RequestMapping(value="/userInfo/Login.do", method=RequestMethod.POST)
public String login(String userName,String password) {
System.out.println(userName+":"+password);
if(userInfoService.login(userName,password)) {
return "success";
}
else {
return "fail";
}
}
}
注:接口上不需要加任何有关Spring的注释
8. web的文件如下:
注:ecplise在写jsp的文件时会提示莫名其妙的错误,但是文件本身并没有出错。jsp放在WEB-INF文件夹下,会更加安全(只能有请求转发访问)
各jsp文件如下:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
NO
</body>
</html>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+request.getContextPath()+"/";
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<body>
<form action="<%=basePath %>userInfo/Login.do" method="post">
<input name="userName"/>
<input type="password" name="password"/>
<input type="submit" value="登陆"/>
</form>
</body>
</body>
</html>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
OK!
</body>
</html>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<script type="text/javascript">
location.href="./index/index.do";
</script>