实习第一天公司就把自己搭建好的SSH框架给我们看,并且要求在短时间内能够上手做基本表的增删改查,给我的一个例子是一个大的模块,使用Maven来管理和配置各个模块之间的关系,这对于初次步入职场的我显然是个不小的考验,首先数据库179张表就把我吓到了,再到后面划分模块的项目我基本连程序的入口都找不到,白白打了一天油。有图有真相:
哎,痛定思痛啊,谁让咱这菜呢,还是先把基础打好再慢慢研究吧,接着进入今天的主题,springMvc的基本配置。我使用的是Eclipse(之前一直用Myeclipse现在苦逼死了),首先还是新建一个Web项目:SpringMvc 首先在配置文件中加入:
<?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">
<servlet>
<!-- 配置Servlet 用来处理URL的请求,DiapatcherServlet会根据Url的请求来进行分发 ,如果有指定的Controller映射请求则交给相应的Controller处理-->
<servlet-name>dispatcherServlet</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name><!-- 通过配置指定 spring 和 servlet 的配置文件,可以自己指定 -->
<param-value>/WEB-INF/springContext.xml,/WEB-INF/spring-servlet.xml</param-value><!-- 指定文件的存放路径 -->
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<!-- 过滤指定的请求 -->
<url-pattern>*.do</url-pattern>
</servlet-mapping>
</web-app>
然后在WEB-INF 的路径下新建两个配置文件:springContext.xml 和 spting-servlet.xml 文件:
先看springContext.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: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-2.5.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd
">
<!-- 自动扫包,不需要我们再一个个的配置bean -->
<context:component-scan base-package="edu.hue.jk"/>
<!-- 支持aop注解 -->
<aop:aspectj-autoproxy />
<!-- 配置数据源,开发时候配置信息应该都是放在properties文件中的-->
<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/springMvc"></property>
<property name="username" value="root"></property>
<property name="password" value="xwjayw"></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">
<!-- 存放Entity 的包 -->
<value>edu.hue.jk.bean</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 * edu.hue.jk.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>
spring-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:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd">
<!-- 对web包中的所有类进行扫描,以完成Bean创建和自动依赖注入的功能 -->
<context:component-scan base-package="edu.hue.jk" />
<mvc:annotation-driven /> <!-- 支持spring3.0新的mvc注解 -->
<!-- 启动Spring MVC的注解功能,完成请求和注解POJO的映射 -->
<bean
class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="cacheSeconds" value="0" />
<property name="messageConverters">
<list>
<bean
class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"></bean>
</list>
</property>
</bean>
<!--对模型视图名称的解析,即在模型视图名称添加前后缀 -->
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:suffix=".jsp" >
<!-- 如果使用jstl的话,配置下面的属性 -->
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
</bean>
</beans>
配置文件写好之后我们需要导入相应的jar包:
<img src="https://img-blog.youkuaiyun.com/20140718093546211?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvdTAxMDc4NTk2OQ==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" alt="" />
<img src="https://img-blog.youkuaiyun.com/20140718093323906?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvdTAxMDc4NTk2OQ==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" alt="" />
1,首先还是配置实体:我的实体所在的包:edu.hue.jk.bean
import javax.persistence.*;
@Entity
@Table(name="tb_user")
public class User {
@Id
@GeneratedValue
@Column(name="user_id")
private int userId;
@Column(name="user_name")
private String userName;
@Column(name="user_pass")
private String userPass;
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getUserPass() {
return userPass;
}
public void setUserPass(String userPass) {
this.userPass = userPass;
}
public User() {
super();
// TODO Auto-generated constructor stub
}
public User(String userName, String userPass) {
super();
this.userName = userName;
this.userPass = userPass;
}
}
然后针对实体的一个简单的dao 和service:
@Repository("userDao")
public class UserDao {
private HibernateTemplate hibernateTemplate;
public HibernateTemplate getHibernateTemplate() {
return hibernateTemplate;
}
@Resource(name="hibernateTemplate")
public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
this.hibernateTemplate = hibernateTemplate;
}
public void addUser(User u){
hibernateTemplate.save(u);
}
}
userService:
@Repository("userService")
public class UserService {
private UserDao userDao;
public UserDao getUserDao() {
return userDao;
}
@Resource(name="userDao")
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
public void assUser(User u){
userDao.addUser(u);;
}
}
最后就是写我们的Controller:
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import edu.hue.jk.bean.User;
import edu.hue.jk.service.UserService;
@Controller
@RequestMapping("/login.do") //指定当用户请求login.do时 UserController会处理用户的请求
public class UserController {
private UserService userService;
public UserService getUserService() {
return userService;
}
@Resource(name="userService")
public void setUserService(UserService userService) {
this.userService = userService;
}
@RequestMapping(params="method=method1") //当使用method1 来请求时 会使用当前方法相应请求
public String registerUser(String userName,String userPass,HttpServletRequest request){ //使用参数得到request
User u=new User(userName,userPass);
request.setAttribute("user", u); // 将用户的信息放到request中
userService.assUser(u);
return "home"; //返回home.jsp页面
}
}
然后我们在index.jsp中写一个注册的form表单:
<%@ 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>
<form action="login.do" method="post">
<table>
<tr>
<td>userName:</td>
<td><input type="text" name="userName"></td>
</tr>
<tr>
<td>userPass:</td>
<td><input type="text" name="userPass"></td>
</tr>
<tr>
<td><input type="submit" name="submit" value="提交"></td>
<td><input type="hidden" name="method" value="method1"></td>
</tr>
</table>
</form>
</body>
</html>
在home.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><!-- 当跳转到home.jsp 时,取出用户注册的信息 -->
userName: ${user.userName}<br>
passWord: ${user.userPass} <br> 注册成功
</body>
</html>
最后运行程序:先输入注册信息
home.jsp 中得到的结果: