Spring学习进阶(一)初识Spring
1 <?xml version="1.0" encoding="UTF-8"?> 2 <project xmlns="http://maven.apache.org/POM/4.0.0" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 5 <modelVersion>4.0.0</modelVersion> 6 <groupId>com.smart</groupId> 7 <artifactId>chapter</artifactId> 8 <packaging>pom</packaging> 9 <version>3.1-SNAPSHOT</version> 10 <name>Spring3.1 </name> 11 <description>Spring3.1</description> 12 <properties> 13 <file.encoding>UTF-8</file.encoding> 14 <java.version>1.6</java.version> 15 <spring.action.version>3.1-SNAPSHOT</spring.action.version> 16 <org.springframework.version>3.1.1.RELEASE</org.springframework.version> 17 <mysql.version>5.1.6</mysql.version> 18 <commons-dbcp.version>1.2.2</commons-dbcp.version> 19 <aspectjweaver.version>1.6.9</aspectjweaver.version> 20 <apache.commons.version>1.1.1</apache.commons.version> 21 <commons-collections.version>3.2.1</commons-collections.version> 22 <javassist.version>3.9.0.GA</javassist.version> 23 <commons-beanutils.version>1.8.3</commons-beanutils.version> 24 <ehcache.version>1.6.2</ehcache.version> 25 <hibernate.version>3.6.10.Final</hibernate.version> 26 <hibernate-validator.version>4.0.2.GA</hibernate-validator.version> 27 <slf4j-jdk14.version>1.6.1</slf4j-jdk14.version> 28 29 <commons-fileupload.version>1.2.1</commons-fileupload.version> 30 <jsp-api.version>2.0</jsp-api.version> 31 <servlet-api.version>2.5</servlet-api.version> 32 <jstl.version>1.2</jstl.version> 33 <standard.version>1.1.2</standard.version> 34 <freemarker.version>2.3.8</freemarker.version> 35 <jetty.version>6.1.5</jetty.version> 36 37 <mockito-all.version>1.8.5</mockito-all.version> 38 <junit.version>4.9.0</junit.version> 39 <testng.version>6.3.1</testng.version> 40 <unitils.version>3.1</unitils.version> 41 <dbunit.version>2.4.8</dbunit.version> 42 </properties> 43 <modules> 44 <module>chapter1</module> 45 <!--<module>chapter2</module> 46 <module>chapter3</module> 47 <module>chapter4</module> 48 <module>chapter5</module> 49 <module>chapter6</module> 50 <module>chapter7</module> 51 <module>chapter8</module> 52 <module>chapter9</module> 53 <module>chapter11</module>--> 54 </modules> 55 <build> 56 <plugins> 57 <plugin> 58 <artifactId>maven-surefire-plugin</artifactId> 59 <configuration> 60 <skip>true</skip> 61 </configuration> 62 </plugin> 63 </plugins> 64 </build> 65 </project>
chapter:pom.xml
1 <?xml version="1.0" encoding="UTF-8"?> 2 <project xmlns="http://maven.apache.org/POM/4.0.0" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 5 <parent> 6 <groupId>com.smart</groupId> 7 <artifactId>chapter</artifactId> 8 <version>3.1-SNAPSHOT</version> 9 </parent> 10 <modelVersion>4.0.0</modelVersion> 11 <artifactId>chapter1</artifactId> 12 <version>3.1-SNAPSHOT</version> 13 <name>第一章示例</name> 14 <description>Spring 快速入门</description> 15 <packaging>war</packaging> 16 <dependencies> 17 <!--① 依赖的Spring模块类库 --> 18 <dependency> 19 <groupId>org.springframework</groupId> 20 <artifactId>spring-beans</artifactId> 21 <version>${org.springframework.version}</version> 22 </dependency> 23 <dependency> 24 <groupId>org.springframework</groupId> 25 <artifactId>spring-jdbc</artifactId> 26 <version>${org.springframework.version}</version> 27 </dependency> 28 <dependency> 29 <groupId>org.springframework</groupId> 30 <artifactId>spring-web</artifactId> 31 <version>${org.springframework.version}</version> 32 </dependency> 33 <dependency> 34 <groupId>org.springframework</groupId> 35 <artifactId>spring-webmvc</artifactId> 36 <version>${org.springframework.version}</version> 37 </dependency> 38 <!--② 依赖的持久化类库--> 39 <dependency> 40 <groupId>mysql</groupId> 41 <artifactId>mysql-connector-java</artifactId> 42 <version>${mysql.version}</version> 43 </dependency> 44 <!--③ 依赖的公共类库--> 45 <dependency> 46 <groupId>commons-dbcp</groupId> 47 <artifactId>commons-dbcp</artifactId> 48 <version>${commons-dbcp.version}</version> 49 </dependency> 50 <dependency> 51 <groupId>org.aspectj</groupId> 52 <artifactId>aspectjweaver</artifactId> 53 <version>${aspectjweaver.version}</version> 54 </dependency> 55 <!--④ 依赖的WEB类库--> 56 <dependency> 57 <groupId>javax.servlet.jsp</groupId> 58 <artifactId>jsp-api</artifactId> 59 <version>${jsp-api.version}</version> 60 <scope>provided</scope> 61 </dependency> 62 <dependency> 63 <groupId>taglibs</groupId> 64 <artifactId>standard</artifactId> 65 <version>${standard.version}</version> 66 <scope>runtime</scope> 67 </dependency> 68 <dependency> 69 <groupId>javax.servlet</groupId> 70 <artifactId>servlet-api</artifactId> 71 <version>${servlet-api.version}</version> 72 </dependency> 73 <dependency> 74 <groupId>javax.servlet</groupId> 75 <artifactId>jstl</artifactId> 76 <version>${jstl.version}</version> 77 </dependency> 78 <!--⑤ 依赖的测试类库--> 79 <dependency> 80 <groupId>org.springframework</groupId> 81 <artifactId>spring-test</artifactId> 82 <version>${org.springframework.version}</version> 83 </dependency> 84 <dependency> 85 <groupId>org.testng</groupId> 86 <artifactId>testng</artifactId> 87 <version>${testng.version}</version> 88 </dependency> 89 <dependency> 90 <groupId>cglib</groupId> 91 <artifactId>cglib</artifactId> 92 <version>1.0</version> 93 </dependency> 94 <dependency> 95 <groupId>commons-logging</groupId> 96 <artifactId>commons-logging</artifactId> 97 <version>1.1</version> 98 </dependency> 99 </dependencies> 100 <build> 101 <finalName>chapter1</finalName> 102 <plugins> 103 <plugin> 104 <artifactId>maven-surefire-plugin</artifactId> 105 <configuration> 106 <skip>true</skip> 107 </configuration> 108 </plugin> 109 <!-- jetty插件 --> 110 <plugin> 111 <groupId>org.mortbay.jetty</groupId> 112 <artifactId>maven-jetty-plugin</artifactId> 113 <version>6.1.5</version> 114 <configuration> 115 <webAppSourceDirectory>src/main/webapp</webAppSourceDirectory> 116 <scanIntervalSeconds>3</scanIntervalSeconds> 117 <contextPath>/chapter1</contextPath> 118 <connectors> 119 <connector implementation="org.mortbay.jetty.nio.SelectChannelConnector"> 120 <port>8088</port> 121 </connector> 122 </connectors> 123 </configuration> 124 </plugin> 125 </plugins> 126 </build> 127 </project>
chapter1 pom.xml
1 package com.smart.domain; 2 3 import java.io.Serializable; 4 import java.util.*; 5 /** 6 * Created by sanglp on 2016/6/29. 7 */ 8 9 /** 10 * domain对象一般要实现Serializable接口,以便进行序列化 11 */ 12 public class User implements Serializable { 13 private int userId; 14 private String userName; 15 private String password; 16 private String lastIp; 17 private Date lastVisit; 18 19 public int getUserId() { 20 return userId; 21 } 22 23 public String getUserName() { 24 return userName; 25 } 26 27 public String getPassword() { 28 return password; 29 } 30 31 public String getLastIp() { 32 return lastIp; 33 } 34 35 public Date getLastVisit() { 36 return lastVisit; 37 } 38 39 public void setUserId(int userId) { 40 this.userId = userId; 41 } 42 43 public void setUserName(String userName) { 44 this.userName = userName; 45 } 46 47 public void setPassword(String password) { 48 this.password = password; 49 } 50 51 public void setLastIp(String lastIp) { 52 this.lastIp = lastIp; 53 } 54 55 public void setLastVisit(Date lastVisit) { 56 this.lastVisit = lastVisit; 57 } 58 }
User.java
1 package com.smart.domain; 2 3 /** 4 * Created by sanglp on 2016/6/29. 5 */ 6 import java.util.*; 7 public class LoginLog { 8 private int loginLogId; 9 private int userId; 10 private String ip; 11 private Date loginDate; 12 13 public int getLoginLogId() { 14 return loginLogId; 15 } 16 17 public int getUserId() { 18 return userId; 19 } 20 21 public String getIp() { 22 return ip; 23 } 24 25 public Date getLoginDate() { 26 return loginDate; 27 } 28 29 public void setLoginLogId(int loginLogId) { 30 this.loginLogId = loginLogId; 31 } 32 33 public void setUserId(int userId) { 34 this.userId = userId; 35 } 36 37 public void setIp(String ip) { 38 this.ip = ip; 39 } 40 41 public void setLoginDate(Date loginDate) { 42 this.loginDate = loginDate; 43 } 44 }
LoginLog.java
1 package com.smart.dao; 2 3 import com.smart.domain.User; 4 import org.springframework.beans.factory.annotation.Autowired; 5 import org.springframework.jdbc.core.JdbcTemplate; 6 import org.springframework.jdbc.core.RowCallbackHandler; 7 import org.springframework.stereotype.Repository; 8 9 import java.sql.ResultSet; 10 import java.sql.SQLException; 11 12 /** 13 * Created by sanglp on 2016/6/29. 14 */ 15 //通过Spring注解定义一个DAO 16 @Repository 17 public class UserDao { 18 //自动注入JdbcTemplate的Bean 19 @Autowired 20 private JdbcTemplate jdbcTemplate; 21 //根据用户名和密码获取匹配的用户数。等于1表示用户名/密码正确,等于0表示用户名或密码错误 22 public int getMatchCount(String userName ,String password){ 23 String sqlStr="select count(*) FROM t_user where user_name=? and password=?"; 24 return jdbcTemplate.queryForInt(sqlStr,new Object[]{userName,password}); 25 } 26 27 /** 28 * 通过调用RowCallbackHandler回调接口实例,将ResultSet转换为User对象 29 * @param userName 30 * @return 31 */ 32 public User findUserByUserName(final String userName){ 33 String sqlStr="SELECT user_id,user_name FROM t_user WHERE user_name=?"; 34 final User user=new User(); 35 jdbcTemplate.query(sqlStr, new Object[]{userName}, 36 new RowCallbackHandler() { //匿名类方式实现的回调函数 37 //processRow负责将查询的结果congenialResultSet装载到类似于领域对象的对象示例中 38 public void processRow(ResultSet resultSet) throws SQLException { 39 user.setUserId(resultSet.getInt("user_id")); 40 user.setUserName(userName); 41 } 42 }); 43 return user; 44 } 45 46 public void updateLoginInfo (User user){ 47 String sqlStr="UPDATE t_user SET last_visit=?,last_ip=? WHERE user_id=?"; 48 jdbcTemplate.update(sqlStr,new Object[]{user.getLastVisit(),user.getLastIp(),user.getUserId()}); 49 } 50 51 }
UserDao.java
1 package com.smart.dao; 2 3 import com.smart.domain.LoginLog; 4 import org.springframework.beans.factory.annotation.Autowired; 5 import org.springframework.jdbc.core.JdbcTemplate; 6 import org.springframework.stereotype.Repository; 7 8 import java.io.Serializable; 9 10 /** 11 * Created by sanglp on 2016/6/29. 12 */ 13 @Repository 14 public class LoginLogDao implements Serializable{ 15 @Autowired 16 private JdbcTemplate jdbcTemplate; 17 18 public void insertLoginLog(LoginLog loginLog){ 19 String sqlStr="INSERT INTO t_login_log(user_id,ip,login_datetime) VALUES(?,?,?)"; 20 jdbcTemplate.update(sqlStr,new Object[]{loginLog.getUserId(),loginLog.getIp(),loginLog.getLoginDate()}); 21 } 22 }
LoginLogDao.java
1 在UserDao和LoginLogDao实现类中都没有打开/释放Connection的代码,那么DAO如何访问数据库? 2 答:样板式的操作都被JdbcTemplate给封装起来了,JdbcTemplate本身需要一个DateSource,这样他就可以根据需要congenialDataSource中获取或返回连接。 3 UserDao和LoginLogDao都提供了一个带@Autowried注解的JdbcTemplate变量。所以必须事先声明一个数据源,然后定义一个JdbcTemplate Bean,通过Spring的 4 容器上下文自动绑定机制进行Bean的注入。
在Spring中装载DAO
1 <?xml version="1.0" encoding="utf-8" ?> 2 <!--引用Spring的多个Schema空间格式定义文件--> 3 <beans xmlns="http://www.springframework.org/schema/beans" 4 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 5 xmlns:p="http://www.springframework.org/schema/p" 6 xmlns:context="http://www.springframework.org/schema/context" 7 xmlns:aop="http://www.springframework.org/schema/aop" 8 xmlns:tx="http://www.springframework.org/schema/tx" 9 xsi:schemaLocation="http://www.springframework.org/schema/beans 10 http://www.springframework.org/schema/beans/spring-beans-3.1.xsd 11 http://www.springframework.org/schema/context 12 http://www.springframework.org/schema/context/spring-context-3.1.xsd 13 http://www.springframework.org/schema/tx 14 http://www.springframework.org/schema/tx/spring-tx-3.1.xsd 15 http://www.springframework.org/schema/aop 16 http://www.springframework.org/schema/aop/spring-aop-3.1.xsd"> 17 18 <!--扫描包类,将标注Spring注解的类自动转化Bean,同时完成Bean的注入--> 19 <!--使用Spring的context:component-scan扫描指定类包下的所有类,这样在类中定义的Spring注解(@Repository和@Autowired等才能产生作用)--> 20 <context:component-scan base-package="com.smart.dao"/> 21 <!--扫描service类包,应用Spring的注解配置--> 22 <context:component-scan base-package="com.smart.service"/> 23 <!--定义一个使用DBCP实现的数据源--> 24 <!--使用Jakarta的DBCP开源数据源实现方案定义个一个数据源并设置驱动,端口用户名密码--> 25 <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" 26 destroy-method="close" 27 p:driverClassName="com.mysql.jdbc.Driver" 28 p:url="jdbc:mysql://localhost:3306/sampledb" 29 p:username="root" 30 p:password="123456"/> 31 32 <!--定义JDBC模板Bean--> 33 <!--配置JdbcTemplate将上面声明的dataSource注入JdbcTemplate中,而这个JdbcTemplate将通过@Autowired自动注入LoginLogDao和UserDao的Bean中--> 34 <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate" 35 p:dataSource-ref="dataSource"/> 36 <!--配置事务管理器 定义了基于数据源的DataSourceTransactionManager事务管理器,该事务管理器负责声明式事务的管理,该管理器需要引用dataSource Bean--> 37 <bean id="transactionManager" 38 class="org.springframework.jdbc.datasource.DataSourceTransactionManager" p:dataSource-ref="dataSource"/> 39 40 <!--通过AOP配置提供事务增强,让service包下所有Bean的所有方法拥有事务--> 41 <aop:config proxy-target-class="true"> 42 <aop:pointcut id="serviceMethod" expression=" execution(* com.smart.service..*(..))"/> 43 <aop:advisor pointcut-ref="serviceMethod" advice-ref="txAdvice"/> 44 </aop:config> 45 <tx:advice id="txAdvice" transaction-manager="transactionManager"> 46 <tx:attributes> 47 <tx:method name="*"/> 48 </tx:attributes> 49 </tx:advice> 50 </beans>
ApplicationContext.xml
1 package com.smart.service; 2 3 import com.smart.dao.LoginLogDao; 4 import com.smart.dao.UserDao; 5 import com.smart.domain.LoginLog; 6 import com.smart.domain.User; 7 import org.springframework.beans.factory.annotation.Autowired; 8 import org.springframework.stereotype.Service; 9 10 /** 11 * Created by sanglp on 2016/6/30. 12 */ 13 14 15 //通过@Service注解将UserService标注为一个服务层的Bean, 16 @Service 17 public class UserService { 18 @Autowired 19 private UserDao userDao; 20 @Autowired 21 private LoginLogDao loginLogDao; 22 23 public boolean hasMatchUser(String userName,String password){ 24 int matchCount=userDao.getMatchCount(userName,password); 25 return matchCount > 0; 26 } 27 28 public User findUserByUserName(String userName){ 29 return userDao.findUserByUserName(userName); 30 } 31 32 public void loginSuccess(User user){ 33 LoginLog loginLog=new LoginLog(); 34 loginLog.setUserId(user.getUserId()); 35 loginLog.setIp(user.getLastIp()); 36 loginLog.setLoginDate(user.getLastVisit()); 37 loginLogDao.insertLoginLog(loginLog); 38 39 } 40 }
UserService.java
1 package com.smart.service; 2 3 import com.smart.domain.User; 4 import org.springframework.beans.factory.annotation.Autowired; 5 import org.springframework.test.context.ContextConfiguration; 6 import org.springframework.test.context.testng.AbstractTestNGSpringContextTests; 7 import org.testng.annotations.Test; 8 9 import javax.jws.soap.SOAPBinding; 10 11 import java.util.Date; 12 13 import static org.testng.Assert.*; 14 /** 15 * Created by sanglp on 2016/6/30. 16 * Spring3.1的测试框架可以和TestNG整合,通过Spring提供的测试基类AbatractTestNGSpringContextTests,可以将Spring 17 * 容器和TestNG测试框架整合。@ContextConfiguration也是Spring提供的注解,它用于指定Spring的配置文件。 18 * 在测试类中可以使用Spring的@Autowired将Spring容器中的Bean注入测试类中。在测试方法前通过TestNG的@Test注解即可将方法标注为测试方法。 19 */ 20 //启动Spring容器 21 @ContextConfiguration(locations ={"/applicationContext.xml"}) 22 //基于TestNG的Spring测试框架 23 public class UserServiceTest extends AbstractTestNGSpringContextTests { 24 @Autowired 25 private UserService userService; 26 27 //标注测试方法 28 @Test 29 public void hasMatchUser(){ 30 boolean b1=userService.hasMatchUser("admin","123456"); 31 boolean b2=userService.hasMatchUser("admin","1111"); 32 assertTrue(b1); 33 34 } 35 36 @Test 37 public void findUserByUserName(){ 38 User user =userService.findUserByUserName("admin"); 39 assertEquals(user.getUserName(),"admin"); 40 } 41 42 @Test 43 public void loginSuccess(){ 44 User user=userService.findUserByUserName("admin"); 45 user.setUserId(1); 46 user.setUserName("admin"); 47 user.setLastIp("192.168.12.7"); 48 user.setLastVisit(new Date()); 49 userService.loginSuccess(user); 50 } 51 }
UserServiceTest.java
1 <?xml version="1.0" encoding="utf-8" ?> 2 <web-app version="2.5" 3 xmlns="http://java.sun.com/xml/ns/javaee" 4 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 5 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> 6 <context-param> 7 <!--从类路径下加载spring配置文件,classpath关键字特指在类路径下加载--> 8 <param-name>contextConfigLocation</param-name> 9 <param-value>classpath:applicationContext.xml</param-value> 10 </context-param> 11 <listener> 12 <!--负责启动spring的容器的监听器,他将引用处的上下文参数获得spring配置文件地址--> 13 <listener-class> 14 org.springframework.web.context.ContextLoaderListener 15 </listener-class> 16 </listener> 17 <!--spring mvc的主控Servlet--> 18 <servlet> 19 <!--Spring mvc也拥有一个spring配置文件,配置文件的文件名和此处定义的servlet名有一个契约,即采用<servlet名>-servlet.xml 因为这里为viewspace所以/WEB-INF目录下必须有一个VIEWSPACE-SERVLET.XMLL--> 20 <servlet-name>viewspace</servlet-name> 21 <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> 22 <load-on-startup>3</load-on-startup> 23 </servlet> 24 <!--spring mvc处理的URL--> 25 <servlet-mapping> 26 <servlet-name>viewspace</servlet-name> 27 <url-pattern>*.html</url-pattern> 28 </servlet-mapping> 29 </web-app>
web.xml配置Spring MVC
1 package com.smart.web; 2 3 import com.smart.domain.User; 4 import com.smart.service.UserService; 5 import org.springframework.beans.factory.annotation.Autowired; 6 import org.springframework.stereotype.Controller; 7 import org.springframework.web.bind.annotation.RequestMapping; 8 import org.springframework.web.servlet.ModelAndView; 9 10 import javax.servlet.http.HttpServletRequest; 11 import javax.servlet.http.HttpServletResponse; 12 import java.util.Date; 13 14 /** 15 * Created by sanglp on 2016/7/5. 16 */ 17 /** 18 * Spring mvc的@Controller注解可以将任何一个POJO的类标注为Spring MVC的控制器,处理HTTP请求,当然标注 了@Controller的类首先会是一个Bean,所以可以使用@Autowired进行Bean的注入 19 * 一个控制器可以拥有多个对应不同HTTP请求路径的处理方法,通过@RequestMapping指定方法如何映射请求路径 20 * 请求的参数会根据参数默认契约自动绑定到响应方法的入参中,在loginCheck方法中请求参数会按名称匹配绑定到loginCommand的入参中。 21 * 请求响应犯法会返回一个ModelAndView或直接返回一个字符串,Spring MVC会解析之并转向目标响应页面。 22 * ModelAndView对象既包括了视图信息又包括偶了视图渲染所需要的模型数据信息。 23 */ 24 //标注为一个controller 25 @Controller 26 @RequestMapping(value="/admin") 27 public class LoginController { 28 29 @Autowired 30 public UserService userService; 31 @RequestMapping(value = "/login.html") //负责处理login.html的请求 32 public String loginPage(){ 33 return "login"; 34 } 35 36 /** 37 * 控制器根据登录处理结果分别返回ModelAndView("login","error","用户名或密码错误")和ModelAndView("main")ModelAndView的第一个参数带包视图的逻辑名 38 * 第二个和第三个参数分别为数据模型名称和数据模型对象,数据模型对象将以数据模型名称为参数名放置到request的属性中 39 * @param request 40 * @param loginCommand 41 * @return 42 */ 43 @RequestMapping(value = "/loginCheck.html") 44 public ModelAndView loginCheck(HttpServletRequest request,LoginCommand loginCommand){ 45 boolean isValidUser = userService.hasMatchUser(loginCommand.getUserName(),loginCommand.getPassword()); 46 47 if(!isValidUser){ 48 return new ModelAndView("login","error","用户名或密码错误"); 49 }else{ 50 User user=userService.findUserByUserName(loginCommand.getUserName()); 51 user.setLastIp(request.getRemoteAddr()); 52 user.setLastVisit(new Date()); 53 userService.loginSuccess(user); 54 request.getSession().setAttribute("user",user); 55 return new ModelAndView("main"); 56 } 57 } 58 }
LoginController.java
1 package com.smart.web; 2 3 /** 4 * Created by sanglp on 2016/7/5. 5 */ 6 public class LoginCommand { 7 private String userName; 8 private String password; 9 10 public String getUserName() { 11 return userName; 12 } 13 14 public String getPassword() { 15 return password; 16 } 17 18 public void setUserName(String userName) { 19 this.userName = userName; 20 } 21 22 public void setPassword(String password) { 23 this.password = password; 24 } 25 }
LoginCommand.java
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:context="http://www.springframework.org/schema/context" 5 xsi:schemaLocation="http://www.springframework.org/schema/beans 6 http://www.springframework.org/schema/beans/spring-beans-3.1.xsd 7 http://www.springframework.org/schema/context 8 http://www.springframework.org/schema/context/spring-context-3.1.xsd"> 9 <!--扫描相应的包,应用spring注解--> 10 <context:component-scan base-package="com.smart.web"/> 11 <bean id="defaultAnnotationHandlerMapping" class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping"/> 12 <bean id="annotationMethodHandlerAdapter" class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"/> 13 14 <!--配置视图解析器,将ModelAndView及字符串解析为具体的页眉 在这里我们使用了InternalResourceViewResolver的视图映射方式,他通过添加前后缀来进行解析--> 15 <!--Springmvc如何将视图逻辑名解析为具体的视图页眉呢? 通过prefix指定在视图名前所添加的前缀,通过suffix指定在视图名后添加的后缀--> 16 <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" 17 p:viewClass="org.springframework.web.servlet.view.JstlView" 18 p:prefix="/WEB-INF/jsp/" 19 p:suffix=".jsp"/> 20 </beans>
viewspace-servlet.xml
1 <%@ page language="java" contentType="text/html" charset="UTF-8" pageEncoding="UTF-8"%> 2 <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> 3 <html> 4 <head> 5 <title>景区网站登录</title> 6 </head> 7 <body> 8 <c:if test="${!empty error}"> 9 <!--使用JSTL标签对登录返回的信息进行错误处理,JSTL标签中引用了error变量,这个变量正是LoginController中返回的ModelAndView("login","error","用户名或密码错误")对象所声明的error参数--> 10 <font color="red"><c:out value="${error}"/></font> 11 </c:if> 12 <!--login.jsp登录表单提交到loginController.html JSTL标签会在URL前自动加上应用程序部署根目录,假设应用部署在网站的viewspace目录下,标签将输出/viewspace/loginController.html 13 由于login.jsp放在WEB-INF/jsp目录下,无法直接通过URL进行调用,他由LoginController控制类中标注了@RequestMapping(value="/login.html")的loginPage()进行转发--> 14 <form action="<c:url value="/loginCheck.html"/>" method="post"> 15 用户名: 16 <input type="text" name="userName"> 17 <br/> 18 密码: 19 <input type="password" name="password"> 20 <br/> 21 <input type="submit" value="登录"/> 22 <input type="reset" value="重置"/> 23 </form> 24 </body> 25 </html>
login.jsp
1 <%@ page language="java" contentType="text/html" charset="UTF-8" pageEncoding="UTF-8"%> 2 <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> 3 <html> 4 <head> 5 <title>景区后台管理主页面</title> 6 </head> 7 <body> 8 <!--访问Session域中的user对象,显示用户名和积分信息--> 9 ${user.userName},欢迎您进入景区管理后台! 10 </body> 11 </html>
main.jsp
jetty无法启动使用:mvn org.mertbay.jetty:maven-jetty-plugin:run