电子邮件表单状态403不支持Spring Request方法过帐

时间:2018-10-11 19:19:17

标签: java spring email-integration

我正在尝试向我的Spring MVC Web应用程序添加电子邮件支持。我一直在代码极客https://examples.javacodegeeks.com/enterprise-java/spring/mvc/sending-email-spring-mvc-example/

上遵循本指南。

尽管我的文件结构不同,但是这是我得到的错误:1 谁能帮我?这是我一直在使用的相关代码,我很茫然:

Spring Java配置

@Configuration
@EnableWebMvc
@EnableTransactionManagement
@ComponentScan("com.luv2code.springdemo")
@PropertySource({ "classpath:persistence-mysql.properties", "classpath:security-persistence-mysql.properties" })
public class DemoAppConfig implements WebMvcConfigurer {

    @Autowired
    private Environment env;

    private Logger logger = Logger.getLogger(getClass().getName());

    // define a bean for email support 
    /*
     * <bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">

    <property name="host" value="smtp.mail.yahoo.com" />
        <property name="port" value="587" />
        <property name="username" value="<!-- Source Email Address -->" />
        <property name="password" value="<!-- Source Email Password -->" />
        <property name="javaMailProperties">
            <props>
                <prop key="mail.smtp.auth">true</prop>
                <prop key="mail.debug">true</prop>
                <prop key="mail.transport.protocol">smtp</prop>
                <prop key="mail.smtp.socketFactory.class">javax.net.ssl.SSLSocketFactory</prop>
                <prop key="mail.smtp.socketFactory.port">465</prop>
                <prop key="mail.smtp.starttls.enable">true</prop>
            </props>
        </property>
*/

    // define a bean for email support
    @Bean
    public JavaMailSenderImpl mailSender() {
        JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
        mailSender.setHost("smtp.mail.yahoo.com");
        mailSender.setPort(587);
        mailSender.setUsername("---");
        mailSender.setPassword("---");

            Properties mailProperties = new Properties();
            mailProperties.put("mail.smtp.auth", true);
            mailProperties.put("mail.debug", true);
            mailProperties.put("mail.transport.protocol", "smtp");
            mailProperties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");    
            mailProperties.put("mail.smtp.socketFactory.port", 465); 
            mailProperties.put("mail.smtp.starttls.enable",true); 
        mailSender.setJavaMailProperties(mailProperties);

        return mailSender;
    }

    @Bean 
    public CommonsMultipartResolver multiPartResolver() {
        CommonsMultipartResolver resolver = new CommonsMultipartResolver();
            resolver.setMaxUploadSize(20971520);
            resolver.setMaxInMemorySize(1048576);
        return resolver;
    }

    @Bean
    public SimpleMappingExceptionResolver exceptionResolver() {
        SimpleMappingExceptionResolver exception = new SimpleMappingExceptionResolver();

        Properties mappings = new Properties();
        mappings.put("java.lang.Exception", "error");

        exception.setExceptionMappings(mappings);

        return exception;

    }

    // define a bean for ViewResolver
    @Bean
    public ViewResolver viewResolver() {

        InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();

        viewResolver.setPrefix("/WEB-INF/view/");
        viewResolver.setSuffix(".jsp");

        return viewResolver;
    }


    @Bean
    public DataSource myDataSource() {

        // create connection pool
        ComboPooledDataSource myDataSource = new ComboPooledDataSource();

        // set the jdbc driver
        try {
            myDataSource.setDriverClass("com.mysql.jdbc.Driver");       
        }
        catch (PropertyVetoException exc) {
            throw new RuntimeException(exc);
        }

        // for sanity's sake, let's log url and user ... just to make sure we are reading the data
        logger.info("jdbc.url=" + env.getProperty("jdbc.url"));
        logger.info("jdbc.user=" + env.getProperty("jdbc.user"));

        // set database connection props
        myDataSource.setJdbcUrl(env.getProperty("jdbc.url"));
        myDataSource.setUser(env.getProperty("jdbc.user"));
        myDataSource.setPassword(env.getProperty("jdbc.password"));

        // set connection pool props
        myDataSource.setInitialPoolSize(getIntProperty("connection.pool.initialPoolSize"));
        myDataSource.setMinPoolSize(getIntProperty("connection.pool.minPoolSize"));
        myDataSource.setMaxPoolSize(getIntProperty("connection.pool.maxPoolSize"));     
        myDataSource.setMaxIdleTime(getIntProperty("connection.pool.maxIdleTime"));

        return myDataSource;
    }

