标签:
刚学习springmvc不久,各种配置我怕记不住,就写个随笔记录一下。
我的项目是springmvc+hibernate。环境是windows+myeclipse(或eclipse)+jdk7+tomcat7+mysql
第一步:引入jar包。第一次为了方便,我将很多jar包和依赖包全部直接拷进去了,实际上只需要一部分。具体需要什么,就加什么,可以在网上查到。
第二步:配置数据源,注解扫描包。
1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" 4 xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" 5 xmlns:tx="http://www.springframework.org/schema/tx" xmlns:mvc="http://www.springframework.org/schema/mvc" 6 xmlns:util="http://www.springframework.org/schema/util" 7 xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.1.xsd 8 http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd 9 http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd 10 http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.1.xsd 11 http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd 12 http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd"> 13 14 <!-- 注解扫描包 --> 15 <context:component-scan base-package="main.java.lms" /> 16 <!-- 开启注解 --> 17 <context:annotation-config /> 18 19 <!--数据源 --> 20 <!-- <bean id="dataSource" 21 class="org.springframework.jdbc.datasource.DriverManagerDataSource"> 22 <property name="driverClassName"> 23 <value>com.mysql.jdbc.Driver</value> 24 </property> 25 <property name="url"> 26 <value>jdbc:mysql://localhost:3306/laboratory</value> 27 </property> 28 <property name="username"> 29 <value>root</value> 30 </property> 31 <property name="password"> 32 <value>root</value> 33 </property> 34 </bean> --> 35 <bean id="dataSource" 36 class="org.springframework.jdbc.datasource.DriverManagerDataSource"> 37 <property name="driverClassName"> 38 <value>com.microsoft.sqlserver.jdbc.SQLServerDriver</value> 39 </property> 40 <property name="url"> 41 <value>jdbc:sqlserver://localhost:1433;databaseName=laboratory</value> 42 </property> 43 <property name="username"> 44 <value>root</value> 45 </property> 46 <property name="password"> 47 <value>root</value> 48 </property> 49 </bean> 50 <!-- <bean id="dataSource" 51 class="org.springframework.jdbc.datasource.DriverManagerDataSource"> 52 <property name="driverClassName"> 53 <value>oracle.jdbc.driver.OracleDriver</value> 54 </property> 55 <property name="url"> 56 <value>jdbc:oracle:thin:@localhost:1521:orcl</value> 57 </property> 58 <property name="username"> 59 <value>root</value> 60 </property> 61 <property name="password"> 62 <value>root</value> 63 </property> 64 </bean> --> 65 66 <!-- Hibernate SessionFactory --> 67 <bean id="sessionFactory" 68 class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"> 69 <property name="dataSource" ref="dataSource" /> 70 <property name="hibernateProperties"> 71 <props> 72 <!-- <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</prop> --> 73 <prop key="hibernate.dialect">org.hibernate.dialect.SQLServerDialect</prop> 74 <!-- <prop key="hibernate.dialect">org.hibernate.dialect.OracleDialect</prop> --> 75 <prop key="hibernate.show_sql">true</prop> 76 <prop key="hibernate.hbm2ddl.auto">update</prop> 77 <prop key="hibernate.format_sql">true</prop> 78 </props> 79 </property> 80 <property name="packagesToScan" value="main.java.lms"></property> 81 </bean> 82 </beans>
第三步:配置试图解析器等
1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" 4 xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" 5 xmlns:tx="http://www.springframework.org/schema/tx" xmlns:mvc="http://www.springframework.org/schema/mvc" 6 xmlns:util="http://www.springframework.org/schema/util" 7 xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.1.xsd 8 http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd 9 http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd 10 http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.1.xsd 11 http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd 12 http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd"> 13 14 <!-- 注解扫描包 --> 15 <context:component-scan base-package="main.java.lms" /> 16 17 <mvc:annotation-driven /> 18 19 <mvc:default-servlet-handler /> 20 21 <!-- spring mvc 视图解析器 --> 22 <bean id="viewResolver" 23 class="org.springframework.web.servlet.view.InternalResourceViewResolver"> 24 <property name="prefix"> 25 <value>/WEB-INF/pages/</value> 26 </property> 27 <property name="suffix"> 28 <value>.jsp</value> 29 </property> 30 31 </bean> 32 33 <bean id="transactionManager" 34 class="org.springframework.orm.hibernate4.HibernateTransactionManager"> 35 <property name="sessionFactory" ref="sessionFactory" /> 36 </bean> 37 38 <!-- <bean id="exceptionResolver" 39 class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver"> 40 <property name="defaultErrorView"> 41 <value>error</value> 42 </property> 43 <property name="exceptionMappings"> 44 <props> 45 <prop key="java.lang.RuntimeException">error</prop> 46 </props> 47 </property> 48 </bean> --> 49 50 <tx:annotation-driven transaction-manager="transactionManager" /> 51 52 <import resource="spring-context.xml" /> 53 </beans>
第四步:配置web.xml
1 <?xml version="1.0" encoding="UTF-8"?> 2 <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_3_0.xsd" id="WebApp_ID" version="3.0"> 3 <display-name>LaboratorySystemSpringmvc</display-name> 4 <welcome-file-list> 5 <welcome-file>index.html</welcome-file> 6 <welcome-file>index.htm</welcome-file> 7 <welcome-file>index.jsp</welcome-file> 8 <welcome-file>default.html</welcome-file> 9 <welcome-file>default.htm</welcome-file> 10 <welcome-file>default.jsp</welcome-file> 11 </welcome-file-list> 12 13 <context-param> 14 <param-name>log4jConfigLocation</param-name> 15 <param-value>/WEB-INF/log4j.properties</param-value> 16 </context-param> 17 <context-param> 18 <param-name>log4jRefreshInterval</param-name> 19 <param-value>3000</param-value> 20 </context-param> 21 <listener> 22 <listener-class> 23 org.springframework.web.util.Log4jConfigListener 24 </listener-class> 25 </listener> 26 27 <context-param> 28 <param-name>contextConfigLocation</param-name> 29 <param-value>/WEB-INF/spring-context.xml</param-value> 30 </context-param> 31 <listener> 32 <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> 33 </listener> 34 <filter> 35 <filter-name>encodingFilter</filter-name> 36 <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> 37 <init-param> 38 <param-name>encoding</param-name> 39 <param-value>UTF-8</param-value> 40 </init-param> 41 </filter> 42 <filter-mapping> 43 <filter-name>encodingFilter</filter-name> 44 <url-pattern>/*</url-pattern> 45 </filter-mapping> 46 <listener> 47 <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class> 48 </listener> 49 <servlet> 50 <servlet-name>Spring MVC Dispatcher Servlet</servlet-name> 51 <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> 52 <init-param> 53 <param-name>contextConfigLocation</param-name> 54 <param-value>/WEB-INF/springmvc-context.xml</param-value> 55 </init-param> 56 <load-on-startup>1</load-on-startup> 57 </servlet> 58 <servlet-mapping> 59 <servlet-name>Spring MVC Dispatcher Servlet</servlet-name> 60 <url-pattern>/</url-pattern> 61 </servlet-mapping> 62 <filter> 63 <filter-name>SpringOpenSessionInViewFilter</filter-name> 64 <filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class> 65 </filter> 66 <filter-mapping> 67 <filter-name>SpringOpenSessionInViewFilter</filter-name> 68 <url-pattern>/*</url-pattern> 69 </filter-mapping> 70 </web-app>
第五步:新建实例
1 package main.java.lms.entities; 2 3 import java.io.Serializable; 4 5 import javax.persistence.CascadeType; 6 import javax.persistence.Column; 7 import javax.persistence.Entity; 8 import javax.persistence.GeneratedValue; 9 import javax.persistence.GenerationType; 10 import javax.persistence.Id; 11 import javax.persistence.JoinColumn; 12 import javax.persistence.ManyToOne; 13 import javax.persistence.OneToOne; 14 import javax.persistence.SequenceGenerator; 15 import javax.persistence.Table; 16 17 import org.hibernate.annotations.GenericGenerator; 18 19 /** 20 * 用户表 21 * 22 */ 23 @Entity 24 @Table(name="lms_user") 25 public class User implements Serializable { 26 /** 27 * 28 */ 29 private static final long serialVersionUID = -1461373625778051299L; 30 private int userId; 31 private String loginNumber;// 登陆名,即学号或工号 32 private String loginPassword; 33 private String userName; 34 private String userIdentity;// 身份:学生,老师管理员:3,2,1 35 36 // 用户扩展表(与用户一对一级联关系) 37 private UserExtends userExtends; 38 39 public User(String loginNumber, String loginPassword) { 40 this.loginNumber = loginNumber; 41 this.loginPassword = loginPassword; 42 } 43 44 public User() { 45 } 46 47 48 @ManyToOne(cascade=CascadeType.ALL) 49 @JoinColumn(name="user_ex_loginName",unique=true,referencedColumnName="user_ex_loginName") 50 public UserExtends getUserExtends() { 51 return userExtends; 52 } 53 54 public void setUserExtends(UserExtends userExtends) { 55 this.userExtends = userExtends; 56 } 57 58 @Id 59 @Column(name = "user_id", unique = true, nullable = false) 60 public int getUserId() { 61 return userId; 62 } 63 64 public void setUserId(int userId) { 65 this.userId = userId; 66 } 67 68 @Column(name = "user_loginName", unique = true, nullable = false) 69 public String getLoginNumber() { 70 return loginNumber; 71 } 72 73 public void setLoginNumber(String loginNumber) { 74 this.loginNumber = loginNumber; 75 } 76 77 @Column(name = "user_loginPassword", nullable = false) 78 public String getLoginPassword() { 79 return loginPassword; 80 } 81 82 public void setLoginPassword(String loginPassword) { 83 this.loginPassword = loginPassword; 84 } 85 86 @Column(name = "user_name", nullable = false) 87 public String getUserName() { 88 return userName; 89 } 90 91 public void setUserName(String userName) { 92 this.userName = userName; 93 } 94 95 @Column(name = "user_identity", nullable = false) 96 public String getUserIdentity() { 97 return userIdentity; 98 } 99 100 public void setUserIdentity(String userIdentity) { 101 this.userIdentity = userIdentity; 102 } 103 104 }
1 package main.java.lms.entities; 2 3 import java.io.Serializable; 4 5 import javax.persistence.CascadeType; 6 import javax.persistence.Column; 7 import javax.persistence.Entity; 8 import javax.persistence.GeneratedValue; 9 import javax.persistence.Id; 10 import javax.persistence.JoinColumn; 11 import javax.persistence.ManyToOne; 12 import javax.persistence.OneToOne; 13 import javax.persistence.Table; 14 15 import org.hibernate.annotations.GenericGenerator; 16 import org.hibernate.annotations.Parameter; 17 18 /** 19 * 用户扩展表 20 * 21 */ 22 @Entity 23 @Table(name = "lms_userextends") 24 public class UserExtends implements Serializable { 25 /** 26 * 27 */ 28 private static final long serialVersionUID = 8046904045928469438L; 29 // 用户(与用户扩展表一对一级联关系) 30 private User user; 31 private String userExLoginNumber; 32 private int sex; 33 private String idCard; 34 private String national;// 民族 35 private String politicalLandscape;// 政治面貌 36 private String placeOfOrigin;// 籍贯 37 38 private String studyType;// 学生类别,本科专科:1本2专 39 private String studentDepartment;// 所在系别 40 private String studentProfessional;// 专业 41 private String studentProfessionalDirection;// 专业方向 42 private int stduentClass;// 班级 43 private int grade;// 年级 44 45 private String workDepartment;// 工作部门单位 46 private String workPosition;// 工作职位 47 private String workTitle;// 职称 48 49 private String phoneNumber; 50 private String email; 51 private String address; 52 private int postalCode; 53 54 @OneToOne(mappedBy="userExtends",cascade=CascadeType.ALL) 55 public User getUser() { 56 return user; 57 } 58 59 public void setUser(User user) { 60 this.user = user; 61 } 62 63 @Id 64 @Column(name = "user_ex_loginName", unique = true, nullable = false) 65 public String getUserExLoginNumber() { 66 return userExLoginNumber; 67 } 68 69 public void setUserExLoginNumber(String userExLoginNumber) { 70 this.userExLoginNumber = userExLoginNumber; 71 } 72 73 @Column(name = "user_sex") 74 public int getSex() { 75 return sex; 76 } 77 78 public void setSex(int sex) { 79 this.sex = sex; 80 } 81 82 @Column(name = "user_idCard") 83 public String getIdCard() { 84 return idCard; 85 } 86 87 public void setIdCard(String idCard) { 88 this.idCard = idCard; 89 } 90 91 @Column(name = "user_national") 92 public String getNational() { 93 return national; 94 } 95 96 public void setNational(String national) { 97 this.national = national; 98 } 99 100 @Column(name = "user_politicalLandscape") 101 public String getPoliticalLandscape() { 102 return politicalLandscape; 103 } 104 105 public void setPoliticalLandscape(String politicalLandscape) { 106 this.politicalLandscape = politicalLandscape; 107 } 108 109 @Column(name = "user_placeOfOrigin") 110 public String getPlaceOfOrigin() { 111 return placeOfOrigin; 112 } 113 114 public void setPlaceOfOrigin(String placeOfOrigin) { 115 this.placeOfOrigin = placeOfOrigin; 116 } 117 118 @Column(name = "user_studyType") 119 public String getStudyType() { 120 return studyType; 121 } 122 123 public void setStudyType(String studyType) { 124 this.studyType = studyType; 125 } 126 127 @Column(name = "user_studentDepartment") 128 public String getStudentDepartment() { 129 return studentDepartment; 130 } 131 132 public void setStudentDepartment(String studentDepartment) { 133 this.studentDepartment = studentDepartment; 134 } 135 136 @Column(name = "user_studentProfessional") 137 public String getStudentProfessional() { 138 return studentProfessional; 139 } 140 141 public void setStudentProfessional(String studentProfessional) { 142 this.studentProfessional = studentProfessional; 143 } 144 145 @Column(name = "user_studentProfessionalDirection") 146 public String getStudentProfessionalDirection() { 147 return studentProfessionalDirection; 148 } 149 150 public void setStudentProfessionalDirection( 151 String studentProfessionalDirection) { 152 this.studentProfessionalDirection = studentProfessionalDirection; 153 } 154 155 @Column(name = "user_studentClass") 156 public int getStduentClass() { 157 return stduentClass; 158 } 159 160 public void setStduentClass(int stduentClass) { 161 this.stduentClass = stduentClass; 162 } 163 164 @Column(name = "user_grade") 165 public int getGrade() { 166 return grade; 167 } 168 169 public void setGrade(int grade) { 170 this.grade = grade; 171 } 172 173 @Column(name = "user_workDepartment") 174 public String getWorkDepartment() { 175 return workDepartment; 176 } 177 178 public void setWorkDepartment(String workDepartment) { 179 this.workDepartment = workDepartment; 180 } 181 182 @Column(name = "user_workPosition") 183 public String getWorkPosition() { 184 return workPosition; 185 } 186 187 public void setWorkPosition(String workPosition) { 188 this.workPosition = workPosition; 189 } 190 191 @Column(name = "user_workTitle") 192 public String getWorkTitle() { 193 return workTitle; 194 } 195 196 public void setWorkTitle(String workTitle) { 197 this.workTitle = workTitle; 198 } 199 200 @Column(name = "user_phoneNumber") 201 public String getPhoneNumber() { 202 return phoneNumber; 203 } 204 205 public void setPhoneNumber(String phoneNumber) { 206 this.phoneNumber = phoneNumber; 207 } 208 209 @Column(name = "user_email") 210 public String getEmail() { 211 return email; 212 } 213 214 public void setEmail(String email) { 215 this.email = email; 216 } 217 218 @Column(name = "user_address") 219 public String getAddress() { 220 return address; 221 } 222 223 public void setAddress(String address) { 224 this.address = address; 225 } 226 227 @Column(name = "user_postalCode") 228 public int getPostalCode() { 229 return postalCode; 230 } 231 232 public void setPostalCode(int postalCode) { 233 this.postalCode = postalCode; 234 } 235 236 }
第六步:controller层
1 @Controller 2 public class UserController { 3 4 @Autowired 5 private UserServices userServices; 6 7 private InitPageGroup initPageGroup= new InitPageGroup(); 8 9 private final int defaultPageSize=10; 10 11 /** 12 * 映射首页的地址,如果已登录跳转到首页,未登录跳转到登录界面 13 * @param request 14 * @param response 15 * @return 16 */ 17 @RequestMapping(value="/index.html",method=RequestMethod.GET) 18 public String toIndex(HttpServletRequest request,HttpServletResponse response){ 19 HttpSession session=request.getSession(); 20 if(session.getAttribute("user")!=null){ 21 return "user/index"; 22 }else { 23 try { 24 response.sendRedirect(request.getContextPath()+"/login.html"); 25 } catch (IOException e) { 26 e.printStackTrace(); 27 } 28 return "user/login"; 29 } 30 } 31 }
第七步:service层
1 @Transactional 2 @Service("userService") 3 public class UserServicesImpl implements UserServices{ 4 5 @Autowired 6 private UserDao userDao; 7 8 @Override 9 public User userLogin(User user) { 10 System.out.println("call service"); 11 User user2=this.userDao.userLogin(user); 12 return user2; 13 } 14 }
第八步:dao层
(1)使用hql
1 @Repository("userDao") 2 public class UserDaoImpl implements UserDao { 3 4 @Autowired 5 private SessionFactory sessionFactory; 6 7 8 @Override 9 public User userLogin(User user) { 10 System.out.println("call dao"); 11 User user2 = (User) this.sessionFactory 12 .getCurrentSession() 13 .createQuery( 14 "FROM User u where u.loginNumber=:loginName and u.loginPassword=:password") 15 .setString("loginName", user.getLoginNumber()) 16 .setString("password", user.getLoginPassword()).uniqueResult(); 17 return user2; 18 } 19 }
(2)使用原生sql
1 @Repository("deviceDao") 2 @SuppressWarnings("unchecked") 3 public class DeviceDaoImpl implements DeviceDao { 4 5 @Autowired 6 private SessionFactory sessionFactory; 7 8 @Override 9 public List<Device> getDevice() { 10 String sql = "SELECT id AS deviceId,name,info,avaiNum,damageNum FROM lms_device WHERE isDelete = ‘2199-12-31 23:59:59‘"; 11 SQLQuery query = sessionFactory.getCurrentSession().createSQLQuery(sql); 12 query.addScalar("deviceId", StandardBasicTypes.INTEGER); 13 query.addScalar("name", StandardBasicTypes.STRING); 14 query.addScalar("info", StandardBasicTypes.STRING); 15 query.addScalar("avaiNum", StandardBasicTypes.INTEGER); 16 query.addScalar("damageNum", StandardBasicTypes.INTEGER); 17 query.setResultTransformer(Transformers.aliasToBean(Device.class)); 18 return query.list(); 19 } 20 }
最后补充:为了方便在控制台看见后台操作的结果,能够输出后台执行时的sql语句,再加一个文件log4j.properties
1 ##OFF->FATAL->ERROR->WARN->INFO->DEBUG->ALL 2 ##ERROR->WARN->INFO->DEBUG 3 # define a logger named CONSOLE 4 log4j.rootLogger=INFO, CONSOLE 5 # CONSOLE logger - console 6 log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender 7 # COSOLE Layout 8 log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout 9 # CONSOLE format Layout 10 log4j.appender.CONSOLE.layout.ConversionPattern=%5p %d{yyyy-MM-dd HH:mm:ss,SSS} %c:(%F:%L) - %m%n
所有的配置文件就是下面这几个。
到这里,再写好jsp页面就可以运行一个springmvc的网站了。
第一次写博客,谨记。
标签:
原文地址:http://www.cnblogs.com/liuqinc/p/5764448.html