1.web.xml配置
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:**/application-context*.xml</param-value>
</context-param>
<listener>
<listener-class> org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
2.application-context.xml配置
<?xml version="1.0" encoding="utf-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd">
<context:annotation-config/>
<context:component-scan base-package="com.anonymity.mobile.blog.*"/>
</beans>
3.Service类
package com.anonymity.mobile.blog.service;
import java.util.List;
import com.anonymity.mobile.blog.entity.Users;
public interface UserService {
/**
* 用户列表
* @return
*/
public List<Users> userList();
}
4.ServiceImpl类
package com.anonymity.mobile.blog.serviceimpl;
import java.util.ArrayList;
import java.util.List;
import org.springframework.stereotype.Component;
import com.anonymity.mobile.blog.entity.Users;
import com.anonymity.mobile.blog.service.UserService;
@Component("userServcie")
public class UserServiceImpl implements UserService {
/**
* 用户列表
* @return
* @see com.anonymity.mobile.blog.service.UserService#userList()
*/
@Override
public List<Users> userList() {
List<Users> list = new ArrayList<Users>();
Users u1 = new Users();
u1.setUserName("admin");
u1.setPwd("000000");
Users u2 = new Users();
u2.setUserName("guest");
u2.setPwd("000000");
list.add(u1);
list.add(u2);
return list;
}
}
5.JSP页面
<%@page import="java.util.*"%>
<%@page import="com.anonymity.mobile.blog.entity.*"%>
<html>
<body>
<%
List<Users> userList = (List<Users>)request.getAttribute("userList");
for(Users user:userList){
out.println("<h1>"+user.getUserName()+"</h1>");
}
%>
</body>
</html>
6.备注
6.1调整web.xml配置
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>*.json</url-pattern>
</servlet-mapping>
6.2调整dispatch-servlet.xml配置
InternalResourceViewResolver将视图名解析为一个url,可以理解为转发获取jsp页面。如果使用/*拦截,则需要配置
<mvc:resources mapping="/WEB-INF/jsp/demo/**" location="/WEB-INF/jsp/demo/" cache-period="31556926"/>标签或者 <mvc:default-servlet-handler/>,就可以访问静态资源了。但是这样的话就显示jsp源码了,并没有解析为servlet。所以使用*.html拦截。