<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<display-name>LabWebServletJdbc</display-name>
<filter>
<filter-name>OpenSessionInViewFilter</filter-name>
<filter-class>misc.OpenSessionInViewFilter</filter-class>
<init-param>
<param-name>sessionFactoryBeanName</param-name>
<param-value>sessionFactory</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>OpenSessionInViewFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
用filter來設定OpenSessionInViewFilter,用以在網站開啟時實行init方法,取得sessionFactory
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
因為直接把Spring的設定檔beans.xml取名叫applicationContext並放對位置,所以不用再特別在web.xml中進行設定
<resource-ref>
<res-ref-name>jdbc/xxx</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
<res-sharing-scope>Shareable</res-sharing-scope>
</resource-ref>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
</web-app>
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
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.xsd">
<!-- 被jndi取代了 -->
<!-- <bean id="dataSource" -->
<!-- class="org.springframework.jdbc.datasource.DriverManagerDataSource"> -->
<!-- <property name="driverClassName" value="com.microsoft.sqlserver.jdbc.SQLServerDriver"
/> -->
<!-- <property name="url" -->
<!-- value="jdbc:sqlserver://localhost:1433;database=java"></property> -->
<!-- <property name="username" value="sa"></property> -->
<!-- <property name="password" value="passw0rd"></property> -->
<!-- </bean> -->
<bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName" value="java:comp/env/jdbc/xxx"></property>
</bean>
<!-- ↓取代了SessionFactoryListener.class的工作 -->
<bean id="sessionFactory" destroy-method="destroy"
class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="configLocation">
<value>classpath:hibernate.cfg.xml</value>
</property>
</bean>
<bean id="CustomerDAOHibernate" class="model.dao.CustomerDAOHibernate">
<constructor-arg ref="sessionFactory"></constructor-arg>
</bean>
<bean id="CustomerService" class="model.CustomerService">
<constructor-arg ref="CustomerDAOHibernate"></constructor-arg>
</bean>
<bean id="ProductDAOHibernate" class="model.dao.ProductDAOHibernate">
<constructor-arg ref="sessionFactory"></constructor-arg>
</bean>
<bean id="ProductService" class="model.ProductService">
<constructor-arg ref="ProductDAOHibernate"></constructor-arg>
</bean>
</beans>
package controller;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import model.CustomerBean;
import model.CustomerService;
import model.dao.CustomerDAOHibernate;
//import model.misc.HibernateUtil;
@WebServlet(
urlPatterns={"/secure/login.controller"}
)
public class LoginServlet extends HttpServlet {
private CustomerService customerService;
@Override
public void init() throws ServletException {
// customerService = new CustomerService(
// new CustomerDAOHibernate(HibernateUtil.getSessionFactory()));
ApplicationContext context = WebApplicationContextUtils
.getWebApplicationContext(this.getServletContext());
this.customerService = (CustomerService) context.getBean("CustomerService");
}
@Override
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
//接收資料
String username = request.getParameter("username");
String password = request.getParameter("password");
//驗證資料
Map<String, String> errors = new HashMap<String, String>();
request.setAttribute("error", errors);
if(username==null || username.length()==0) {
errors.put("username", "Please Enter ID");
}
if(password==null || password.length()==0) {
errors.put("password", "Please Enter PWD");
}
if(errors!=null && !errors.isEmpty()) {
request.getRequestDispatcher(
"/secure/login.jsp").forward(request, response);
return ;
}
//呼叫Model
CustomerBean bean = customerService.login(username, password);
//根據Model執行結果顯示View
if(bean==null) {
errors.put("password", "Login failed, please try again.");
request.getRequestDispatcher(
"/secure/login.jsp").forward(request, response);
} else {
HttpSession session = request.getSession();
session.setAttribute("user", bean);
String path = request.getContextPath();
response.sendRedirect(path+"/index.jsp");
}
}
@Override
protected void doPost(HttpServletRequest req,
HttpServletResponse resp) throws ServletException, IOException {
this.doGet(req, resp);
}
}
package misc;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import org.hibernate.SessionFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
public class OpenSessionInViewFilter implements Filter {
@Override
public void destroy() {
}
@Override
public void doFilter(ServletRequest req, ServletResponse resp,
FilterChain chain) throws IOException, ServletException {
// HttpServletRequest request = (HttpServletRequest) req;
// HttpServletResponse response = (HttpServletResponse) resp;
System.out.println("sessionFactory");
try {
// 所有取得SessionFactory()的工作都交給Spring了
// HibernateUtil.getSessionFactory().getCurrentSession().beginTransaction();
sessionFactory.getCurrentSession().beginTransaction();
chain.doFilter(req, resp);
// HibernateUtil.getSessionFactory().getCurrentSession().getTransaction().commit();
sessionFactory.getCurrentSession().getTransaction().commit();
} catch (Exception e) {
// HibernateUtil.getSessionFactory().getCurrentSession().getTransaction().rollback();
sessionFactory.getCurrentSession().getTransaction().rollback();
e.printStackTrace();
chain.doFilter(req, resp);
}
}
private SessionFactory sessionFactory;
private FilterConfig config;
@Override
public void init(FilterConfig config) throws ServletException {
this.config = config;
String sessionFactoryBeanName=config.getInitParameter("sessionFactoryBeanName");
ServletContext application =config.getServletContext();
ApplicationContext context = WebApplicationContextUtils
.getWebApplicationContext(application);
sessionFactory = (SessionFactory) context.getBean(sessionFactoryBeanName);
//LocalSessionFactoryBean實作了FactoryBean
//FactoryBean定義實作自己的類別不會回傳自己,大致的意思就是說實現了此接口的類並不會返回他自己的實例,而是另外一個通過getObject 方法返回的實例。
}
}
留言列表