标签:common 乱码 反转 include hashmap xxx 复杂 local 系统
Spring 是一个开源框架, Spring 是于 2003 年兴起的一个轻量级的 Java 开发框架,由 Rod Johnson 在其著作 Expert One-On-One J2EE Development and Design 中阐述的部分理念和原型衍生而来。它是为了解决企业应用开发的复杂性而创建的。 Spring 使用基本的 JavaBean 来完成以前只可能由 EJB 完成的事情。然而, Spring 的用途不仅限于服务器端的开发。从简单性、可测试性和松耦合的角度而言,任何 Java 应用都可以从 Spring 中受益。 简单来说, Spring 是一个轻量级的控制反转( IoC )和面向切面( AOP )的容器框架。
Spring MVC 属于 SpringFrameWork 的后续产品,已经融合在 Spring Web Flow 里面。 Spring MVC 分离了控制器、模型对象、分派器以及处理程序对象的角色,这种分离让它们更容易进行定制。
MyBatis 本是 Apache 的一个开源项目iBatis , 2010 年这个项目由 apache software foundation 迁移到了 google code ,并且改名为 MyBatis 。 MyBatis 是一个基于 Java 的 持久层框架。 iBATIS 提供的持久层框架包括 SQL Maps 和 Data Access Objects ( DAO ) MyBatis 消除了几乎所有的 JDBC 代码和参数的手工设置以及结果集的检索。 MyBatis 使用简单的 XML 或注解用于配置和原始映射,将接口和 Java 的 POJOs ( Plain Old Java Objects ,普通的 Java 对象)映射成数据库中的记录。
3、SSM项目结构搭建
①Spring:
spring-aop-4.3.0.RELEASE.jar
spring-aspects-4.3.0.RELEASE.jar
spring-beans-4.3.0.RELEASE.jar
spring-context-4.3.0.RELEASE.jar
spring-context-support-4.3.0.RELEASE.jar
spring-core-4.3.0.RELEASE.jar
spring-expression-4.3.0.RELEASE.jar
spring-jdbc-4.3.0.RELEASE.jar
spring-tx-4.3.0.RELEASE.jar
spring-web-4.3.0.RELEASE.jar
spring-webmvc-4.3.0.RELEASE.jar
spring-webmvc-portlet-4.3.0.RELEASE.jar
spring-websocket-4.3.0.RELEASE.jar
com.springsource.net.sf.cglib-2.2.0.jar
com.springsource.org.aopalliance-1.0.0.jar
com.springsource.org.aspectj.weaver-1.6.8.RELEASE.jar
commons-logging-1.2.jar
③MyBatis:
mybatis-3.1.1.jar
log4j-1.2.16.jar
mybatis-spring-1.2.1.jar
④文件上传/下载:
commons-fileupload-1.2.2.jar
commons-io-2.4.jar
⑤C3P0数据源:
c3p0-0.9.5.1.jar
mchange-commons-java-0.2.10.jar
classmate-0.8.0.jar
⑥MySQL:
mysql-connector-java-5.0.8-bin.jar
⑦JSTL:
taglibs-standard-compat-1.2.5.jar
taglibs-standard-impl-1.2.5.jar
taglibs-standard-jstlel-1.2.5.jar
taglibs-standard-spec-1.2.5.jar
⑧JSON:
jackson-annotations-2.6.0.jar
jackson-core-2.6.0.jar
jackson-databind-2.6.0.jar
⑨Hibernate Validate:
hibernate-validator-4.3.0.Final.jar
validation-api-1.0.0.GA.jar
validation-api-1.1.0.CR1.jar
jboss-logging-3.1.0.CR2.jar
jboss-logging-3.1.1.GA.jar
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
id="WebApp_ID" version="3.1">
<display-name>SSM_01</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<!-- 1、配置 Spring 配置文件的名称和位置 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring/applicationContext.xml</param-value>
</context-param>
<!-- ContextLoaderListener:监听器 -->
<!--当 web项目已启动的时候,会把 Spring IOC 容器获取到,并放入 application 域中 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 2、配置 SpringMVC 的前端控制器(要过滤所有的请求) -->
<servlet>
<servlet-name>springDispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- 配置 SpringMVC 配置文件的名称和位置 -->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc/springMvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springDispatcherServlet</servlet-name>
<!-- SpringMVC 的前端控制器过滤所有的请求 -->
<url-pattern>/</url-pattern>
</servlet-mapping>
<!-- 3、配置 CharacterEncodingFilter:映射出现乱码 -->
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<async-supported>true</async-supported>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- 4、配置 HiddenHttpMethodFilter:支持 REST 风格的 CRUD -->
<filter>
<filter-name>HiddenHttpMethodFilter</filter-name>
<filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>HiddenHttpMethodFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
<?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:tx="http://www.springframework.org/schema/tx"
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.3.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">
<!-- 1、配置自动扫描的(Spring IOC 容器不扫描Controller) -->
<context:component-scan base-package="cn.com.zfc.ssm">
<context:include-filter type="annotation"
expression="org.springframework.stereotype.Component" />
<context:include-filter type="annotation"
expression="org.springframework.stereotype.Repository" />
<context:include-filter type="annotation"
expression="org.springframework.stereotype.Service" />
</context:component-scan>
<!-- 2.加载配数据源配置文件 db.properties -->
<context:property-placeholder location="classpath:db.properties" />
<!-- 3、配置 C3P0 数据源 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="user" value="${user}"></property>
<property name="password" value="${password}"></property>
<property name="jdbcUrl" value="${jdbcUrl}"></property>
<property name="driverClass" value="${driverClass}"></property>
</bean>
<!-- 4.事务管理器 (JDBC) -->
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 5.启动声明式事务驱动 -->
<tx:annotation-driven transaction-manager="transactionManager" />
<!-- MyBatis 整合 spring -->
<!-- 1. spring 通过 sqlSessionFactoryBean 获取 sqlSessionFactory 工厂类 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<!-- 使用mapper 时可以实用化别名(BeanName) -->
<property name="typeAliasesPackage" value="cn.com.zfc.ssm.entity"></property>
</bean>
<!-- 2.打开 sqlSession 会话对象(扫描映射配置文件:XXXmapper.xml/XXXmapper.java) -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="cn.com.zfc.ssm.dao" />
<!-- 注意使用 sqlSessionFactoryBeanName 避免出现spring 扫描组件失效问题 -->
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
</bean>
</beans>
<?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" xmlns:aop="http://www.springframework.org/schema/aop"
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
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd">
<!-- 1、配置自动扫描的包,SpringMVC IOC 容器只扫描Controller -->
<context:component-scan base-package="cn.com.zfc.ssm">
<context:include-filter type="annotation"
expression="org.springframework.stereotype.Controller" />
</context:component-scan>
<!-- 2、配置视图解析器 -->
<bean id="internalResourceViewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
<!-- 3.处理静态资源,默认 Servlet 处理 -->
<mvc:default-servlet-handler />
<!-- 4.启动 MVC 注解驱动 -->
<mvc:annotation-driven />
<!--5、启用AOP -->
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
</beans>
user=root
password=root
driverClass=com.mysql.jdbc.Driver
jdbcUrl=jdbc:mysql://localhost:3306/ssm_01
# Global logging configuration
log4j.rootLogger=DEBUG, stdout
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
log4j.logger.java.sql.ResultSet=INFO
log4j.logger.org.apache=INFO
log4j.logger.java.sql.Connection=DEBUG
log4j.logger.java.sql.Statement=DEBUG
log4j.logger.java.sql.PreparedStatement=DEBUG
package cn.com.zfc.ssm.entity;
import org.springframework.stereotype.Component;
/**
* 定义实体类:如果实体类的属性名和数据表中的字段名不一致,则需要在 映射文件中配置 resultMap
*
* @author FuchangZhang
*
*/
@Component
public class User {
private Integer id;
private String userName;
private String userSex;
private Integer userAge;
public User() {
super();
}
public User(String userName, String userSex, Integer userAge) {
super();
this.userName = userName;
this.userSex = userSex;
this.userAge = userAge;
}
public User(Integer id, String userName, String userSex, Integer userAge) {
super();
this.id = id;
this.userName = userName;
this.userSex = userSex;
this.userAge = userAge;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getUserSex() {
return userSex;
}
public void setUserSex(String userSex) {
this.userSex = userSex;
}
public Integer getUserAge() {
return userAge;
}
public void setUserAge(Integer userAge) {
this.userAge = userAge;
}
@Override
public String toString() {
return "User [id=" + id + ", userName=" + userName + ", userSex=" + userSex + ", userAge=" + userAge + "]";
}
}
3.9 UserMapper.java
package cn.com.zfc.ssm.dao;
import java.util.List;
import org.springframework.stereotype.Repository;
import cn.com.zfc.ssm.entity.User;
/**
* 定义接口:方法名得和相应的 mapper.xml 中的 id 保持一致
*
* @author FuchangZhang
*
*/
@Repository
public interface UserMapper {
// 添加一条用户信息
public int save(User user);
// 删除一条用户信息
public int delete(int id);
// 修改一条用户信息
public int update(User user);
// 查询一条用户信息
public User getUser(int id);
// 查询全部用户信息
public List<User> getUsers();
}
3.10 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="cn.com.zfc.ssm.dao.UserMapper">
<!-- 结果集映射:映射实体类属性与数据表字段名 -->
<resultMap type="User" id="userResultMap">
<id property="id" column="id" />
<result property="userName" column="user_name" />
<result property="userSex" column="user_sex" />
<result property="userAge" column="user_age" />
</resultMap>
<!-- 参数映射:映射实体类属性与数据表字段名 -->
<!-- resultMap:resultMap的id ,property:resultMap的property,即实体类中的属性 -->
<parameterMap type="User" id="userParameterMap">
<parameter property="id" resultMap="userResultMap" />
<parameter property="userName" resultMap="userResultMap" />
<parameter property="userSex" resultMap="userResultMap" />
<parameter property="userAge" resultMap="userResultMap" />
</parameterMap>
<!-- 添加一个用户信息 -->
<insert id="save" parameterMap="userParameterMap">
insert into user_info
(user_name,user_sex,user_age)
values
(#{userName},#{userSex},#{userAge})
</insert>
<!-- 删除一个用户信息 -->
<delete id="delete" parameterType="int">
delete from user_info
where
id=#{id}
</delete>
<!-- 修改一个用户信息 -->
<update id="update" parameterMap="userParameterMap">
update user_info
set
user_name=#{userName},user_sex=#{userSex},user_age=#{userAge}
where
id=#{id}
</update>
<!-- 查询一个用户信息 -->
<select id="getUser" parameterType="int" resultMap="userResultMap">
select * from
user_info
where
id=#{id}
</select>
<!-- 查询全部用户信息 -->
<select id="getUsers" resultMap="userResultMap">
select * from user_info
</select>
</mapper>
3.11、UserService.java
package cn.com.zfc.ssm.service;
import java.util.List;
import org.springframework.stereotype.Repository;
import cn.com.zfc.ssm.entity.User;
@Repository
public interface UserService {
// 添加一条用户信息
public boolean add(User user);
// 删除一条用户信息
public boolean delete(int id);
// 修改一条用户信息
public boolean update(User user);
// 查询一条用户信息
public User queryOne(int id);
// 查询全部用户信息
public List<User> queryAll();
}
3.12、UserServiceImpl.java
package cn.com.zfc.ssm.service.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import cn.com.zfc.ssm.dao.UserMapper;
import cn.com.zfc.ssm.entity.User;
import cn.com.zfc.ssm.service.UserService;
@Service("userService")
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
private int result;
@Override
public boolean add(User user) {
result = userMapper.save(user);
if (result > 0) {
return true;
} else {
return false;
}
}
@Override
public boolean delete(int id) {
result = userMapper.delete(id);
if (result > 0) {
return true;
} else {
return false;
}
}
@Override
public boolean update(User user) {
result = userMapper.update(user);
if (result > 0) {
return true;
} else {
return false;
}
}
@Override
public User queryOne(int id) {
User user = userMapper.getUser(id);
return user;
}
@Override
public List<User> queryAll() {
List<User> users = userMapper.getUsers();
return users;
}
}
3.13、UserHandler.java
package cn.com.zfc.ssm.handler;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import cn.com.zfc.ssm.entity.User;
import cn.com.zfc.ssm.service.UserService;
@Controller
public class UserHandler {
@Autowired
private UserService userService;
// 添加页面
@RequestMapping("/addView")
public String addView(Map<String, Object> map) {
map.put("user", new User());
return "addUser";
}
// 保存操作
@RequestMapping("/addUser")
public String addUser(User user) {
if (userService.add(user)) {
return "success";
} else {
return "redirect:/queryAll";
}
}
// 删除操作
@RequestMapping("/delete")
public String delete(int id) {
if (userService.delete(id)) {
System.out.println("删除成功");
} else {
System.out.println("删除失败");
}
return "redirect:/queryAll";
}
// 查询一个操作
@RequestMapping("/queryOne")
public String queryOne(int id, Map<String, Object> map) {
map.put("user", userService.queryOne(id));
return "update";
}
// 修改操作
@RequestMapping("/update")
public String update(User user, Map<String, Object> map) {
if (userService.update(user)) {
System.out.println("修改成功");
return "redirect:/queryAll";
} else {
System.out.println("修改失败");
map.put("user", userService.queryOne(user.getId()));
return "update";
}
}
// 查询全部操作
@RequestMapping("/queryAll")
public String queryAll(Map<String, Object> map) {
map.put("users", userService.queryAll());
return "queryAll";
}
}
3.14、index.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>
<a href="${pageContext.request.contextPath}/addView">添加用户</a>
<hr />
<a href="${pageContext.request.contextPath}/queryAll">查询全部</a>
</body>
</html>
3.15、addUser.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page import="java.util.*"%>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!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>用户添加</title>
</head>
<body>
<h1>用户添加</h1>
<form:form action="addUser" method="post" modelAttribute="user">
UserName:<form:input path="userName" />
<hr />
<%
Map<String, Object> sexes = new HashMap<>();
sexes.put("男", "男");
sexes.put("女", "女");
request.setAttribute("sexes", sexes);
%>
Sex:
<form:radiobuttons path="userSex" items="${sexes}" />
<hr />
UserAge:<form:input path="userAge" />
<hr />
<input type="submit" value="添加" />
</form:form>
</body>
</html>
3.16、success.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>
<h1>Success Page!!!</h1>
</body>
</html>
3.17、queryAll.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!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>
<style type="text/css">
table, tr, th, td {
border: 1px solid black;
}
table {
width: 80%;
}
</style>
</head>
<body>
<table>
<thead>
<tr>
<th>ID</th>
<th>UserName</th>
<th>UserSex</th>
<th>UserAge</th>
<th>Operator</th>
</tr>
</thead>
<tbody>
<c:choose>
<c:when test="${requestScope.users.size()>0 }">
<c:forEach items="${requestScope.users}" var="user">
<tr>
<td>${user.id }</td>
<td>${user.userName }</td>
<td>${user.userSex }</td>
<td>${user.userAge }</td>
<td><a
href="${pageContext.request.contextPath}/delete?id=${user.id}">Delete</a>
<a
href="${pageContext.request.contextPath}/queryOne?id=${user.id}">Update</a>
</td>
</tr>
</c:forEach>
</c:when>
<c:otherwise>没有人</c:otherwise>
</c:choose>
</tbody>
</table>
</body>
</html>
3.18、update.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page import="java.util.*"%>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!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>
<h1>用户修改</h1>
<form:form action="${pageContext.request.contextPath}/update"
method="post" modelAttribute="user">
<!-- 隐藏域:用来存储要修改的 user 的 id -->
<input type="hidden" name="id" value="${user.id}" />
UserName:<form:input path="userName" />
<hr />
<%
Map<String, Object> sexes = new HashMap<>();
sexes.put("男", "男");
sexes.put("女", "女");
request.setAttribute("sexes", sexes);
%>
Sex:
<form:radiobuttons path="userSex" items="${sexes}" />
<hr />
UserAge:<form:input path="userAge" />
<hr />
<input type="submit" value="修改" />
</form:form>
</body>
</html>
注:由于本人技术有限,此文章仅供参考
标签:common 乱码 反转 include hashmap xxx 复杂 local 系统
原文地址:http://www.cnblogs.com/zfc-java/p/6658577.html