    private Properties getHibernateProperties() {

        // set hibernate properties
        Properties props = new Properties();

        props.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect"));
        props.setProperty("hibernate.show_sql", env.getProperty("hibernate.show_sql"));

        return props;               
    }

    // define a bean for our security datasource

    @Bean
    public DataSource securityDataSource() {

        // create connection pool
        ComboPooledDataSource securityDataSource
                                    = new ComboPooledDataSource();

        // set the jdbc driver class

        try {
            securityDataSource.setDriverClass(env.getProperty("security.jdbc.driver"));
        } catch (PropertyVetoException exc) {
            throw new RuntimeException(exc);
        }

        // log the connection props
        // for sanity's sake, log this info
        // just to make sure we are REALLY reading data from properties file

        logger.info(">>> security.jdbc.url=" + env.getProperty("security.jdbc.url"));
        logger.info(">>> security.jdbc.user=" + env.getProperty("security.jdbc.user"));


        // set database connection props

        securityDataSource.setJdbcUrl(env.getProperty("security.jdbc.url"));
        securityDataSource.setUser(env.getProperty("security.jdbc.user"));
        securityDataSource.setPassword(env.getProperty("security.jdbc.password"));

        // set connection pool props

        securityDataSource.setInitialPoolSize(
                getIntProperty("security.connection.pool.initialPoolSize"));

        securityDataSource.setMinPoolSize(
                getIntProperty("security.connection.pool.minPoolSize"));

        securityDataSource.setMaxPoolSize(
                getIntProperty("security.connection.pool.maxPoolSize"));

        securityDataSource.setMaxIdleTime(
                getIntProperty("security.connection.pool.maxIdleTime"));

        return securityDataSource;
    }

    // need a helper method 
    // read environment property and convert to int

    private int getIntProperty(String propName) {

        String propVal = env.getProperty(propName);

        // now convert to int
        int intPropVal = Integer.parseInt(propVal);

        return intPropVal;
    }   

    @Bean
    public LocalSessionFactoryBean sessionFactory(){

        // create session factorys
        LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();

        // set the properties
        sessionFactory.setDataSource(myDataSource());
        sessionFactory.setPackagesToScan(env.getProperty("hibernate.packagesToScan"));
        sessionFactory.setHibernateProperties(getHibernateProperties());

        return sessionFactory;
    }

    @Bean
    @Autowired
    public HibernateTransactionManager transactionManager(SessionFactory sessionFactory) {

        // setup transaction manager based on session factory
        HibernateTransactionManager txManager = new HibernateTransactionManager();
        txManager.setSessionFactory(sessionFactory);

        return txManager;
    }   

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry
          .addResourceHandler("/resources/**")
          .addResourceLocations("/resources/"); 


    }   
}

春季安全性

@Configuration
@EnableWebSecurity
public class DemoSecurityConfig extends WebSecurityConfigurerAdapter {

    // add a reference to our security data source

    @Autowired
    private DataSource securityDataSource;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {

        // use jdbc authentication ... oh yeah!!!

        auth.jdbcAuthentication().dataSource(securityDataSource);

    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.authorizeRequests()
        //  .antMatchers("/recruit/showForm*").hasAnyRole("MANAGER", "ADMIN")
        //  .antMatchers("/client/showForm*").hasAnyRole("MANAGER", "ADMIN")
        //  .antMatchers("/recruit/save*").hasAnyRole("MANAGER", "ADMIN")
        //  .antMatchers("/client/save*").hasAnyRole("MANAGER", "ADMIN")
        //  .antMatchers("/recruit/delete").hasRole("ADMIN")
        //  .antMatchers("/client/delete").hasRole("ADMIN")
            .antMatchers("/recruit/**").authenticated()
            .antMatchers("/client/**").authenticated()
            .anyRequest().permitAll()
            .antMatchers("/resources/**").permitAll()
            .and()
            .formLogin()
                .loginPage("/showMyLoginPage")
                .loginProcessingUrl("/authenticateTheUser")
                .permitAll()
            .and()
            .logout().permitAll()
            .and()
            .exceptionHandling().accessDeniedPage("/access-denied");

    }

