SSM开发实例(基于spring 3.X)
来源:互联网 发布:python 回滚 编辑:程序博客网 时间:2024/06/07 03:13
基于spring 3.X项目开发实例
此示例采用的是:spring MVC+MyBatis+spring的开发架构。
1. 导入相关jar包,页面结构如下:
后台结构如下图:
2. 创建数据表和实体类
public class User {
private Integerid;
private StringuserName;
private Stringpassword;
private Stringtel;
private Stringemail;
//省略get/set
}
3. 创建数据访问接口(MyBatis不需要实现类,所以只创建接口即可)
public interface UserMapper {
public List<User> getUserList();
public User getUser(Useruser);
public int insertUser(Useruser);
public int deleteUser(Useruser);
public int updateUser(Useruser);
}
4. MyBatis接口映射文件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="org.project.dao.user.UserMapper">
<!-- getUserList -->
<select id="getUserList" resultType="user" parameterType="user">
select * from user order by id desc
</select>
<!-- getUser -->
<select id="getUser" resultType="user" parameterType="user">
select * from user where username = #{userName} and password = #{password}
</select>
<!-- insertUser -->
<insert id="insertUser" parameterType="user">
insert into user (username,password,tel,email) values (
#{userName},#{password},#{tel},#{email}
)
</insert>
<!-- deleteUser -->
<delete id="deleteUser" parameterType="user">
delete from user where id = #{id}
</delete>
<!-- updateUser -->
<update id="updateUser" parameterType="user">
update user set password = #{password}, tel = #{tel}, email = #{email}
where id = #{id}
</update>
</mapper>
5. 编写Service接口及实现类
public interface UserService {
/**
* getUserList
* @return
*/
public List<User> getUserList();
/**
* getUser
* @param user
* @return user
*/
public User getUser(Useruser);
/**
* insertUser
* @param user
* @return int
*/
public int insertUser(Useruser);
/**
* deleteUser
* @param user
* @return int
*/
public int deleteUser(Useruser);
/**
* updateUser
* @param user
* @return int
*/
public int updateUser(Useruser);
}
@Service
public class UserServiceImplimplements UserService {
@Resource
private UserMappermapper;
public int deleteUser(Useruser) {
// TODO Auto-generated method stub
return mapper.deleteUser(user);
}
public User getUser(Useruser) {
// TODO Auto-generated method stub
return mapper.getUser(user);
}
public List<User> getUserList() {
// TODO Auto-generated method stub
return mapper.getUserList();
}
public int insertUser(Useruser) {
// TODO Auto-generated method stub
return mapper.insertUser(user);
}
public int updateUser(Useruser) {
// TODO Auto-generated method stub
return mapper.updateUser(user);
}
}
6. 编写Controller
@Controller //类似Struts的Action
public class IndexController {
private Loggerloger = Logger.getLogger(IndexController.class);
@Resource
private UserServiceuserService;
@RequestMapping("/index.html") //请求url地址映射,类似Struts的action-mapping
public String index() {
loger.debug("IndexController index.userService:" +userService );
return "index";
}
@RequestMapping("/register.html")
public String register(){
return "register";
}
@RequestMapping("/exit.html") //请求url地址映射,类似Struts的action-mapping
public String exit() {
loger.debug("IndexController exit.");
return "exit";
}
@RequestMapping("/login.html")
public String login(){
return "login";
}
@RequestMapping("/loginsuccess.html") //请求url地址映射,类似Struts的action-mapping
public ModelAndView loginsuccess(Useruser) {
loger.debug("IndexController login.username : " +user.getUserName()
+ " --- password:"+user.getPassword());
user =userService.getUser(user);
loger.debug("select username : " +user.getUserName()
+ " --- password:"+user.getPassword());
return new ModelAndView("loginsuccess");
}
@RequestMapping("/regsuccess.html")
public ModelAndView regsuccess(Useruser){
loger.debug("IndexController register.username : " +user.getUserName()
+ "---- password: " +user.getPassword());
int f =userService.insertUser(user);
if(f > 0){
user =userService.getUser(user);
}
return new ModelAndView("regsuccess");
}
}
7. 编写spring配置文件applicationContext-mybatis.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:aop="http://www.springframework.org/schema/aop"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:tx="http://www.springframework.org/schema/tx"
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/aop http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<!-- Properties文件读取配置,base的properties -->
<context:property-placeholder location="classpath:jdbc.properties"/>
<!-- JNDI获取数据源(使用dbcp连接池) -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close" scope="singleton">
<property name="driverClassName" value="${driverClassName}"/>
<property name="url" value="${url}"/>
<property name="username" value="${uname}"/>
<property name="password" value="${password}"/>
</bean>
<!-- enable transaction demarcation with annotations -->
<tx:annotation-driven />
<!-- (事务管理)transaction manager, use JtaTransactionManager for globaltx -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
<!-- define the SqlSessionFactory, notice that configLocation is not needed when you use MapperFactoryBean -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation" value="classpath:mybatis-config.xml" />
</bean>
<!-- scan for mappers and let them beautowired
MapperScannerConfigurer Mybatis-Spring会自动为我们注册Mapper对应的MapperFactoryBean对象-->
<!-- Mapper接口所在包名,Spring会自动查找其下的Mapper -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="org.project.dao" />
</bean>
</beans>
8. spring配置文件springmvc-servlet.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"
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">
<!-- 使spring扫描包下的所有类,让标注spring注解的类生效-->
<context:component-scan base-package="org.project"/>
<!-- 对转向页面的路径解析。prefix:前缀,suffix:后缀-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/pages/"/>
<property name="suffix" value=".jsp"/>
</bean>
</beans>
9. JDBC属性文件 jdbc.properties【注:log4j的配置文件自己去找。】
driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/springmvcdb?useUnicode=true&characterEncoding=UTF-8
uname=root
password=123456
minIdle=10
maxIdle=50
initialSize=5
maxActive=100
maxWait=100
removeAbandonedTimeout=180
removeAbandoned=true
10. 修改web.xml配置文件:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
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_2_5.xsd">
<!-- 指定Spring Bean的配置文件所在目录。默认配置在WEB-INF目录下-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext-*.xml</param-value>
</context-param>
<!-- spring字符编码过滤器start-->
<filter>
<!--① Spring 编码过滤器-->
<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>
<!-- ② 过滤器的匹配URL -->
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- spring字符编码过滤器end-->
<!-- ====================================== -->
<!-- Spring MVC配置-->
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!-- ====================================== -->
<!-- Spring配置 -->
<listener><listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- log4j配置start -->
<context-param>
<param-name>log4jConfigLocation</param-name>
<param-value>classpath:log4j.properties</param-value>
</context-param>
<!-- Spring 加载Log4j 的监听-->
<listener>
<listener-class>
org.springframework.web.util.Log4jConfigListener
</listener-class>
</listener>
<!-- log4j配置end -->
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
11. MyBatis的主配置文件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>
<settings>
<!-- changes from the defaults -->
<setting name="lazyLoadingEnabled" value="false" />
</settings>
<typeAliases>
<!--这里给实体类取别名,方便在mapper配置文件中使用-->
<package name="org.project.pojo"/>
</typeAliases>
</configuration>
12. register.jsp
<body>
This is register JSP page. <br>
<form action="regsuccess.html" method="post">
username:<input type="text" name="userName"/><br/>
password:<input type="text" name="password"/><br/>
tel: <input type="text" name="tel"/><br/>
email: <input type="text" name="email"/><br/>
<input type="submit" value="submit"/><br/>
</form>
</body>
13. regsuccess.jsp
<body>
register success! <br>
<span>
username:${user.userName}
password:${user.password}
tel:${user.tel}
email: ${user.email}</span>
<A HREF="login.html">登录</A> <br/>
</body>
14. login.jsp与loginsuccess.jsp
<body>
This is my WEB-INF login JSP page. <br>
<form action="loginsuccess.html" method="post">
username: <input type="text" name="userName"/><br/>
password: <input type="text" name="password"/><br/>
<input type="submit" value="submit"/><br/>
</form>
</body>
<body>
This is my WEB-INF login JSP page. <br>
<A HREF="exit.html">退出页面</A> <br/>
<span>welcome:${user.userName}</span>
</body>
15. 附:Hibernate集成时的配置文件
<?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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
">
<context:component-scan base-package="com.sxt"/>
<!-- 支持aop注解-->
<aop:aspectj-autoproxy />
<bean id="dataSource"
class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName"
value="com.mysql.jdbc.Driver">
</property>
<property name="url" value="jdbc:mysql://localhost:3306/myhib"></property>
<property name="username" value="root"></property>
<property name="password" value="123456"></property>
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource">
<ref bean="dataSource" />
</property>
<property name="hibernateProperties">
<props>
<!-- key的名字前面都要加hibernate. -->
<prop key="hibernate.dialect">
org.hibernate.dialect.MySQLDialect
</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
</props>
</property>
<property name="packagesToScan">
<value>com.sxt.po</value>
</property>
</bean>
<bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate" >
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<!--配置一个JdbcTemplate实例-->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"/>
</bean>
<!-- 配置事务管理 -->
<bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager" >
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<tx:annotation-driven transaction-manager="txManager" />
<aop:config>
<aop:pointcut expression="execution(public * com.sxt.service.impl.*.*(..))" id="businessService"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="businessService" />
</aop:config>
<tx:advice id="txAdvice" transaction-manager="txManager" >
<tx:attributes>
<tx:method name="find*" read-only="true" propagation="NOT_SUPPORTED" />
<!-- get开头的方法不需要在事务中运行 。
有些情况是没有必要使用事务的,比如获取数据。开启事务本身对性能是有一定的影响的-->
<tx:method name="*"/> <!--其他方法在实务中运行 -->
</tx:attributes>
</tx:advice>
</beans>
16. 运行,测试。
- SSM开发实例(基于spring 3.X)
- 基于maven和SSM(spring+springMVC+mybatis)的实例
- SSM(Spring+SpringMVC+Mybatis)登录实例
- 基于Struts 2.x + Spring 2.x + Hibernate 3.x整合开发
- 基于SSM 开发
- ssm框架实例开发
- ssm整合开发实例
- RESTLET开发实例(三)基于spring的REST服务
- RESTLET开发实例(三)基于spring的REST服务
- java开发ssm-spring
- Restlet - 基于Spring的Restlet开发实例
- SSM搭建-Spring mvc基于注解的配置(13)
- 基于Maven的SSM框架整合(Spring+SpringMVC+MyBatis)
- 基于现如今流行的SSM(spring springMVC mybatis mysql)框架的hrm人事管理系统后台实例
- 简单易懂的ssm(spring mvc,mybatis,spring)开发实例分析
- 基于(ssm,websocket,mysql)开发的web聊天系统
- 基于maven搭建ssm开发框架(1) mybatis和spring的整合
- 基于maven搭建ssm开发框架(1) SpringMVC和spring的整合
- 常用命令
- 事件代理的实际应用
- 身份证号检测工具
- BZOJ 4563: [Haoi2016]放棋子
- protobuf安装使用(python版)
- SSM开发实例(基于spring 3.X)
- Attempt to set a non-property-list object null as an NSUserDefaults
- https是如何工作的?
- 【Java基础】Java分支结构
- Tomcata-Tomcat的系统安全管理
- 智能化将对企业产生四方面影响
- MySQL 1055错误
- Eclipse 打开Eclipse Marketplace报错:Cannot open Eclipse Marketplace
- 直接插入排序