    @Bean
    public UserDetailsManager userDetailsManager() {

        JdbcUserDetailsManager jdbcUserDetailsManager = new JdbcUserDetailsManager();

        jdbcUserDetailsManager.setDataSource(securityDataSource);

        return jdbcUserDetailsManager; 
    }

}

EmailController类

@Controller
public class EmailController {

    static String emailToRecipient, emailSubject, emailMessage;
    static final String emailFromRecipient = "<!-- Source Email Address -->";

    static ModelAndView modelViewObj;

    @Autowired
    private JavaMailSender mailSenderObj;

    @RequestMapping(value = {"/", "emailForm"}, method = RequestMethod.GET)
    public ModelAndView showEmailForm(ModelMap model) {
        modelViewObj = new ModelAndView("emailForm");
        return  modelViewObj;       
    }

    // This Method Is Used To Prepare The Email Message And Send It To The Client
    @RequestMapping(value = "sendEmail", method = RequestMethod.POST)
    public ModelAndView sendEmailToClient(HttpServletRequest request, final @RequestParam CommonsMultipartFile attachFileObj) {

        // Reading Email Form Input Parameters      
        emailSubject = request.getParameter("subject");
        emailMessage = request.getParameter("message");
        emailToRecipient = request.getParameter("mailTo");

        // Logging The Email Form Parameters For Debugging Purpose
        System.out.println("\nReceipient?= " + emailToRecipient + ", Subject?= " + emailSubject + ", Message?= " + emailMessage + "\n");

        mailSenderObj.send(new MimeMessagePreparator() {
            public void prepare(MimeMessage mimeMessage) throws Exception {

                MimeMessageHelper mimeMsgHelperObj = new MimeMessageHelper(mimeMessage, true, "UTF-8");             
                mimeMsgHelperObj.setTo(emailToRecipient);
                mimeMsgHelperObj.setFrom(emailFromRecipient);               
                mimeMsgHelperObj.setText(emailMessage);
                mimeMsgHelperObj.setSubject(emailSubject);

                // Determine If There Is An File Upload. If Yes, Attach It To The Client Email              
                if ((attachFileObj != null) && (attachFileObj.getSize() > 0) && (!attachFileObj.equals(""))) {
                    System.out.println("\nAttachment Name?= " + attachFileObj.getOriginalFilename() + "\n");
                    mimeMsgHelperObj.addAttachment(attachFileObj.getOriginalFilename(), new InputStreamSource() {                   
                        public InputStream getInputStream() throws IOException {
                            return attachFileObj.getInputStream();
                        }
                    });
                } else {
                    System.out.println("\nNo Attachment Is Selected By The User. Sending Text Email!\n");
                }
            }
        });
        System.out.println("\nMessage Send Successfully.... Hurrey!\n");

        modelViewObj = new ModelAndView("welcome-contact-page-success","messageObj","Thank You! Your Email Has Been Sent!");
        return  modelViewObj;   
    }
}

emailForm.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>Spring MVC Email Example</title>
        <style type="text/css">
            #sendEmailBtn {
                float: left;
                margin-top: 22px;
            }
        </style>
    </head>

    <body>
        <center>
            <h2>Spring MVC Email Example</h2>
            <form id="sendEmailForm" method="post" action="sendEmail" enctype="multipart/form-data">
                <table id="emailFormBeanTable" border="0" width="80%">
                    <tr>
                        <td>Email To: </td>
                        <td><input id="receiverMail" type="text" name="mailTo" size="65" /></td>
                    </tr>
                    <tr>
                        <td>Subject: </td>
                        <td><input id="mailSubject" type="text" name="subject" size="65" /></td>
                    </tr>
                    <tr>
                        <td>Message: </td>
                        <td><textarea id="mailMessage" cols="50" rows="10" name="message"></textarea></td>
                    </tr>
                    <tr>
                        <td>Attachment: </td>
                        <td><input id="mailAttachment" type="file" name="attachFileObj" size="60" /></td>
                    </tr>
                    <tr>
                        <td colspan="2" align="center"><input id="sendEmailBtn" type="submit" value="Send Email" /></td>
                    </tr>
                </table>
            </form>
        </center>
    </body>
</html>

我输入表格,而不是发送到成功页面或错误页面,我最终看到的是上面链接的图片,错误代码403不支持POST。

0 个答案:

没有答案
相关问题